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