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