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