macro documentation fixup
[bpt/guile.git] / doc / ref / api-macros.texi
1 @c -*-texinfo-*-
2 @c This is part of the GNU Guile Reference Manual.
3 @c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004, 2009, 2010
4 @c Free Software Foundation, Inc.
5 @c See the file guile.texi for copying conditions.
6
7 @node Macros
8 @section Macros
9
10 At its best, programming in Lisp is an iterative process of building up a
11 language appropriate to the problem at hand, and then solving the problem in
12 that language. Defining new procedures is part of that, but Lisp also allows
13 the user to extend its syntax, with its famous @dfn{macros}.
14
15 @cindex macros
16 @cindex transformation
17 Macros are syntactic extensions which cause the expression that they appear in
18 to be transformed in some way @emph{before} being evaluated. In expressions that
19 are intended for macro transformation, the identifier that names the relevant
20 macro must appear as the first element, like this:
21
22 @lisp
23 (@var{macro-name} @var{macro-args} @dots{})
24 @end lisp
25
26 @cindex macro expansion
27 Macro expansion is a separate phase of evaluation, run before code is
28 interpreted or compiled. A macro is a program that runs on programs, translating
29 an embedded language into core Scheme.
30
31 @menu
32 * Defining Macros:: Binding macros, globally and locally.
33 * Syntax Rules:: Pattern-driven macros.
34 * Syntax Case:: Procedural, hygienic macros.
35 * Defmacros:: Lisp-style macros.
36 * Identifier Macros:: Identifier macros.
37 * Eval When:: Affecting the expand-time environment.
38 * Internal Macros:: Macros as first-class values.
39 @end menu
40
41 @node Defining Macros
42 @subsection Defining Macros
43
44 A macro is a binding between a keyword and a syntax transformer. Since it's
45 difficult to discuss @code{define-syntax} without discussing the format of
46 transformers, consider the following example macro definition:
47
48 @example
49 (define-syntax when
50 (syntax-rules ()
51 ((when condition exp ...)
52 (if condition
53 (begin exp ...)))))
54
55 (when #t
56 (display "hey ho\n")
57 (display "let's go\n"))
58 @print{} hey ho
59 @print{} let's go
60 @end example
61
62 In this example, the @code{when} binding is bound with @code{define-syntax}.
63 Syntax transformers are discussed in more depth in @ref{Syntax Rules} and
64 @ref{Syntax Case}.
65
66 @deffn {Syntax} define-syntax keyword transformer
67 Bind @var{keyword} to the syntax transformer obtained by evaluating
68 @var{transformer}.
69
70 After a macro has been defined, further instances of @var{keyword} in Scheme
71 source code will invoke the syntax transformer defined by @var{transformer}.
72 @end deffn
73
74 One can also establish local syntactic bindings with @code{let-syntax}.
75
76 @deffn {Syntax} let-syntax ((keyword transformer) ...) exp...
77 Bind @var{keyword...} to @var{transformer...} while expanding @var{exp...}.
78
79 A @code{let-syntax} binding only exists at expansion-time.
80
81 @example
82 (let-syntax ((unless
83 (syntax-rules ()
84 ((unless condition exp ...)
85 (if (not condition)
86 (begin exp ...))))))
87 (unless #t
88 (primitive-exit 1))
89 "rock rock rock")
90 @result{} "rock rock rock"
91 @end example
92 @end deffn
93
94 A @code{define-syntax} form is valid anywhere a definition may appear: at the
95 top-level, or locally. Just as a local @code{define} expands out to an instance
96 of @code{letrec}, a local @code{define-syntax} expands out to
97 @code{letrec-syntax}.
98
99 @deffn {Syntax} letrec-syntax ((keyword transformer) ...) exp...
100 Bind @var{keyword...} to @var{transformer...} while expanding @var{exp...}.
101
102 In the spirit of @code{letrec} versus @code{let}, an expansion produced by
103 @var{transformer} may reference a @var{keyword} bound by the
104 same @var{letrec-syntax}.
105
106 @example
107 (letrec-syntax ((my-or
108 (syntax-rules ()
109 ((my-or)
110 #t)
111 ((my-or exp)
112 exp)
113 ((my-or exp rest ...)
114 (let ((t exp))
115 (if exp
116 exp
117 (my-or rest ...)))))))
118 (my-or #f "rockaway beach"))
119 @result{} "rockaway beach"
120 @end example
121 @end deffn
122
123 @node Syntax Rules
124 @subsection Syntax-rules Macros
125
126 @code{syntax-rules} macros are simple, pattern-driven syntax transformers, with
127 a beauty worthy of Scheme.
128
129 @deffn {Syntax} syntax-rules literals (pattern template)...
130 Create a syntax transformer that will rewrite an expression using the rules
131 embodied in the @var{pattern} and @var{template} clauses.
132 @end deffn
133
134 A @code{syntax-rules} macro consists of three parts: the literals (if any), the
135 patterns, and as many templates as there are patterns.
136
137 When the syntax expander sees the invocation of a @code{syntax-rules} macro, it
138 matches the expression against the patterns, in order, and rewrites the
139 expression using the template from the first matching pattern. If no pattern
140 matches, a syntax error is signalled.
141
142 @subsubsection Patterns
143
144 We have already seen some examples of patterns in the previous section:
145 @code{(unless condition exp ...)}, @code{(my-or exp)}, and so on. A pattern is
146 structured like the expression that it is to match. It can have nested structure
147 as well, like @code{(let ((var val) ...) exp exp* ...)}. Broadly speaking,
148 patterns are made of lists, improper lists, vectors, identifiers, and datums.
149 Users can match a sequence of patterns using the ellipsis (@code{...}).
150
151 Identifiers in a pattern are called @dfn{literals} if they are present in the
152 @code{syntax-rules} literals list, and @dfn{pattern variables} otherwise. When
153 building up the macro output, the expander replaces instances of a pattern
154 variable in the template with the matched subexpression.
155
156 @example
157 (define-syntax kwote
158 (syntax-rules ()
159 ((kwote exp)
160 (quote exp))))
161 (kwote (foo . bar))
162 @result{} (foo . bar)
163 @end example
164
165 An improper list of patterns matches as rest arguments do:
166
167 @example
168 (define-syntax let1
169 (syntax-rules ()
170 ((_ (var val) . exps)
171 (let ((var val)) . exps))))
172 @end example
173
174 However this definition of @code{let1} probably isn't what you want, as the tail
175 pattern @var{exps} will match non-lists, like @code{(let1 (foo 'bar) . baz)}. So
176 often instead of using improper lists as patterns, ellipsized patterns are
177 better. Instances of a pattern variable in the template must be followed by an
178 ellipsis.
179
180 @example
181 (define-syntax let1
182 (syntax-rules ()
183 ((_ (var val) exp ...)
184 (let ((var val)) exp ...))))
185 @end example
186
187 This @code{let1} probably still doesn't do what we want, because the body
188 matches sequences of zero expressions, like @code{(let1 (foo 'bar))}. In this
189 case we need to assert we have at least one body expression. A common idiom for
190 this is to name the ellipsized pattern variable with an asterisk:
191
192 @example
193 (define-syntax let1
194 (syntax-rules ()
195 ((_ (var val) exp exp* ...)
196 (let ((var val)) exp exp* ...))))
197 @end example
198
199 A vector of patterns matches a vector whose contents match the patterns,
200 including ellipsizing and tail patterns.
201
202 @example
203 (define-syntax letv
204 (syntax-rules ()
205 ((_ #((var val) ...) exp exp* ...)
206 (let ((var val) ...) exp exp* ...))))
207 (letv #((foo 'bar)) foo)
208 @result{} foo
209 @end example
210
211 Literals are used to match specific datums in an expression, like the use of
212 @code{=>} and @code{else} in @code{cond} expressions.
213
214 @example
215 (define-syntax cond1
216 (syntax-rules (=> else)
217 ((cond1 test => fun)
218 (let ((exp test))
219 (if exp (fun exp) #f)))
220 ((cond1 test exp exp* ...)
221 (if test (begin exp exp* ...)))
222 ((cond1 else exp exp* ...)
223 (begin exp exp* ...))))
224
225 (define (square x) (* x x))
226 (cond1 10 => square)
227 @result{} 100
228 (let ((=> #t))
229 (cond1 10 => square))
230 @result{} #<procedure square (x)>
231 @end example
232
233 A literal matches an input expression if the input expression is an identifier
234 with the same name as the literal, and both are unbound@footnote{Language
235 lawyers probably see the need here for use of @code{literal-identifier=?} rather
236 than @code{free-identifier=?}, and would probably be correct. Patches
237 accepted.}.
238
239 If a pattern is not a list, vector, or an identifier, it matches as a literal,
240 with @code{equal?}.
241
242 @example
243 (define-syntax define-matcher-macro
244 (syntax-rules ()
245 ((_ name lit)
246 (define-syntax name
247 (syntax-rules ()
248 ((_ lit) #t)
249 ((_ else) #f))))))
250
251 (define-matcher-macro is-literal-foo? "foo")
252
253 (is-literal-foo? "foo")
254 @result{} #t
255 (is-literal-foo? "bar")
256 @result{} #f
257 (let ((foo "foo"))
258 (is-literal-foo? foo))
259 @result{} #f
260 @end example
261
262 The last example indicates that matching happens at expansion-time, not
263 at run-time.
264
265 Syntax-rules macros are always used as @code{(@var{macro} . @var{args})}, and
266 the @var{macro} will always be a symbol. Correspondingly, a @code{syntax-rules}
267 pattern must be a list (proper or improper), and the first pattern in that list
268 must be an identifier. Incidentally it can be any identifier -- it doesn't have
269 to actually be the name of the macro. Thus the following three are equivalent:
270
271 @example
272 (define-syntax when
273 (syntax-rules ()
274 ((when c e ...)
275 (if c (begin e ...)))))
276
277 (define-syntax when
278 (syntax-rules ()
279 ((_ c e ...)
280 (if c (begin e ...)))))
281
282 (define-syntax when
283 (syntax-rules ()
284 ((something-else-entirely c e ...)
285 (if c (begin e ...)))))
286 @end example
287
288 For clarity, use one of the first two variants. Also note that since the pattern
289 variable will always match the macro itself (e.g., @code{cond1}), it is actually
290 left unbound in the template.
291
292 @subsubsection Hygiene
293
294 @code{syntax-rules} macros have a magical property: they preserve referential
295 transparency. When you read a macro definition, any free bindings in that macro
296 are resolved relative to the macro definition; and when you read a macro
297 instantiation, all free bindings in that expression are resolved relative to the
298 expression.
299
300 This property is sometimes known as @dfn{hygiene}, and it does aid in code
301 cleanliness. In your macro definitions, you can feel free to introduce temporary
302 variables, without worrying about inadvertantly introducing bindings into the
303 macro expansion.
304
305 Consider the definition of @code{my-or} from the previous section:
306
307 @example
308 (define-syntax my-or
309 (syntax-rules ()
310 ((my-or)
311 #t)
312 ((my-or exp)
313 exp)
314 ((my-or exp rest ...)
315 (let ((t exp))
316 (if exp
317 exp
318 (my-or rest ...))))))
319 @end example
320
321 A naive expansion of @code{(let ((t #t)) (my-or #f t))} would yield:
322
323 @example
324 (let ((t #t))
325 (let ((t #f))
326 (if t t t)))
327 @result{} #f
328 @end example
329
330 @noindent
331 Which clearly is not what we want. Somehow the @code{t} in the definition is
332 distinct from the @code{t} at the site of use; and it is indeed this distinction
333 that is maintained by the syntax expander, when expanding hygienic macros.
334
335 This discussion is mostly relevant in the context of traditional Lisp macros
336 (@pxref{Defmacros}), which do not preserve referential transparency. Hygiene
337 adds to the expressive power of Scheme.
338
339 @subsubsection Further Information
340
341 For a formal definition of @code{syntax-rules} and its pattern language, see
342 @xref{Macros, , Macros, r5rs, Revised(5) Report on the Algorithmic Language
343 Scheme}.
344
345 @code{syntax-rules} macros are simple and clean, but do they have limitations.
346 They do not lend themselves to expressive error messages: patterns either match
347 or they don't. Their ability to generate code is limited to template-driven
348 expansion; often one needs to define a number of helper macros to get real work
349 done. Sometimes one wants to introduce a binding into the lexical context of the
350 generated code; this is impossible with @code{syntax-rules}. Relatedly, they
351 cannot programmatically generate identifiers.
352
353 The solution to all of these problems is to use @code{syntax-case} if you need
354 its features. But if for some reason you're stuck with @code{syntax-rules}, you
355 might enjoy Joe Marshall's
356 @uref{http://sites.google.com/site/evalapply/eccentric.txt,@code{syntax-rules}
357 Primer for the Merely Eccentric}.
358
359 @node Syntax Case
360 @subsection Support for the @code{syntax-case} System
361
362 @code{syntax-case} macros are procedural syntax transformers, with a power
363 worthy of Scheme.
364
365 @deffn {Syntax} syntax-case syntax literals (pattern [guard] exp)...
366 Match the syntax object @var{syntax} against the given patterns, in order. If a
367 @var{pattern} matches, return the result of evaluating the associated @var{exp}.
368 @end deffn
369
370 Compare the following definitions of @code{when}:
371
372 @example
373 (define-syntax when
374 (syntax-rules ()
375 ((_ test e e* ...)
376 (if test (begin e e* ...)))))
377
378 (define-syntax when
379 (lambda (x)
380 (syntax-case x ()
381 ((_ test e e* ...)
382 #'(if test (begin e e* ...))))))
383 @end example
384
385 Clearly, the @code{syntax-case} definition is similar to its @code{syntax-rules}
386 counterpart, and equally clearly there are some differences. The
387 @code{syntax-case} definition is wrapped in a @code{lambda}, a function of one
388 argument; that argument is passed to the @code{syntax-case} invocation; and the
389 ``return value'' of the macro has a @code{#'} prefix.
390
391 All of these differences stem from the fact that @code{syntax-case} does not
392 define a syntax transformer itself -- instead, @code{syntax-case} expressions
393 provide a way to destructure a @dfn{syntax object}, and to rebuild syntax
394 objects as output.
395
396 So the @code{lambda} wrapper is simply a leaky implementation detail, that
397 syntax transformers are just functions that transform syntax to syntax. This
398 should not be surprising, given that we have already described macros as
399 ``programs that write programs''. @code{syntax-case} is simply a way to take
400 apart and put together program text, and to be a valid syntax transformer it
401 needs to be wrapped in a procedure.
402
403 Unlike traditional Lisp macros (@pxref{Defmacros}), @code{syntax-case} macros
404 transform syntax objects, not raw Scheme forms. Recall the naive expansion of
405 @code{my-or} given in the previous section:
406
407 @example
408 (let ((t #t))
409 (my-or #f t))
410 ;; naive expansion:
411 (let ((t #t))
412 (let ((t #f))
413 (if t t t)))
414 @end example
415
416 Raw Scheme forms simply don't have enough information to distinguish the first
417 two @code{t} instances in @code{(if t t t)} from the third @code{t}. So instead
418 of representing identifiers as symbols, the syntax expander represents
419 identifiers as annotated syntax objects, attaching such information to those
420 syntax objects as is needed to maintain referential transparency.
421
422 @deffn {Syntax} syntax form
423 Create a syntax object wrapping @var{form} within the current lexical context.
424 @end deffn
425
426 Syntax objects are typically created internally to the process of expansion, but
427 it is possible to create them outside of syntax expansion:
428
429 @example
430 (syntax (foo bar baz))
431 @result{} #<some representation of that syntax>
432 @end example
433
434 @noindent
435 However it is more common, and useful, to create syntax objects when building
436 output from a @code{syntax-case} expression.
437
438 @example
439 (define-syntax add1
440 (lambda (x)
441 (syntax-case x ()
442 ((_ exp)
443 (syntax (+ exp 1))))))
444 @end example
445
446 It is not strictly necessary for a @code{syntax-case} expression to return a
447 syntax object, because @code{syntax-case} expressions can be used in helper
448 functions, or otherwise used outside of syntax expansion itself. However a
449 syntax transformer procedure must return a syntax object, so most uses of
450 @code{syntax-case} do end up returning syntax objects.
451
452 Here in this case, the form that built the return value was @code{(syntax (+ exp
453 1))}. The interesting thing about this is that within a @code{syntax}
454 expression, any appearance of a pattern variable is substituted into the
455 resulting syntax object, carrying with it all relevant metadata from the source
456 expression, such as lexical identity and source location.
457
458 Indeed, a pattern variable may only be referenced from inside a @code{syntax}
459 form. The syntax expander would raise an error when defining @code{add1} if it
460 found @var{exp} referenced outside a @code{syntax} form.
461
462 Since @code{syntax} appears frequently in macro-heavy code, it has a special
463 reader macro: @code{#'}. @code{#'foo} is transformed by the reader into
464 @code{(syntax foo)}, just as @code{'foo} is tranformed into @code{(quote foo)}.
465
466 The pattern language used by @code{syntax-case} is conveniently the same
467 language used by @code{syntax-rules}. Given this, Guile actually defines
468 @code{syntax-rules} in terms of @code{syntax-case}:
469
470 @example
471 (define-syntax syntax-rules
472 (lambda (x)
473 (syntax-case x ()
474 ((_ (k ...) ((keyword . pattern) template) ...)
475 #'(lambda (x)
476 (syntax-case x (k ...)
477 ((dummy . pattern) #'template)
478 ...))))))
479 @end example
480
481 And that's that.
482
483 @subsubsection Why @code{syntax-case}?
484
485 The examples we have shown thus far could just as well have been expressed with
486 @code{syntax-rules}, and have just shown that @code{syntax-case} is more
487 verbose, which is true. But there is a difference: @code{syntax-case} creates
488 @emph{procedural} macros, giving the full power of Scheme to the macro expander.
489 This has many practical applications.
490
491 A common desire is to be able to match a form only if it is an identifier. This
492 is impossible with @code{syntax-rules}, given the datum matching forms. But with
493 @code{syntax-case} it is easy:
494
495 @deffn {Scheme Procedure} identifier? syntax-object
496 Returns @code{#t} iff @var{syntax-object} is an identifier.
497 @end deffn
498
499 @example
500 ;; relying on previous add1 definition
501 (define-syntax add1!
502 (lambda (x)
503 (syntax-case x ()
504 ((_ var) (identifier? #'var)
505 #'(set! var (add1 var))))))
506
507 (define foo 0)
508 (add1! foo)
509 foo @result{} 1
510 (add1! "not-an-identifier") @result{} error
511 @end example
512
513 With @code{syntax-rules}, the error for @code{(add1! "not-an-identifier")} would
514 be something like ``invalid @code{set!}''. With @code{syntax-case}, it will say
515 something like ``invalid @code{add1!}'', because we attach the @dfn{guard
516 clause} to the pattern: @code{(identifier? #'var)}. This becomes more important
517 with more complicated macros. It is necessary to use @code{identifier?}, because
518 to the expander, an identifier is more than a bare symbol.
519
520 Note that even in the guard clause, we reference the @var{var} pattern variable
521 within a @code{syntax} form, via @code{#'var}.
522
523 Another common desire is to introduce bindings into the lexical context of the
524 output expression. One example would be in the so-called ``anaphoric macros'',
525 like @code{aif}. Anaphoric macros bind some expression to a well-known
526 identifier, often @code{it}, within their bodies. For example, in @code{(aif
527 (foo) (bar it))}, @code{it} would be bound to the result of @code{(foo)}.
528
529 To begin with, we should mention a solution that doesn't work:
530
531 @example
532 ;; doesn't work
533 (define-syntax aif
534 (lambda (x)
535 (syntax-case x ()
536 ((_ test then else)
537 #'(let ((it test))
538 (if it then else))))))
539 @end example
540
541 The reason that this doesn't work is that, by default, the expander will
542 preserve referential transparency; the @var{then} and @var{else} expressions
543 won't have access to the binding of @code{it}.
544
545 But they can, if we explicitly introduce a binding via @code{datum->syntax}.
546
547 @deffn {Scheme Procedure} datum->syntax for-syntax datum
548 Create a syntax object that wraps @var{datum}, within the lexical context
549 corresponding to the syntax object @var{for-syntax}.
550 @end deffn
551
552 For completeness, we should mention that it is possible to strip the metadata
553 from a syntax object, returning a raw Scheme datum:
554
555 @deffn {Scheme Procedure} syntax->datum syntax-object
556 Strip the metadata from @var{syntax-object}, returning its contents as a raw
557 Scheme datum.
558 @end deffn
559
560 In this case we want to introduce @code{it} in the context of the whole
561 expression, so we can create a syntax object as @code{(datum->syntax x 'it)},
562 where @code{x} is the whole expression, as passed to the transformer procedure.
563
564 Here's another solution that doesn't work:
565
566 @example
567 ;; doesn't work either
568 (define-syntax aif
569 (lambda (x)
570 (syntax-case x ()
571 ((_ test then else)
572 (let ((it (datum->syntax x 'it)))
573 #'(let ((it test))
574 (if it then else)))))))
575 @end example
576
577 The reason that this one doesn't work is that there are really two
578 environments at work here -- the environment of pattern variables, as
579 bound by @code{syntax-case}, and the environment of lexical variables,
580 as bound by normal Scheme. The outer let form establishes a binding in
581 the environment of lexical variables, but the inner let form is inside a
582 syntax form, where only pattern variables will be substituted. Here we
583 need to introduce a piece of the lexical environment into the pattern
584 variable environment, and we can do so using @code{syntax-case} itself:
585
586 @example
587 ;; works, but is obtuse
588 (define-syntax aif
589 (lambda (x)
590 (syntax-case x ()
591 ((_ test then else)
592 ;; invoking syntax-case on the generated
593 ;; syntax object to expose it to `syntax'
594 (syntax-case (datum->syntax x 'it) ()
595 (it
596 #'(let ((it test))
597 (if it then else))))))))
598
599 (aif (getuid) (display it) (display "none")) (newline)
600 @print{} 500
601 @end example
602
603 However there are easier ways to write this. @code{with-syntax} is often
604 convenient:
605
606 @deffn {Syntax} with-syntax ((pat val)...) exp...
607 Bind patterns @var{pat} from their corresponding values @var{val}, within the
608 lexical context of @var{exp...}.
609
610 @example
611 ;; better
612 (define-syntax aif
613 (lambda (x)
614 (syntax-case x ()
615 ((_ test then else)
616 (with-syntax ((it (datum->syntax x 'it)))
617 #'(let ((it test))
618 (if it then else)))))))
619 @end example
620 @end deffn
621
622 As you might imagine, @code{with-syntax} is defined in terms of
623 @code{syntax-case}. But even that might be off-putting to you if you are an old
624 Lisp macro hacker, used to building macro output with @code{quasiquote}. The
625 issue is that @code{with-syntax} creates a separation between the point of
626 definition of a value and its point of substitution.
627
628 @pindex quasisyntax
629 @pindex unsyntax
630 @pindex unsyntax-splicing
631 So for cases in which a @code{quasiquote} style makes more sense,
632 @code{syntax-case} also defines @code{quasisyntax}, and the related
633 @code{unsyntax} and @code{unsyntax-splicing}, abbreviated by the reader as
634 @code{#`}, @code{#,}, and @code{#,@@}, respectively.
635
636 For example, to define a macro that inserts a compile-time timestamp into a
637 source file, one may write:
638
639 @example
640 (define-syntax display-compile-timestamp
641 (lambda (x)
642 (syntax-case x ()
643 ((_)
644 #`(begin
645 (display "The compile timestamp was: ")
646 (display #,(current-time))
647 (newline))))))
648 @end example
649
650 Finally, we should mention the following helper procedures defined by the core
651 of @code{syntax-case}:
652
653 @deffn {Scheme Procedure} bound-identifier=? a b
654 Returns @code{#t} iff the syntax objects @var{a} and @var{b} refer to the same
655 lexically-bound identifier.
656 @end deffn
657
658 @deffn {Scheme Procedure} free-identifier=? a b
659 Returns @code{#t} iff the syntax objects @var{a} and @var{b} refer to the same
660 free identifier.
661 @end deffn
662
663 @deffn {Scheme Procedure} generate-temporaries ls
664 Return a list of temporary identifiers as long as @var{ls} is long.
665 @end deffn
666
667 Readers interested in further information on @code{syntax-case} macros should
668 see R. Kent Dybvig's excellent @cite{The Scheme Programming Language}, either
669 edition 3 or 4, in the chapter on syntax. Dybvig was the primary author of the
670 @code{syntax-case} system. The book itself is available online at
671 @uref{http://scheme.com/tspl4/}.
672
673 @node Defmacros
674 @subsection Lisp-style Macro Definitions
675
676 The traditional way to define macros in Lisp is very similar to procedure
677 definitions. The key differences are that the macro definition body should
678 return a list that describes the transformed expression, and that the definition
679 is marked as a macro definition (rather than a procedure definition) by the use
680 of a different definition keyword: in Lisp, @code{defmacro} rather than
681 @code{defun}, and in Scheme, @code{define-macro} rather than @code{define}.
682
683 @fnindex defmacro
684 @fnindex define-macro
685 Guile supports this style of macro definition using both @code{defmacro}
686 and @code{define-macro}. The only difference between them is how the
687 macro name and arguments are grouped together in the definition:
688
689 @lisp
690 (defmacro @var{name} (@var{args} @dots{}) @var{body} @dots{})
691 @end lisp
692
693 @noindent
694 is the same as
695
696 @lisp
697 (define-macro (@var{name} @var{args} @dots{}) @var{body} @dots{})
698 @end lisp
699
700 @noindent
701 The difference is analogous to the corresponding difference between
702 Lisp's @code{defun} and Scheme's @code{define}.
703
704 Having read the previous section on @code{syntax-case}, it's probably clear that
705 Guile actually implements defmacros in terms of @code{syntax-case}, applying the
706 transformer on the expression between invocations of @code{syntax->datum} and
707 @code{datum->syntax}. This realization leads us to the problem with defmacros,
708 that they do not preserve referential transparency. One can be careful to not
709 introduce bindings into expanded code, via liberal use of @code{gensym}, but
710 there is no getting around the lack of referential transparency for free
711 bindings in the macro itself.
712
713 Even a macro as simple as our @code{when} from before is difficult to get right:
714
715 @example
716 (define-macro (when cond exp . rest)
717 `(if ,cond
718 (begin ,exp . ,rest)))
719
720 (when #f (display "Launching missiles!\n"))
721 @result{} #f
722
723 (let ((if list))
724 (when #f (display "Launching missiles!\n")))
725 @print{} Launching missiles!
726 @result{} (#f #<unspecified>)
727 @end example
728
729 Guile's perspective is that defmacros have had a good run, but that modern
730 macros should be written with @code{syntax-rules} or @code{syntax-case}. There
731 are still many uses of defmacros within Guile itself, but we will be phasing
732 them out over time. Of course we won't take away @code{defmacro} or
733 @code{define-macro} themselves, as there is lots of code out there that uses
734 them.
735
736
737 @node Identifier Macros
738 @subsection Identifier Macros
739
740 When the syntax expander sees a form in which the first element is a macro, the
741 whole form gets passed to the macro's syntax transformer. One may visualize this
742 as:
743
744 @example
745 (define-syntax foo foo-transformer)
746 (foo @var{arg}...)
747 ;; expands via
748 (foo-transformer #'(foo @var{arg}...))
749 @end example
750
751 If, on the other hand, a macro is referenced in some other part of a form, the
752 syntax transformer is invoked with only the macro reference, not the whole form.
753
754 @example
755 (define-syntax foo foo-transformer)
756 foo
757 ;; expands via
758 (foo-transformer #'foo)
759 @end example
760
761 This allows bare identifier references to be replaced programmatically via a
762 macro. @code{syntax-rules} provides some syntax to effect this transformation
763 more easily.
764
765 @deffn {Syntax} identifier-syntax exp
766 Returns a macro transformer that will replace occurences of the macro with
767 @var{exp}.
768 @end deffn
769
770 For example, if you are importing external code written in terms of @code{fx+},
771 the fixnum addition operator, but Guile doesn't have @code{fx+}, you may use the
772 following to replace @code{fx+} with @code{+}:
773
774 @example
775 (define-syntax fx+ (identifier-syntax +))
776 @end example
777
778 There is also special support for recognizing identifiers on the
779 left-hand side of a @code{set!} expression, as in the following:
780
781 @example
782 (define-syntax foo foo-transformer)
783 (set! foo @var{val})
784 ;; expands via
785 (foo-transformer #'(set! foo @var{val}))
786 ;; iff foo-transformer is a "variable transformer"
787 @end example
788
789 As the example notes, the transformer procedure must be explicitly
790 marked as being a ``variable transformer'', as most macros aren't
791 written to discriminate on the form in the operator position.
792
793 @deffn {Scheme Procedure} make-variable-transformer transformer
794 Mark the @var{transformer} procedure as being a ``variable
795 transformer''. In practice this means that, when bound to a syntactic
796 keyword, it may detect references to that keyword on the left-hand-side
797 of a @code{set!}.
798
799 @example
800 (define bar 10)
801 (define-syntax bar-alias
802 (make-variable-transformer
803 (lambda (x)
804 (syntax-case x (set!)
805 ((set! var val) #'(set! bar val))
806 ((var arg ...) #'(bar arg ...))
807 (var (identifier? #'var) #'bar)))))
808
809 bar-alias @result{} 10
810 (set! bar-alias 20)
811 bar @result{} 20
812 (set! bar 30)
813 bar-alias @result{} 30
814 @end example
815 @end deffn
816
817 There is an extension to identifer-syntax which allows it to handle the
818 @code{set!} case as well:
819
820 @deffn {Syntax} identifier-syntax (var exp1) ((set! var val) exp2)
821 Create a variable transformer. The first clause is used for references
822 to the variable in operator or operand position, and the second for
823 appearances of the variable on the left-hand-side of an assignment.
824
825 For example, the previous @code{bar-alias} example could be expressed
826 more succinctly like this:
827
828 @example
829 (define-syntax bar-alias
830 (identifier-syntax
831 (var bar)
832 ((set! var val) (set! bar val))))
833 @end example
834
835 @noindent
836 As before, the templates in @code{identifier-syntax} forms do not need
837 wrapping in @code{#'} syntax forms.
838 @end deffn
839
840
841 @node Eval When
842 @subsection Eval-when
843
844 As @code{syntax-case} macros have the whole power of Scheme available to them,
845 they present a problem regarding time: when a macro runs, what parts of the
846 program are available for the macro to use?
847
848 The default answer to this question is that when you import a module (via
849 @code{define-module} or @code{use-modules}), that module will be loaded up at
850 expansion-time, as well as at run-time. Additionally, top-level syntactic
851 definitions within one compilation unit made by @code{define-syntax} are also
852 evaluated at expansion time, in the order that they appear in the compilation
853 unit (file).
854
855 But if a syntactic definition needs to call out to a normal procedure at
856 expansion-time, it might well need need special declarations to indicate that
857 the procedure should be made available at expansion-time.
858
859 For example, the following code will work at a REPL, but not in a file:
860
861 @example
862 ;; incorrect
863 (use-modules (srfi srfi-19))
864 (define (date) (date->string (current-date)))
865 (define-syntax %date (identifier-syntax (date)))
866 (define *compilation-date* %date)
867 @end example
868
869 It works at a REPL because the expressions are evaluated one-by-one, in order,
870 but if placed in a file, the expressions are expanded one-by-one, but not
871 evaluated until the compiled file is loaded.
872
873 The fix is to use @code{eval-when}.
874
875 @example
876 ;; correct: using eval-when
877 (use-modules (srfi srfi-19))
878 (eval-when (compile load eval)
879 (define (date) (date->string (current-date))))
880 (define-syntax %date (identifier-syntax (date)))
881 (define *compilation-date* %date)
882 @end example
883
884 @deffn {Syntax} eval-when conditions exp...
885 Evaluate @var{exp...} under the given @var{conditions}. Valid conditions include
886 @code{eval}, @code{load}, and @code{compile}. If you need to use
887 @code{eval-when}, use it with all three conditions, as in the above example.
888 Other uses of @code{eval-when} may void your warranty or poison your cat.
889 @end deffn
890
891 @node Internal Macros
892 @subsection Internal Macros
893
894 @deffn {Scheme Procedure} make-syntax-transformer name type binding
895 Construct a syntax transformer object. This is part of Guile's low-level support
896 for syntax-case.
897 @end deffn
898
899 @deffn {Scheme Procedure} macro? obj
900 @deffnx {C Function} scm_macro_p (obj)
901 Return @code{#t} iff @var{obj} is a syntax transformer.
902
903 Note that it's a bit difficult to actually get a macro as a first-class object;
904 simply naming it (like @code{case}) will produce a syntax error. But it is
905 possible to get these objects using @code{module-ref}:
906
907 @example
908 (macro? (module-ref (current-module) 'case))
909 @result{} #t
910 @end example
911 @end deffn
912
913 @deffn {Scheme Procedure} macro-type m
914 @deffnx {C Function} scm_macro_type (m)
915 Return the @var{type} that was given when @var{m} was constructed, via
916 @code{make-syntax-transformer}.
917 @end deffn
918
919 @deffn {Scheme Procedure} macro-name m
920 @deffnx {C Function} scm_macro_name (m)
921 Return the name of the macro @var{m}.
922 @end deffn
923
924 @deffn {Scheme Procedure} macro-binding m
925 @deffnx {C Function} scm_macro_binding (m)
926 Return the binding of the macro @var{m}.
927 @end deffn
928
929 @deffn {Scheme Procedure} macro-transformer m
930 @deffnx {C Function} scm_macro_transformer (m)
931 Return the transformer of the macro @var{m}. This will return a procedure, for
932 which one may ask the docstring. That's the whole reason this section is
933 documented. Actually a part of the result of @code{macro-binding}.
934 @end deffn
935
936
937 @c Local Variables:
938 @c TeX-master: "guile.texi"
939 @c End: