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