]> code.delx.au - gnu-emacs/blob - doc/lispref/macros.texi
2e1d530286137ad59c746ff7756e397ffc73b51f
[gnu-emacs] / doc / lispref / macros.texi
1 @c -*-texinfo-*-
2 @c This is part of the GNU Emacs Lisp Reference Manual.
3 @c Copyright (C) 1990-1995, 1998, 2001-2012 Free Software Foundation, Inc.
4 @c See the file elisp.texi for copying conditions.
5 @node Macros
6 @chapter Macros
7 @cindex macros
8
9 @dfn{Macros} enable you to define new control constructs and other
10 language features. A macro is defined much like a function, but instead
11 of telling how to compute a value, it tells how to compute another Lisp
12 expression which will in turn compute the value. We call this
13 expression the @dfn{expansion} of the macro.
14
15 Macros can do this because they operate on the unevaluated expressions
16 for the arguments, not on the argument values as functions do. They can
17 therefore construct an expansion containing these argument expressions
18 or parts of them.
19
20 If you are using a macro to do something an ordinary function could
21 do, just for the sake of speed, consider using an inline function
22 instead. @xref{Inline Functions}.
23
24 @menu
25 * Simple Macro:: A basic example.
26 * Expansion:: How, when and why macros are expanded.
27 * Compiling Macros:: How macros are expanded by the compiler.
28 * Defining Macros:: How to write a macro definition.
29 * Problems with Macros:: Don't evaluate the macro arguments too many times.
30 Don't hide the user's variables.
31 * Indenting Macros:: Specifying how to indent macro calls.
32 @end menu
33
34 @node Simple Macro
35 @section A Simple Example of a Macro
36
37 Suppose we would like to define a Lisp construct to increment a
38 variable value, much like the @code{++} operator in C@. We would like to
39 write @code{(inc x)} and have the effect of @code{(setq x (1+ x))}.
40 Here's a macro definition that does the job:
41
42 @findex inc
43 @example
44 @group
45 (defmacro inc (var)
46 (list 'setq var (list '1+ var)))
47 @end group
48 @end example
49
50 When this is called with @code{(inc x)}, the argument @var{var} is the
51 symbol @code{x}---@emph{not} the @emph{value} of @code{x}, as it would
52 be in a function. The body of the macro uses this to construct the
53 expansion, which is @code{(setq x (1+ x))}. Once the macro definition
54 returns this expansion, Lisp proceeds to evaluate it, thus incrementing
55 @code{x}.
56
57 @node Expansion
58 @section Expansion of a Macro Call
59 @cindex expansion of macros
60 @cindex macro call
61
62 A macro call looks just like a function call in that it is a list which
63 starts with the name of the macro. The rest of the elements of the list
64 are the arguments of the macro.
65
66 Evaluation of the macro call begins like evaluation of a function call
67 except for one crucial difference: the macro arguments are the actual
68 expressions appearing in the macro call. They are not evaluated before
69 they are given to the macro definition. By contrast, the arguments of a
70 function are results of evaluating the elements of the function call
71 list.
72
73 Having obtained the arguments, Lisp invokes the macro definition just
74 as a function is invoked. The argument variables of the macro are bound
75 to the argument values from the macro call, or to a list of them in the
76 case of a @code{&rest} argument. And the macro body executes and
77 returns its value just as a function body does.
78
79 The second crucial difference between macros and functions is that
80 the value returned by the macro body is an alternate Lisp expression,
81 also known as the @dfn{expansion} of the macro. The Lisp interpreter
82 proceeds to evaluate the expansion as soon as it comes back from the
83 macro.
84
85 Since the expansion is evaluated in the normal manner, it may contain
86 calls to other macros. It may even be a call to the same macro, though
87 this is unusual.
88
89 Note that Emacs tries to expand macros when loading an uncompiled
90 Lisp file. This is not always possible, but if it is, it speeds up
91 subsequent execution. @xref{How Programs Do Loading}.
92
93 You can see the expansion of a given macro call by calling
94 @code{macroexpand}.
95
96 @defun macroexpand form &optional environment
97 @cindex macro expansion
98 This function expands @var{form}, if it is a macro call. If the result
99 is another macro call, it is expanded in turn, until something which is
100 not a macro call results. That is the value returned by
101 @code{macroexpand}. If @var{form} is not a macro call to begin with, it
102 is returned as given.
103
104 Note that @code{macroexpand} does not look at the subexpressions of
105 @var{form} (although some macro definitions may do so). Even if they
106 are macro calls themselves, @code{macroexpand} does not expand them.
107
108 The function @code{macroexpand} does not expand calls to inline functions.
109 Normally there is no need for that, since a call to an inline function is
110 no harder to understand than a call to an ordinary function.
111
112 If @var{environment} is provided, it specifies an alist of macro
113 definitions that shadow the currently defined macros. Byte compilation
114 uses this feature.
115
116 @example
117 @group
118 (defmacro inc (var)
119 (list 'setq var (list '1+ var)))
120 @end group
121
122 @group
123 (macroexpand '(inc r))
124 @result{} (setq r (1+ r))
125 @end group
126
127 @group
128 (defmacro inc2 (var1 var2)
129 (list 'progn (list 'inc var1) (list 'inc var2)))
130 @end group
131
132 @group
133 (macroexpand '(inc2 r s))
134 @result{} (progn (inc r) (inc s)) ; @r{@code{inc} not expanded here.}
135 @end group
136 @end example
137 @end defun
138
139
140 @defun macroexpand-all form &optional environment
141 @code{macroexpand-all} expands macros like @code{macroexpand}, but
142 will look for and expand all macros in @var{form}, not just at the
143 top-level. If no macros are expanded, the return value is @code{eq}
144 to @var{form}.
145
146 Repeating the example used for @code{macroexpand} above with
147 @code{macroexpand-all}, we see that @code{macroexpand-all} @emph{does}
148 expand the embedded calls to @code{inc}:
149
150 @example
151 (macroexpand-all '(inc2 r s))
152 @result{} (progn (setq r (1+ r)) (setq s (1+ s)))
153 @end example
154
155 @end defun
156
157 @node Compiling Macros
158 @section Macros and Byte Compilation
159 @cindex byte-compiling macros
160
161 You might ask why we take the trouble to compute an expansion for a
162 macro and then evaluate the expansion. Why not have the macro body
163 produce the desired results directly? The reason has to do with
164 compilation.
165
166 When a macro call appears in a Lisp program being compiled, the Lisp
167 compiler calls the macro definition just as the interpreter would, and
168 receives an expansion. But instead of evaluating this expansion, it
169 compiles the expansion as if it had appeared directly in the program.
170 As a result, the compiled code produces the value and side effects
171 intended for the macro, but executes at full compiled speed. This would
172 not work if the macro body computed the value and side effects
173 itself---they would be computed at compile time, which is not useful.
174
175 In order for compilation of macro calls to work, the macros must
176 already be defined in Lisp when the calls to them are compiled. The
177 compiler has a special feature to help you do this: if a file being
178 compiled contains a @code{defmacro} form, the macro is defined
179 temporarily for the rest of the compilation of that file.
180
181 Byte-compiling a file also executes any @code{require} calls at
182 top-level in the file, so you can ensure that necessary macro
183 definitions are available during compilation by requiring the files
184 that define them (@pxref{Named Features}). To avoid loading the macro
185 definition files when someone @emph{runs} the compiled program, write
186 @code{eval-when-compile} around the @code{require} calls (@pxref{Eval
187 During Compile}).
188
189 @node Defining Macros
190 @section Defining Macros
191
192 A Lisp macro object is a list whose @sc{car} is @code{macro}, and
193 whose @sc{cdr} is a lambda expression. Expansion of the macro works
194 by applying the lambda expression (with @code{apply}) to the list of
195 @emph{unevaluated} arguments from the macro call.
196
197 It is possible to use an anonymous Lisp macro just like an anonymous
198 function, but this is never done, because it does not make sense to
199 pass an anonymous macro to functionals such as @code{mapcar}. In
200 practice, all Lisp macros have names, and they are almost always
201 defined with the @code{defmacro} macro.
202
203 @defmac defmacro name args [doc] [declare] body@dots{}
204 @code{defmacro} defines the symbol @var{name} (which should not be
205 quoted) as a macro that looks like this:
206
207 @example
208 (macro lambda @var{args} . @var{body})
209 @end example
210
211 (Note that the @sc{cdr} of this list is a lambda expression.) This
212 macro object is stored in the function cell of @var{name}. The
213 meaning of @var{args} is the same as in a function, and the keywords
214 @code{&rest} and @code{&optional} may be used (@pxref{Argument List}).
215 Neither @var{name} nor @var{args} should be quoted. The return value
216 of @code{defmacro} is undefined.
217
218 @var{doc}, if present, should be a string specifying the macro's
219 documentation string. @var{declare}, if present, should be a
220 @code{declare} form specifying metadata for the macro (@pxref{Declare
221 Form}). Note that macros cannot have interactive declarations, since
222 they cannot be called interactively.
223 @end defmac
224
225 Macros often need to construct large list structures from a mixture
226 of constants and nonconstant parts. To make this easier, use the
227 @samp{`} syntax (@pxref{Backquote}). For example:
228
229 @example
230 @example
231 @group
232 (defmacro t-becomes-nil (variable)
233 `(if (eq ,variable t)
234 (setq ,variable nil)))
235 @end group
236
237 @group
238 (t-becomes-nil foo)
239 @equiv{} (if (eq foo t) (setq foo nil))
240 @end group
241 @end example
242 @end example
243
244 The body of a macro definition can include a @code{declare} form,
245 which specifies additional properties about the macro. @xref{Declare
246 Form}.
247
248 @node Problems with Macros
249 @section Common Problems Using Macros
250
251 Macro expansion can have counterintuitive consequences. This
252 section describes some important consequences that can lead to
253 trouble, and rules to follow to avoid trouble.
254
255 @menu
256 * Wrong Time:: Do the work in the expansion, not in the macro.
257 * Argument Evaluation:: The expansion should evaluate each macro arg once.
258 * Surprising Local Vars:: Local variable bindings in the expansion
259 require special care.
260 * Eval During Expansion:: Don't evaluate them; put them in the expansion.
261 * Repeated Expansion:: Avoid depending on how many times expansion is done.
262 @end menu
263
264 @node Wrong Time
265 @subsection Wrong Time
266
267 The most common problem in writing macros is doing some of the
268 real work prematurely---while expanding the macro, rather than in the
269 expansion itself. For instance, one real package had this macro
270 definition:
271
272 @example
273 (defmacro my-set-buffer-multibyte (arg)
274 (if (fboundp 'set-buffer-multibyte)
275 (set-buffer-multibyte arg)))
276 @end example
277
278 With this erroneous macro definition, the program worked fine when
279 interpreted but failed when compiled. This macro definition called
280 @code{set-buffer-multibyte} during compilation, which was wrong, and
281 then did nothing when the compiled package was run. The definition
282 that the programmer really wanted was this:
283
284 @example
285 (defmacro my-set-buffer-multibyte (arg)
286 (if (fboundp 'set-buffer-multibyte)
287 `(set-buffer-multibyte ,arg)))
288 @end example
289
290 @noindent
291 This macro expands, if appropriate, into a call to
292 @code{set-buffer-multibyte} that will be executed when the compiled
293 program is actually run.
294
295 @node Argument Evaluation
296 @subsection Evaluating Macro Arguments Repeatedly
297
298 When defining a macro you must pay attention to the number of times
299 the arguments will be evaluated when the expansion is executed. The
300 following macro (used to facilitate iteration) illustrates the
301 problem. This macro allows us to write a ``for'' loop construct.
302
303 @findex for
304 @example
305 @group
306 (defmacro for (var from init to final do &rest body)
307 "Execute a simple \"for\" loop.
308 For example, (for i from 1 to 10 do (print i))."
309 (list 'let (list (list var init))
310 (cons 'while
311 (cons (list '<= var final)
312 (append body (list (list 'inc var)))))))
313 @end group
314
315 @group
316 (for i from 1 to 3 do
317 (setq square (* i i))
318 (princ (format "\n%d %d" i square)))
319 @expansion{}
320 @end group
321 @group
322 (let ((i 1))
323 (while (<= i 3)
324 (setq square (* i i))
325 (princ (format "\n%d %d" i square))
326 (inc i)))
327 @end group
328 @group
329
330 @print{}1 1
331 @print{}2 4
332 @print{}3 9
333 @result{} nil
334 @end group
335 @end example
336
337 @noindent
338 The arguments @code{from}, @code{to}, and @code{do} in this macro are
339 ``syntactic sugar''; they are entirely ignored. The idea is that you
340 will write noise words (such as @code{from}, @code{to}, and @code{do})
341 in those positions in the macro call.
342
343 Here's an equivalent definition simplified through use of backquote:
344
345 @example
346 @group
347 (defmacro for (var from init to final do &rest body)
348 "Execute a simple \"for\" loop.
349 For example, (for i from 1 to 10 do (print i))."
350 `(let ((,var ,init))
351 (while (<= ,var ,final)
352 ,@@body
353 (inc ,var))))
354 @end group
355 @end example
356
357 Both forms of this definition (with backquote and without) suffer from
358 the defect that @var{final} is evaluated on every iteration. If
359 @var{final} is a constant, this is not a problem. If it is a more
360 complex form, say @code{(long-complex-calculation x)}, this can slow
361 down the execution significantly. If @var{final} has side effects,
362 executing it more than once is probably incorrect.
363
364 @cindex macro argument evaluation
365 A well-designed macro definition takes steps to avoid this problem by
366 producing an expansion that evaluates the argument expressions exactly
367 once unless repeated evaluation is part of the intended purpose of the
368 macro. Here is a correct expansion for the @code{for} macro:
369
370 @example
371 @group
372 (let ((i 1)
373 (max 3))
374 (while (<= i max)
375 (setq square (* i i))
376 (princ (format "%d %d" i square))
377 (inc i)))
378 @end group
379 @end example
380
381 Here is a macro definition that creates this expansion:
382
383 @example
384 @group
385 (defmacro for (var from init to final do &rest body)
386 "Execute a simple for loop: (for i from 1 to 10 do (print i))."
387 `(let ((,var ,init)
388 (max ,final))
389 (while (<= ,var max)
390 ,@@body
391 (inc ,var))))
392 @end group
393 @end example
394
395 Unfortunately, this fix introduces another problem,
396 described in the following section.
397
398 @node Surprising Local Vars
399 @subsection Local Variables in Macro Expansions
400
401 @ifnottex
402 In the previous section, the definition of @code{for} was fixed as
403 follows to make the expansion evaluate the macro arguments the proper
404 number of times:
405
406 @example
407 @group
408 (defmacro for (var from init to final do &rest body)
409 "Execute a simple for loop: (for i from 1 to 10 do (print i))."
410 @end group
411 @group
412 `(let ((,var ,init)
413 (max ,final))
414 (while (<= ,var max)
415 ,@@body
416 (inc ,var))))
417 @end group
418 @end example
419 @end ifnottex
420
421 The new definition of @code{for} has a new problem: it introduces a
422 local variable named @code{max} which the user does not expect. This
423 causes trouble in examples such as the following:
424
425 @example
426 @group
427 (let ((max 0))
428 (for x from 0 to 10 do
429 (let ((this (frob x)))
430 (if (< max this)
431 (setq max this)))))
432 @end group
433 @end example
434
435 @noindent
436 The references to @code{max} inside the body of the @code{for}, which
437 are supposed to refer to the user's binding of @code{max}, really access
438 the binding made by @code{for}.
439
440 The way to correct this is to use an uninterned symbol instead of
441 @code{max} (@pxref{Creating Symbols}). The uninterned symbol can be
442 bound and referred to just like any other symbol, but since it is
443 created by @code{for}, we know that it cannot already appear in the
444 user's program. Since it is not interned, there is no way the user can
445 put it into the program later. It will never appear anywhere except
446 where put by @code{for}. Here is a definition of @code{for} that works
447 this way:
448
449 @example
450 @group
451 (defmacro for (var from init to final do &rest body)
452 "Execute a simple for loop: (for i from 1 to 10 do (print i))."
453 (let ((tempvar (make-symbol "max")))
454 `(let ((,var ,init)
455 (,tempvar ,final))
456 (while (<= ,var ,tempvar)
457 ,@@body
458 (inc ,var)))))
459 @end group
460 @end example
461
462 @noindent
463 This creates an uninterned symbol named @code{max} and puts it in the
464 expansion instead of the usual interned symbol @code{max} that appears
465 in expressions ordinarily.
466
467 @node Eval During Expansion
468 @subsection Evaluating Macro Arguments in Expansion
469
470 Another problem can happen if the macro definition itself
471 evaluates any of the macro argument expressions, such as by calling
472 @code{eval} (@pxref{Eval}). If the argument is supposed to refer to the
473 user's variables, you may have trouble if the user happens to use a
474 variable with the same name as one of the macro arguments. Inside the
475 macro body, the macro argument binding is the most local binding of this
476 variable, so any references inside the form being evaluated do refer to
477 it. Here is an example:
478
479 @example
480 @group
481 (defmacro foo (a)
482 (list 'setq (eval a) t))
483 @end group
484 @group
485 (setq x 'b)
486 (foo x) @expansion{} (setq b t)
487 @result{} t ; @r{and @code{b} has been set.}
488 ;; @r{but}
489 (setq a 'c)
490 (foo a) @expansion{} (setq a t)
491 @result{} t ; @r{but this set @code{a}, not @code{c}.}
492
493 @end group
494 @end example
495
496 It makes a difference whether the user's variable is named @code{a} or
497 @code{x}, because @code{a} conflicts with the macro argument variable
498 @code{a}.
499
500 Another problem with calling @code{eval} in a macro definition is that
501 it probably won't do what you intend in a compiled program. The
502 byte compiler runs macro definitions while compiling the program, when
503 the program's own computations (which you might have wished to access
504 with @code{eval}) don't occur and its local variable bindings don't
505 exist.
506
507 To avoid these problems, @strong{don't evaluate an argument expression
508 while computing the macro expansion}. Instead, substitute the
509 expression into the macro expansion, so that its value will be computed
510 as part of executing the expansion. This is how the other examples in
511 this chapter work.
512
513 @node Repeated Expansion
514 @subsection How Many Times is the Macro Expanded?
515
516 Occasionally problems result from the fact that a macro call is
517 expanded each time it is evaluated in an interpreted function, but is
518 expanded only once (during compilation) for a compiled function. If the
519 macro definition has side effects, they will work differently depending
520 on how many times the macro is expanded.
521
522 Therefore, you should avoid side effects in computation of the
523 macro expansion, unless you really know what you are doing.
524
525 One special kind of side effect can't be avoided: constructing Lisp
526 objects. Almost all macro expansions include constructed lists; that is
527 the whole point of most macros. This is usually safe; there is just one
528 case where you must be careful: when the object you construct is part of a
529 quoted constant in the macro expansion.
530
531 If the macro is expanded just once, in compilation, then the object is
532 constructed just once, during compilation. But in interpreted
533 execution, the macro is expanded each time the macro call runs, and this
534 means a new object is constructed each time.
535
536 In most clean Lisp code, this difference won't matter. It can matter
537 only if you perform side-effects on the objects constructed by the macro
538 definition. Thus, to avoid trouble, @strong{avoid side effects on
539 objects constructed by macro definitions}. Here is an example of how
540 such side effects can get you into trouble:
541
542 @lisp
543 @group
544 (defmacro empty-object ()
545 (list 'quote (cons nil nil)))
546 @end group
547
548 @group
549 (defun initialize (condition)
550 (let ((object (empty-object)))
551 (if condition
552 (setcar object condition))
553 object))
554 @end group
555 @end lisp
556
557 @noindent
558 If @code{initialize} is interpreted, a new list @code{(nil)} is
559 constructed each time @code{initialize} is called. Thus, no side effect
560 survives between calls. If @code{initialize} is compiled, then the
561 macro @code{empty-object} is expanded during compilation, producing a
562 single ``constant'' @code{(nil)} that is reused and altered each time
563 @code{initialize} is called.
564
565 One way to avoid pathological cases like this is to think of
566 @code{empty-object} as a funny kind of constant, not as a memory
567 allocation construct. You wouldn't use @code{setcar} on a constant such
568 as @code{'(nil)}, so naturally you won't use it on @code{(empty-object)}
569 either.
570
571 @node Indenting Macros
572 @section Indenting Macros
573
574 Within a macro definition, you can use the @code{declare} form
575 (@pxref{Defining Macros}) to specify how @key{TAB} should indent
576 calls to the macro. An indentation specification is written like this:
577
578 @example
579 (declare (indent @var{indent-spec}))
580 @end example
581
582 @noindent
583 Here are the possibilities for @var{indent-spec}:
584
585 @table @asis
586 @item @code{nil}
587 This is the same as no property---use the standard indentation pattern.
588 @item @code{defun}
589 Handle this function like a @samp{def} construct: treat the second
590 line as the start of a @dfn{body}.
591 @item an integer, @var{number}
592 The first @var{number} arguments of the function are
593 @dfn{distinguished} arguments; the rest are considered the body
594 of the expression. A line in the expression is indented according to
595 whether the first argument on it is distinguished or not. If the
596 argument is part of the body, the line is indented @code{lisp-body-indent}
597 more columns than the open-parenthesis starting the containing
598 expression. If the argument is distinguished and is either the first
599 or second argument, it is indented @emph{twice} that many extra columns.
600 If the argument is distinguished and not the first or second argument,
601 the line uses the standard pattern.
602 @item a symbol, @var{symbol}
603 @var{symbol} should be a function name; that function is called to
604 calculate the indentation of a line within this expression. The
605 function receives two arguments:
606
607 @table @asis
608 @item @var{state}
609 The value returned by @code{parse-partial-sexp} (a Lisp primitive for
610 indentation and nesting computation) when it parses up to the
611 beginning of this line.
612 @item @var{pos}
613 The position at which the line being indented begins.
614 @end table
615
616 @noindent
617 It should return either a number, which is the number of columns of
618 indentation for that line, or a list whose car is such a number. The
619 difference between returning a number and returning a list is that a
620 number says that all following lines at the same nesting level should
621 be indented just like this one; a list says that following lines might
622 call for different indentations. This makes a difference when the
623 indentation is being computed by @kbd{C-M-q}; if the value is a
624 number, @kbd{C-M-q} need not recalculate indentation for the following
625 lines until the end of the list.
626 @end table