[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

18. Macros

Macros enable you to define new control constructs and other language features. A macro is defined much like a function, but instead of telling how to compute a value, it tells how to compute another Lisp expression which will in turn compute the value. We call this expression the expansion of the macro.

Macros can do this because they operate on the unevaluated expressions for the arguments, not on the argument values as functions do. They can therefore construct an expansion containing these argument expressions or parts of them.

If you are using a macro to do something an ordinary function could do, just for the sake of speed, consider using an inline function instead. See section 17.9 Inline Functions.

18.1 A Simple Example of a Macro  A basic example.
18.2 Expansion of a Macro Call  How, when and why macros are expanded.
18.3 Macros and Byte Compilation  How macros are expanded by the compiler.
18.4 Defining Macros  How to write a macro definition.
18.5 Backquote  Easier construction of list structure.
18.6 Common Problems Using Macros  Don't evaluate the macro arguments too many times. Don't hide the user's variables.

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

18.1 A Simple Example of a Macro

Suppose we would like to define a Lisp construct to increment a variable value, much like the ++ operator in C. We would like to write (inc x) and have the effect of (setq x (1+ x)). Here's a macro definition that does the job:

(defmacro inc (var)
   (list 'setq var (list '1+ var)))

When this is called with (inc x), the argument var has the value x---not the value of x. The body of the macro uses this to construct the expansion, which is (setq x (1+ x)). Once the macro definition returns this expansion, Lisp proceeds to evaluate it, thus incrementing x.

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

18.2 Expansion of a Macro Call

A macro call looks just like a function call in that it is a list which starts with the name of the macro. The rest of the elements of the list are the arguments of the macro.

Evaluation of the macro call begins like evaluation of a function call except for one crucial difference: the macro arguments are the actual expressions appearing in the macro call. They are not evaluated before they are given to the macro definition. By contrast, the arguments of a function are results of evaluating the elements of the function call list.

Having obtained the arguments, Lisp invokes the macro definition just as a function is invoked. The argument variables of the macro are bound to the argument values from the macro call, or to a list of them in the case of a &rest argument. And the macro body executes and returns its value just as a function body does.

The second crucial difference between macros and functions is that the value returned by the macro body is not the value of the macro call. Instead, it is an alternate expression for computing that value, also known as the expansion of the macro. The Lisp interpreter proceeds to evaluate the expansion as soon as it comes back from the macro.

Since the expansion is evaluated in the normal manner, it may contain calls to other macros. It may even be a call to the same macro, though this is unusual.

You can see the expansion of a given macro call by calling macroexpand.

Function: macroexpand form &optional environment
This function expands form, if it is a macro call. If the result is another macro call, it is expanded in turn, until something which is not a macro call results. That is the value returned by macroexpand. If form is not a macro call to begin with, it is returned as given.

Note that macroexpand does not look at the subexpressions of form (although some macro definitions may do so). Even if they are macro calls themselves, macroexpand does not expand them.

The function macroexpand does not expand calls to inline functions. Normally there is no need for that, since a call to an inline function is no harder to understand than a call to an ordinary function.

If environment is provided, it specifies an alist of macro definitions that shadow the currently defined macros. Byte compilation uses this feature.

(defmacro inc (var)
    (list 'setq var (list '1+ var)))
     => inc

(macroexpand '(inc r))
     => (setq r (1+ r))

(defmacro inc2 (var1 var2)
    (list 'progn (list 'inc var1) (list 'inc var2)))
     => inc2

(macroexpand '(inc2 r s))
     => (progn (inc r) (inc s))  ; inc not expanded here.

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

18.3 Macros and Byte Compilation

You might ask why we take the trouble to compute an expansion for a macro and then evaluate the expansion. Why not have the macro body produce the desired results directly? The reason has to do with compilation.

When a macro call appears in a Lisp program being compiled, the Lisp compiler calls the macro definition just as the interpreter would, and receives an expansion. But instead of evaluating this expansion, it compiles the expansion as if it had appeared directly in the program. As a result, the compiled code produces the value and side effects intended for the macro, but executes at full compiled speed. This would not work if the macro body computed the value and side effects itself--they would be computed at compile time, which is not useful.

In order for compilation of macro calls to work, the macros must be defined in Lisp when the calls to them are compiled. The compiler has a special feature to help you do this: if a file being compiled contains a defmacro form, the macro is defined temporarily for the rest of the compilation of that file. To use this feature, you must define the macro in the same file where it is used and before its first use.

Byte-compiling a file executes any require calls at top-level in the file. This is in case the file needs the required packages for proper compilation. One way to ensure that necessary macro definitions are available during compilation is to require the files that define them (see section 20.4 Features). To avoid loading the macro definition files when someone runs the compiled program, write eval-when-compile around the require calls (see section 21.6 Evaluation During Compilation).

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

18.4 Defining Macros

A Lisp macro is a list whose CAR is macro. Its CDR should be a function; expansion of the macro works by applying the function (with apply) to the list of unevaluated argument-expressions from the macro call.

It is possible to use an anonymous Lisp macro just like an anonymous function. It doesn't make sense to pass an anonymous macro to functionals such as mapcar, and it is usually more readable to use macrolet to make a local macro definition, and call that. But if, for whatever reason, macrolet is not available, code like the following may be useful:

((macro . (lambda (&rest arguments)
	    (let (res)
	      (while (consp arguments)
		(setq res (cons (cons 'put
				      (cons (list 'quote (car arguments))
					    '((quote my-property) t)))
		      arguments (cdr arguments)))
	      (cons 'progn res))))
 + - = floor ceiling round)

This expands to:

  (put 'round 'my-property t)
  (put 'ceiling 'my-property t)
  (put 'floor 'my-property t)
  (put '= 'my-property t)
  (put '- 'my-property t)
  (put '+ 'my-property t))

In practice, almost all Lisp macros have names, and they are usually defined with the special operator defmacro.

Special Operator: defmacro name argument-list body-forms...
defmacro defines the symbol name as a macro that looks like this:

(macro lambda argument-list . body-forms)

This macro object is stored in the function cell of name. The value returned by evaluating the defmacro form is name, but usually we ignore this value.

The shape and meaning of argument-list is the same as in a function, and the keywords &rest and &optional may be used (see section 17.2.3 Advanced Features of Argument Lists). Macros may have a documentation string, but any interactive declaration is ignored since macros cannot be called interactively.

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

18.5 Backquote

Macros often need to construct large list structures from a mixture of constants and nonconstant parts. To make this easier, use the macro ``' (often called backquote).

Backquote allows you to quote a list, but selectively evaluate elements of that list. In the simplest case, it is identical to the special operator quote (see section 14.4 Quoting). For example, these two forms yield identical results:

`(a list of (+ 2 3) elements)
     => (a list of (+ 2 3) elements)
'(a list of (+ 2 3) elements)
     => (a list of (+ 2 3) elements)

The special marker `,' inside of the argument to backquote indicates a value that isn't constant. Backquote evaluates the argument of `,' and puts the value in the list structure:

(list 'a 'list 'of (+ 2 3) 'elements)
     => (a list of 5 elements)
`(a list of ,(+ 2 3) elements)
     => (a list of 5 elements)

You can also splice an evaluated value into the resulting list, using the special marker `,@'. The elements of the spliced list become elements at the same level as the other elements of the resulting list. The equivalent code without using ``' is often unreadable. Here are some examples:

(setq some-list '(2 3))
     => (2 3)
(cons 1 (append some-list '(4) some-list))
     => (1 2 3 4 2 3)
`(1 ,@some-list 4 ,@some-list)
     => (1 2 3 4 2 3)

(setq list '(hack foo bar))
     => (hack foo bar)
(cons 'use
  (cons 'the
    (cons 'words (append (cdr list) '(as elements)))))
     => (use the words foo bar as elements)
`(use the words ,@(cdr list) as elements)
     => (use the words foo bar as elements)

In older versions of Emacs (before XEmacs 19.12 or FSF Emacs version 19.29), ``' used a different syntax which required an extra level of parentheses around the entire backquote construct. Likewise, each `,' or `,@' substitution required an extra level of parentheses surrounding both the `,' or `,@' and the following expression. The old syntax required whitespace between the ``', `,' or `,@' and the following expression.

This syntax is still accepted, but no longer recommended except for compatibility with old Emacs versions.

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

18.6 Common Problems Using Macros

The basic facts of macro expansion have counterintuitive consequences. This section describes some important consequences that can lead to trouble, and rules to follow to avoid trouble.

18.6.1 Evaluating Macro Arguments Repeatedly  The expansion should evaluate each macro arg once.
18.6.2 Local Variables in Macro Expansions  Local variable bindings in the expansion require special care.
18.6.3 Evaluating Macro Arguments in Expansion  Don't evaluate them; put them in the expansion.
18.6.4 How Many Times is the Macro Expanded?  Avoid depending on how many times expansion is done.

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

18.6.1 Evaluating Macro Arguments Repeatedly

When defining a macro you must pay attention to the number of times the arguments will be evaluated when the expansion is executed. The following macro (used to facilitate iteration) illustrates the problem. This macro allows us to write a simple "for" loop such as one might find in Pascal.

(defmacro for (var from init to final do &rest body)
  "Execute a simple \"for\" loop.
For example, (for i from 1 to 10 do (print i))."
  (list 'let (list (list var init))
        (cons 'while (cons (list '<= var final)
                           (append body (list (list 'inc var)))))))
=> for

(for i from 1 to 3 do
   (setq square (* i i))
   (princ (format "\n%d %d" i square)))
(let ((i 1))
  (while (<= i 3)
    (setq square (* i i))
    (princ (format "%d      %d" i square))
    (inc i)))

     -|1       1
     -|2       4
     -|3       9
=> nil

(The arguments from, to, and do in this macro are "syntactic sugar"; they are entirely ignored. The idea is that you will write noise words (such as from, to, and do) in those positions in the macro call.)

Here's an equivalent definition simplified through use of backquote:

(defmacro for (var from init to final do &rest body)
  "Execute a simple \"for\" loop.
For example, (for i from 1 to 10 do (print i))."
  `(let ((,var ,init))
     (while (<= ,var ,final)
       (inc ,var))))

Both forms of this definition (with backquote and without) suffer from the defect that final is evaluated on every iteration. If final is a constant, this is not a problem. If it is a more complex form, say (long-complex-calculation x), this can slow down the execution significantly. If final has side effects, executing it more than once is probably incorrect.

A well-designed macro definition takes steps to avoid this problem by producing an expansion that evaluates the argument expressions exactly once unless repeated evaluation is part of the intended purpose of the macro. Here is a correct expansion for the for macro:

(let ((i 1)
      (max 3))
  (while (<= i max)
    (setq square (* i i))
    (princ (format "%d      %d" i square))
    (inc i)))

Here is a macro definition that creates this expansion:

(defmacro for (var from init to final do &rest body)
  "Execute a simple for loop: (for i from 1 to 10 do (print i))."
  `(let ((,var ,init)
         (max ,final))
     (while (<= ,var max)
       (inc ,var))))

Unfortunately, this introduces another problem. Proceed to the following node.

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

18.6.2 Local Variables in Macro Expansions

In the previous section, the definition of for was fixed as follows to make the expansion evaluate the macro arguments the proper number of times:

(defmacro for (var from init to final do &rest body)
  "Execute a simple for loop: (for i from 1 to 10 do (print i))."
  `(let ((,var ,init)
         (max ,final))
     (while (<= ,var max)
       (inc ,var))))

The new definition of for has a new problem: it introduces a local variable named max which the user does not expect. This causes trouble in examples such as the following:

(let ((max 0))
  (for x from 0 to 10 do
    (let ((this (frob x)))
      (if (< max this)
          (setq max this)))))

The references to max inside the body of the for, which are supposed to refer to the user's binding of max, really access the binding made by for.

The way to correct this is to use an uninterned symbol instead of max (see section 13.3 Creating and Interning Symbols). The uninterned symbol can be bound and referred to just like any other symbol, but since it is created by for, we know that it cannot already appear in the user's program. Since it is not interned, there is no way the user can put it into the program later. It will never appear anywhere except where put by for. Here is a definition of for that works this way:

(defmacro for (var from init to final do &rest body)
  "Execute a simple for loop: (for i from 1 to 10 do (print i))."
  (let ((tempvar (make-symbol "max")))
    `(let ((,var ,init)
           (,tempvar ,final))
       (while (<= ,var ,tempvar)
         (inc ,var)))))

This creates an uninterned symbol named max and puts it in the expansion instead of the usual interned symbol max that appears in expressions ordinarily.

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

18.6.3 Evaluating Macro Arguments in Expansion

Another problem can happen if you evaluate any of the macro argument expressions during the computation of the expansion, such as by calling eval (see section 14.2 Eval). If the argument is supposed to refer to the user's variables, you may have trouble if the user happens to use a variable with the same name as one of the macro arguments. Inside the macro body, the macro argument binding is the most local binding of this variable, so any references inside the form being evaluated do refer to it. Here is an example:

(defmacro foo (a)
  (list 'setq (eval a) t))
     => foo
(setq x 'b)
(foo x) ==> (setq b t)
     => t                  ; and b has been set.
;; but
(setq a 'c)
(foo a) ==> (setq a t)
     => t                  ; but this set a, not c.

It makes a difference whether the user's variable is named a or x, because a conflicts with the macro argument variable a.

Another reason not to call eval in a macro definition is that it probably won't do what you intend in a compiled program. The byte-compiler runs macro definitions while compiling the program, when the program's own computations (which you might have wished to access with eval) don't occur and its local variable bindings don't exist.

The safe way to work with the run-time value of an expression is to put the expression into the macro expansion, so that its value is computed as part of executing the expansion.

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

18.6.4 How Many Times is the Macro Expanded?

Occasionally problems result from the fact that a macro call is expanded each time it is evaluated in an interpreted function, but is expanded only once (during compilation) for a compiled function. If the macro definition has side effects, they will work differently depending on how many times the macro is expanded.

In particular, constructing objects is a kind of side effect. If the macro is called once, then the objects are constructed only once. In other words, the same structure of objects is used each time the macro call is executed. In interpreted operation, the macro is reexpanded each time, producing a fresh collection of objects each time. Usually this does not matter--the objects have the same contents whether they are shared or not. But if the surrounding program does side effects on the objects, it makes a difference whether they are shared. Here is an example:

(defmacro empty-object ()
  (list 'quote (cons nil nil)))

(defun initialize (condition)
  (let ((object (empty-object)))
    (if condition
        (setcar object condition))

If initialize is interpreted, a new list (nil) is constructed each time initialize is called. Thus, no side effect survives between calls. If initialize is compiled, then the macro empty-object is expanded during compilation, producing a single "constant" (nil) that is reused and altered each time initialize is called.

One way to avoid pathological cases like this is to think of empty-object as a funny kind of constant, not as a memory allocation construct. You wouldn't use setcar on a constant such as '(nil), so naturally you won't use it on (empty-object) either.

[ << ] [ >> ]           [Top] [Contents] [Index] [ ? ]

This document was generated by XEmacs Webmaster on August, 3 2012 using texi2html