@c -*-texinfo-*-@c This is part of the GNU Emacs Lisp Reference Manual.@c Copyright (C) 1990, 1991, 1992, 1993, 1994, 1995, 1998 Free Software Foundation, Inc. @c See the file elisp.texi for copying conditions.@setfilename ../info/macros@node Macros, Customization, Functions, Top@chapter Macros@cindex macros @dfn{Macros} enable you to define new control constructs and otherlanguage features. A macro is defined much like a function, but insteadof telling how to compute a value, it tells how to compute another Lispexpression which will in turn compute the value. We call thisexpression the @dfn{expansion} of the macro. Macros can do this because they operate on the unevaluated expressionsfor the arguments, not on the argument values as functions do. They cantherefore construct an expansion containing these argument expressionsor parts of them. If you are using a macro to do something an ordinary function coulddo, just for the sake of speed, consider using an inline functioninstead. @xref{Inline Functions}.@menu* Simple Macro:: A basic example.* Expansion:: How, when and why macros are expanded.* Compiling Macros:: How macros are expanded by the compiler.* Defining Macros:: How to write a macro definition.* Backquote:: Easier construction of list structure.* Problems with Macros:: Don't evaluate the macro arguments too many times. Don't hide the user's variables.@end menu@node Simple Macro@section A Simple Example of a Macro Suppose we would like to define a Lisp construct to increment avariable value, much like the @code{++} operator in C. We would like towrite @code{(inc x)} and have the effect of @code{(setq x (1+ x))}.Here's a macro definition that does the job:@findex inc@example@group(defmacro inc (var) (list 'setq var (list '1+ var)))@end group@end example When this is called with @code{(inc x)}, the argument @var{var} is thesymbol @code{x}---@emph{not} the @emph{value} of @code{x}, as it wouldbe in a function. The body of the macro uses this to construct theexpansion, which is @code{(setq x (1+ x))}. Once the macro definitionreturns this expansion, Lisp proceeds to evaluate it, thus incrementing@code{x}.@node Expansion@section Expansion of a Macro Call@cindex expansion of macros@cindex macro call A macro call looks just like a function call in that it is a list whichstarts with the name of the macro. The rest of the elements of the listare the arguments of the macro. Evaluation of the macro call begins like evaluation of a function callexcept for one crucial difference: the macro arguments are the actualexpressions appearing in the macro call. They are not evaluated beforethey are given to the macro definition. By contrast, the arguments of afunction are results of evaluating the elements of the function calllist. Having obtained the arguments, Lisp invokes the macro definition justas a function is invoked. The argument variables of the macro are boundto the argument values from the macro call, or to a list of them in thecase of a @code{&rest} argument. And the macro body executes andreturns its value just as a function body does. The second crucial difference between macros and functions is that thevalue returned by the macro body is not the value of the macro call.Instead, it is an alternate expression for computing that value, alsoknown as the @dfn{expansion} of the macro. The Lisp interpreterproceeds to evaluate the expansion as soon as it comes back from themacro. Since the expansion is evaluated in the normal manner, it may containcalls to other macros. It may even be a call to the same macro, thoughthis is unusual. You can see the expansion of a given macro call by calling@code{macroexpand}.@defun macroexpand form &optional environment@cindex macro expansionThis function expands @var{form}, if it is a macro call. If the resultis another macro call, it is expanded in turn, until something which isnot a macro call results. That is the value returned by@code{macroexpand}. If @var{form} is not a macro call to begin with, itis returned as given.Note that @code{macroexpand} does not look at the subexpressions of@var{form} (although some macro definitions may do so). Even if theyare macro calls themselves, @code{macroexpand} does not expand them.The function @code{macroexpand} does not expand calls to inline functions.Normally there is no need for that, since a call to an inline function isno harder to understand than a call to an ordinary function.If @var{environment} is provided, it specifies an alist of macrodefinitions that shadow the currently defined macros. Byte compilationuses this feature.@smallexample@group(defmacro inc (var) (list 'setq var (list '1+ var))) @result{} inc@end group@group(macroexpand '(inc r)) @result{} (setq r (1+ r))@end group@group(defmacro inc2 (var1 var2) (list 'progn (list 'inc var1) (list 'inc var2))) @result{} inc2@end group@group(macroexpand '(inc2 r s)) @result{} (progn (inc r) (inc s)) ; @r{@code{inc} not expanded here.}@end group@end smallexample@end defun@node Compiling Macros@section Macros and Byte Compilation@cindex byte-compiling macros You might ask why we take the trouble to compute an expansion for amacro and then evaluate the expansion. Why not have the macro bodyproduce the desired results directly? The reason has to do withcompilation. When a macro call appears in a Lisp program being compiled, the Lispcompiler calls the macro definition just as the interpreter would, andreceives an expansion. But instead of evaluating this expansion, itcompiles the expansion as if it had appeared directly in the program.As a result, the compiled code produces the value and side effectsintended for the macro, but executes at full compiled speed. This wouldnot work if the macro body computed the value and side effectsitself---they would be computed at compile time, which is not useful. In order for compilation of macro calls to work, the macros mustalready be defined in Lisp when the calls to them are compiled. Thecompiler has a special feature to help you do this: if a file beingcompiled contains a @code{defmacro} form, the macro is definedtemporarily for the rest of the compilation of that file. To make thisfeature work, you must put the @code{defmacro} in the same file where itis used, and before its first use. Byte-compiling a file executes any @code{require} calls at top-levelin the file. This is in case the file needs the required packages forproper compilation. One way to ensure that necessary macro definitionsare available during compilation is to require the files that definethem (@pxref{Named Features}). To avoid loading the macro definition fileswhen someone @emph{runs} the compiled program, write@code{eval-when-compile} around the @code{require} calls (@pxref{EvalDuring Compile}).@node Defining Macros@section Defining Macros A Lisp macro is a list whose @sc{car} is @code{macro}. Its @sc{cdr} shouldbe a function; expansion of the macro works by applying the function(with @code{apply}) to the list of unevaluated argument-expressionsfrom the macro call. It is possible to use an anonymous Lisp macro just like an anonymousfunction, but this is never done, because it does not make sense to passan anonymous macro to functionals such as @code{mapcar}. In practice,all Lisp macros have names, and they are usually defined with thespecial form @code{defmacro}.@defspec defmacro name argument-list body-forms@dots{}@code{defmacro} defines the symbol @var{name} as a macro that lookslike this:@example(macro lambda @var{argument-list} . @var{body-forms})@end example(Note that the @sc{cdr} of this list is a function---a lambda expression.)This macro object is stored in the function cell of @var{name}. Thevalue returned by evaluating the @code{defmacro} form is @var{name}, butusually we ignore this value.The shape and meaning of @var{argument-list} is the same as in afunction, and the keywords @code{&rest} and @code{&optional} may be used(@pxref{Argument List}). Macros may have a documentation string, butany @code{interactive} declaration is ignored since macros cannot becalled interactively.@end defspec@node Backquote@section Backquote@cindex backquote (list substitution)@cindex ` (list substitution)@findex ` Macros often need to construct large list structures from a mixture ofconstants and nonconstant parts. To make this easier, use the @samp{`}syntax (usually called @dfn{backquote}). Backquote allows you to quote a list, but selectively evaluateelements of that list. In the simplest case, it is identical to thespecial form @code{quote} (@pxref{Quoting}). For example, thesetwo forms yield identical results:@example@group`(a list of (+ 2 3) elements) @result{} (a list of (+ 2 3) elements)@end group@group'(a list of (+ 2 3) elements) @result{} (a list of (+ 2 3) elements)@end group@end example@findex , @r{(with Backquote)}The special marker @samp{,} inside of the argument to backquoteindicates a value that isn't constant. Backquote evaluates theargument of @samp{,} and puts the value in the list structure:@example@group(list 'a 'list 'of (+ 2 3) 'elements) @result{} (a list of 5 elements)@end group@group`(a list of ,(+ 2 3) elements) @result{} (a list of 5 elements)@end group@end example Substitution with @samp{,} is allowed at deeper levels of the liststructure also. For example:@example@group(defmacro t-becomes-nil (variable) `(if (eq ,variable t) (setq ,variable nil)))@end group@group(t-becomes-nil foo) @equiv{} (if (eq foo t) (setq foo nil))@end group@end example@findex ,@@ @r{(with Backquote)}@cindex splicing (with backquote) You can also @dfn{splice} an evaluated value into the resulting list,using the special marker @samp{,@@}. The elements of the spliced listbecome elements at the same level as the other elements of the resultinglist. The equivalent code without using @samp{`} is often unreadable.Here are some examples:@example@group(setq some-list '(2 3)) @result{} (2 3)@end group@group(cons 1 (append some-list '(4) some-list)) @result{} (1 2 3 4 2 3)@end group@group`(1 ,@@some-list 4 ,@@some-list) @result{} (1 2 3 4 2 3)@end group@group(setq list '(hack foo bar)) @result{} (hack foo bar)@end group@group(cons 'use (cons 'the (cons 'words (append (cdr list) '(as elements))))) @result{} (use the words foo bar as elements)@end group@group`(use the words ,@@(cdr list) as elements) @result{} (use the words foo bar as elements)@end group@end exampleIn old Emacs versions, before version 19.29, @samp{`} used a differentsyntax which required an extra level of parentheses around the entirebackquote construct. Likewise, each @samp{,} or @samp{,@@} substitutionrequired an extra level of parentheses surrounding both the @samp{,} or@samp{,@@} and the following expression. The old syntax requiredwhitespace between the @samp{`}, @samp{,} or @samp{,@@} and thefollowing expression.This syntax is still accepted, for compatibility with old Emacsversions, but we recommend not using it in new programs.@node Problems with Macros@section Common Problems Using Macros The basic facts of macro expansion have counterintuitive consequences.This section describes some important consequences that can lead totrouble, and rules to follow to avoid trouble.@menu* Argument Evaluation:: The expansion should evaluate each macro arg once.* Surprising Local Vars:: Local variable bindings in the expansion require special care.* Eval During Expansion:: Don't evaluate them; put them in the expansion.* Repeated Expansion:: Avoid depending on how many times expansion is done.@end menu@node Argument Evaluation@subsection Evaluating Macro Arguments Repeatedly When defining a macro you must pay attention to the number of timesthe arguments will be evaluated when the expansion is executed. Thefollowing macro (used to facilitate iteration) illustrates the problem.This macro allows us to write a simple ``for'' loop such as one mightfind in Pascal.@findex for@smallexample@group(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)))))))@end group@result{} for@group(for i from 1 to 3 do (setq square (* i i)) (princ (format "\n%d %d" i square)))@expansion{}@end group@group(let ((i 1)) (while (<= i 3) (setq square (* i i)) (princ (format "%d %d" i square)) (inc i)))@end group@group @print{}1 1 @print{}2 4 @print{}3 9@result{} nil@end group@end smallexample@noindentThe arguments @code{from}, @code{to}, and @code{do} in this macro are``syntactic sugar''; they are entirely ignored. The idea is that youwill write noise words (such as @code{from}, @code{to}, and @code{do})in those positions in the macro call.Here's an equivalent definition simplified through use of backquote:@smallexample@group(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) ,@@body (inc ,var))))@end group@end smallexampleBoth forms of this definition (with backquote and without) suffer fromthe defect that @var{final} is evaluated on every iteration. If@var{final} is a constant, this is not a problem. If it is a morecomplex form, say @code{(long-complex-calculation x)}, this can slowdown the execution significantly. If @var{final} has side effects,executing it more than once is probably incorrect.@cindex macro argument evaluationA well-designed macro definition takes steps to avoid this problem byproducing an expansion that evaluates the argument expressions exactlyonce unless repeated evaluation is part of the intended purpose of themacro. Here is a correct expansion for the @code{for} macro:@smallexample@group(let ((i 1) (max 3)) (while (<= i max) (setq square (* i i)) (princ (format "%d %d" i square)) (inc i)))@end group@end smallexampleHere is a macro definition that creates this expansion: @smallexample@group(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) ,@@body (inc ,var))))@end group@end smallexample Unfortunately, this fix introduces another problem,described in the following section.@node Surprising Local Vars@subsection Local Variables in Macro Expansions@ifinfo In the previous section, the definition of @code{for} was fixed asfollows to make the expansion evaluate the macro arguments the propernumber of times:@smallexample@group(defmacro for (var from init to final do &rest body) "Execute a simple for loop: (for i from 1 to 10 do (print i))."@end group@group `(let ((,var ,init) (max ,final)) (while (<= ,var max) ,@@body (inc ,var))))@end group@end smallexample@end ifinfo The new definition of @code{for} has a new problem: it introduces alocal variable named @code{max} which the user does not expect. Thiscauses trouble in examples such as the following:@smallexample@group(let ((max 0)) (for x from 0 to 10 do (let ((this (frob x))) (if (< max this) (setq max this)))))@end group@end smallexample@noindentThe references to @code{max} inside the body of the @code{for}, whichare supposed to refer to the user's binding of @code{max}, really accessthe binding made by @code{for}.The way to correct this is to use an uninterned symbol instead of@code{max} (@pxref{Creating Symbols}). The uninterned symbol can bebound and referred to just like any other symbol, but since it iscreated by @code{for}, we know that it cannot already appear in theuser's program. Since it is not interned, there is no way the user canput it into the program later. It will never appear anywhere exceptwhere put by @code{for}. Here is a definition of @code{for} that worksthis way:@smallexample@group(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) ,@@body (inc ,var)))))@end group@end smallexample@noindentThis creates an uninterned symbol named @code{max} and puts it in theexpansion instead of the usual interned symbol @code{max} that appearsin expressions ordinarily.@node Eval During Expansion@subsection Evaluating Macro Arguments in Expansion Another problem can happen if you the macro definition itselfevaluates any of the macro argument expressions, such as by calling@code{eval} (@pxref{Eval}). If the argument is supposed to refer to theuser's variables, you may have trouble if the user happens to use avariable with the same name as one of the macro arguments. Inside themacro body, the macro argument binding is the most local binding of thisvariable, so any references inside the form being evaluated do refer toit. Here is an example:@example@group(defmacro foo (a) (list 'setq (eval a) t)) @result{} foo@end group@group(setq x 'b)(foo x) @expansion{} (setq b t) @result{} t ; @r{and @code{b} has been set.};; @r{but}(setq a 'c)(foo a) @expansion{} (setq a t) @result{} t ; @r{but this set @code{a}, not @code{c}.}@end group@end example It makes a difference whether the user's variable is named @code{a} or@code{x}, because @code{a} conflicts with the macro argument variable@code{a}. Another problem with calling @code{eval} in a macro definition is thatit probably won't do what you intend in a compiled program. Thebyte-compiler runs macro definitions while compiling the program, whenthe program's own computations (which you might have wished to accesswith @code{eval}) don't occur and its local variable bindings don'texist. To avoid these problems, @strong{don't evaluate an argument expressionwhile computing the macro expansion.} Instead, substitute theexpression into the macro expansion, so that its value will be computedas part of executing the expansion. This is how the other examples inthis chapter work.@node Repeated Expansion@subsection How Many Times is the Macro Expanded? Occasionally problems result from the fact that a macro call isexpanded each time it is evaluated in an interpreted function, but isexpanded only once (during compilation) for a compiled function. If themacro definition has side effects, they will work differently dependingon how many times the macro is expanded. Therefore, you should avoid side effects in computation of themacro expansion, unless you really know what you are doing. One special kind of side effect can't be avoided: constructing Lispobjects. Almost all macro expansions include constructed lists; that isthe whole point of most macros. This is usually safe; there is just onecase where you must be careful: when the object you construct is part of aquoted constant in the macro expansion. If the macro is expanded just once, in compilation, then the object isconstructed just once, during compilation. But in interpretedexecution, the macro is expanded each time the macro call runs, and thismeans a new object is constructed each time. In most clean Lisp code, this difference won't matter. It can matteronly if you perform side-effects on the objects constructed by the macrodefinition. Thus, to avoid trouble, @strong{avoid side effects onobjects constructed by macro definitions}. Here is an example of howsuch side effects can get you into trouble:@lisp@group(defmacro empty-object () (list 'quote (cons nil nil)))@end group@group(defun initialize (condition) (let ((object (empty-object))) (if condition (setcar object condition)) object))@end group@end lisp@noindentIf @code{initialize} is interpreted, a new list @code{(nil)} isconstructed each time @code{initialize} is called. Thus, no side effectsurvives between calls. If @code{initialize} is compiled, then themacro @code{empty-object} is expanded during compilation, producing asingle ``constant'' @code{(nil)} that is reused and altered each time@code{initialize} is called.One way to avoid pathological cases like this is to think of@code{empty-object} as a funny kind of constant, not as a memoryallocation construct. You wouldn't use @code{setcar} on a constant suchas @code{'(nil)}, so naturally you won't use it on @code{(empty-object)}either.