Node:Macros, Next:C interface, Previous:Keyword tuples, Up:Functions
A macro is a function that is called at compile time. It is given some input expressions, and uses them to create a new expression. That expression is then compiled as if it were part of the original input.
A macro definition has the form:
:(macro left_arg name right_args)=bodyThis defines name to be a macro function bound to name. A macro function is just like a regular function, except that it is executed by the compiler at bind-time, not at run-time. (Bind-time is the stage after parsing. and before execution or dumping.) When the compiler sees name, it calls the function, passing the other expressions in the same application as parameters. The result should be an expression, which is then traversed further.
An example should make the idea clear, but first we mention
the parse
function which is very useful when writing macros.
parse arg1 ... argn | Function |
Each argi must be either a string or an expression. Informally, all the arguments are concatenated together. The result is parsed, yielding an expression. When, during the parse, an argi that is an expression is seen, that expression is inserted into the resulting expression. |
Here are the actual definitions from the Q runtime system,
defining the cd
macro, which is use to change working directories.
:|(macro cd :x@)= parse "__cd (quote " x@ ")" :|(__cd :args)=external CdActionThe function
__cd
does the actual "work:" Its argument
is a string vector, usually of length one, which names
the desired new directory.
An instance of cd
:
cd ~/binThe binder invokes the
cd
macro with an array
whose single element is the expression parsed for ~/bin
.
The parse
function is invoked, and the result
is as if the user had written:
__cd (quote ~bin)which evaluates to the same as:
__cd ["~bin"]