Common Lisp the Language, 2nd Edition

Next: Macro Definition Up: Common Lisp the Language Previous: Dynamic Non-Local Exits

# 8. Macros

The Common Lisp macro facility allows the user to define arbitrary functions that convert certain Lisp forms into different forms before evaluating or compiling them. This is done at the expression level, not at the character-string level as in most other languages. Macros are important in the writing of good code: they make it possible to write code that is clear and elegant at the user level but that is converted to a more complex or more efficient internal form for execution.

When `eval` is given a list whose car is a symbol, it looks for local definitions of that symbol (by `flet`, `labels`, and `macrolet`); if that fails, it looks for a global definition. If the definition is a macro definition, then the original list is said to be a macro call. Associated with the definition will be a function of two arguments, called the expansion function. This function is called with the entire macro call as its first argument (the second argument is a lexical environment); it must return some new Lisp form, called the expansion of the macro call. (Actually, a more general mechanism is involved; see `macroexpand`.) This expansion is then evaluated in place of the original form.

When a function is being compiled, any macros it contains are expanded at compilation time. This means that a macro definition must be seen by the compiler before the first use of the macro.

More generally, an implementation of Common Lisp has great latitude in deciding exactly when to expand macro calls within a program. For example, it is acceptable for the `defun` special form to expand all macro calls within its body at the time the `defun` form is executed and record the fully expanded body as the body of the function being defined. (An implementation might even choose always to compile functions defined by `defun`, even when operating in an ``interpretive'' mode.)

Macros should be written so as to depend as little as possible on the execution environment to produce a correct expansion. To ensure consistent behavior, it is best to ensure that all macro definitions are available, whether to the interpreter or compiler, before any code containing calls to those macros is introduced.

In Common Lisp, macros are not functions. In particular, macros cannot be used as functional arguments to such functions as `apply`, `funcall`, or `map`; in such situations, the list representing the ``original macro call'' does not exist, and cannot exist, because in some sense the arguments have already been evaluated.

- Macro Definition
- Macro Expansion
- Destructuring
- Compiler Macros
- Environments

Next: Macro Definition Up: Common Lisp the Language Previous: Dynamic Non-Local Exits