Metaprogramming

From Rosetta Code
Task
Metaprogramming
You are encouraged to solve this task according to the task description, using any language you may know.

Name and briefly demonstrate any support your language has for metaprogramming. Your demonstration may take the form of cross-references to other tasks on Rosetta Code. When possible, provide links to relevant documentation.

For the purposes of this task, "support for metaprogramming" means any way the user can effectively modify the language's syntax that's built into the language (like Lisp macros) or that's conventionally used with the language (like the C preprocessor). Such facilities need not be very powerful: even user-defined infix operators count. On the other hand, in general, neither operator overloading nor eval count. The task author acknowledges that what qualifies as metaprogramming is largely a judgment call.

Perl

You can textually transform code with a source filter, a module that when used modifies the following lines of source. Filter::Util::Call provides a general means of writing source filters. Filter::Simple is an interface to Filter::Util::Call that lets you elide a lot of boilerplate code. More important, Filter::Simple can hide the contents of quoting constructs from your filter, obviating the biggest dangers of textual metaprogramming. For example, given the following module:

<lang perl>package UnicodeEllipsis;

use Filter::Simple;

FILTER_ONLY code => sub { s/…/../g };</lang>

this program:

<lang perl>use UnicodeEllipsis;

print join(' … ', 1 … 5), "\n";</lang>

prints:

 1 … 2 … 3 … 4 … 5

Devel::Declare lets you define a new keyword by setting up a hook to be run whenever the parser encounters a bareword of your choice. Devel::Declare is powerful, but it has a reputation for being difficult to understand. See this blog post for a relatively simple usage example.

Python

Metaprogramming is frowned on in Python and considered un-pythonic. The only widely known example of metaprogramming in Python was an inplementtion of a goto (and comefrom) keyword done as an April-fools joke.