macros.texi 23 KB

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