Next: , Previous: , Up: Macros   [Contents][Index]

5.10.3 Macro Expansion

When a macro call is detected (see List Forms) the function which is the cdr of the macro’s definition (see Defining Macros) is applied to the macro call’s arguments. Unlike in a function call, the arguments are not evaluated, the actual forms are the arguments to the macro’s expansion function. This is to allow these forms to be rearranged by the macro’s expansion function, creating the form that will finally be evaluated.

There is a function which performs macro expansion, its main use is to let the Lisp compiler expand macro calls at compile time.

Function: macroexpand form #!optional environment

If form is a macro call macroexpand will expand that call by calling the macro’s expansion function (the cdr of the macro definition). If this expansion is another macro call the process is repeated until an expansion is obtained which is not a macro call, this form is then returned.

The optional environment argument is a function to call to do the actual expansion.

(defmacro when (condition #!rest body)
  "Evaluates condition, if it's true evaluates the body
  (list 'if condition (cons 'progn body)))
    ⇒ when

(macroexpand '(when x (setq foo bar)))
    ⇒ (cond (x (progn (setq foo bar))))

While a macro is being expanded, the special variable macro-environment is bound to value of the environment parameter in the containing call to macroexpand. This allows macros to expand inner macros correctly.

Function: macroexpand-1 form #!optional environment

Similar to macroexpand, but only a single macro expansion is ever performed, i.e. if form is a macro call the result of expanding that call will be returned, otherwise form is returned.

(macroexpand-1 '(when x (setq foo bar)))
    ⇒ (if x (progn (setq foo bar)))

Next: , Previous: , Up: Macros   [Contents][Index]