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