Doc updates to macroexpansion, compiled procs, and compiler.texi
[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 45* Eval When:: Affecting the expand-time environment.
67915ab0 46* Macro Expansion:: Procedurally expanding macros.
e4955559
AW
47* Internal Macros:: Macros as first-class values.
48@end menu
49
50@node Defining Macros
51@subsection Defining Macros
52
53A macro is a binding between a keyword and a syntax transformer. Since it's
54difficult to discuss @code{define-syntax} without discussing the format of
55transformers, 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
71In this example, the @code{when} binding is bound with @code{define-syntax}.
72Syntax transformers are discussed in more depth in @ref{Syntax Rules} and
73@ref{Syntax Case}.
74
75@deffn {Syntax} define-syntax keyword transformer
76Bind @var{keyword} to the syntax transformer obtained by evaluating
77@var{transformer}.
78
79After a macro has been defined, further instances of @var{keyword} in Scheme
80source code will invoke the syntax transformer defined by @var{transformer}.
81@end deffn
82
83One can also establish local syntactic bindings with @code{let-syntax}.
84
df0a1002
BT
85@deffn {Syntax} let-syntax ((keyword transformer) @dots{}) exp1 exp2 @dots{}
86Bind each @var{keyword} to its corresponding @var{transformer} while
87expanding @var{exp1} @var{exp2} @enddots{}.
e4955559
AW
88
89A @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
104A @code{define-syntax} form is valid anywhere a definition may appear: at the
105top-level, or locally. Just as a local @code{define} expands out to an instance
106of @code{letrec}, a local @code{define-syntax} expands out to
107@code{letrec-syntax}.
108
df0a1002
BT
109@deffn {Syntax} letrec-syntax ((keyword transformer) @dots{}) exp1 exp2 @dots{}
110Bind each @var{keyword} to its corresponding @var{transformer} while
111expanding @var{exp1} @var{exp2} @enddots{}.
e4955559
AW
112
113In the spirit of @code{letrec} versus @code{let}, an expansion produced by
114@var{transformer} may reference a @var{keyword} bound by the
115same @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))
e006d87b
MW
126 (if t
127 t
e4955559
AW
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
138a beauty worthy of Scheme.
139
140@deffn {Syntax} syntax-rules literals (pattern template)...
1fc8dcc7
AW
141Create a syntax transformer that will rewrite an expression using the rules
142embodied in the @var{pattern} and @var{template} clauses.
143@end deffn
144
e4955559
AW
145A @code{syntax-rules} macro consists of three parts: the literals (if any), the
146patterns, and as many templates as there are patterns.
147
148When the syntax expander sees the invocation of a @code{syntax-rules} macro, it
149matches the expression against the patterns, in order, and rewrites the
150expression using the template from the first matching pattern. If no pattern
151matches, a syntax error is signalled.
e4955559
AW
152
153@subsubsection Patterns
154
155We 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
157structured like the expression that it is to match. It can have nested structure
158as well, like @code{(let ((var val) ...) exp exp* ...)}. Broadly speaking,
159patterns are made of lists, improper lists, vectors, identifiers, and datums.
160Users can match a sequence of patterns using the ellipsis (@code{...}).
161
162Identifiers 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
164building up the macro output, the expander replaces instances of a pattern
165variable 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
176An 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
185However this definition of @code{let1} probably isn't what you want, as the tail
186pattern @var{exps} will match non-lists, like @code{(let1 (foo 'bar) . baz)}. So
187often instead of using improper lists as patterns, ellipsized patterns are
188better. Instances of a pattern variable in the template must be followed by an
189ellipsis.
190
191@example
192(define-syntax let1
193 (syntax-rules ()
194 ((_ (var val) exp ...)
195 (let ((var val)) exp ...))))
196@end example
197
198This @code{let1} probably still doesn't do what we want, because the body
199matches sequences of zero expressions, like @code{(let1 (foo 'bar))}. In this
200case we need to assert we have at least one body expression. A common idiom for
201this 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
210A vector of patterns matches a vector whose contents match the patterns,
211including 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)
912f5f34 219@result{} bar
e4955559
AW
220@end example
221
222Literals 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
244A literal matches an input expression if the input expression is an identifier
245with the same name as the literal, and both are unbound@footnote{Language
246lawyers probably see the need here for use of @code{literal-identifier=?} rather
247than @code{free-identifier=?}, and would probably be correct. Patches
248accepted.}.
249
250If a pattern is not a list, vector, or an identifier, it matches as a literal,
251with @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
273The last example indicates that matching happens at expansion-time, not
274at run-time.
275
276Syntax-rules macros are always used as @code{(@var{macro} . @var{args})}, and
277the @var{macro} will always be a symbol. Correspondingly, a @code{syntax-rules}
278pattern must be a list (proper or improper), and the first pattern in that list
279must be an identifier. Incidentally it can be any identifier -- it doesn't have
280to 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
299For clarity, use one of the first two variants. Also note that since the pattern
300variable will always match the macro itself (e.g., @code{cond1}), it is actually
301left unbound in the template.
302
303@subsubsection Hygiene
304
305@code{syntax-rules} macros have a magical property: they preserve referential
306transparency. When you read a macro definition, any free bindings in that macro
307are resolved relative to the macro definition; and when you read a macro
308instantiation, all free bindings in that expression are resolved relative to the
309expression.
310
311This property is sometimes known as @dfn{hygiene}, and it does aid in code
312cleanliness. In your macro definitions, you can feel free to introduce temporary
ecb87335 313variables, without worrying about inadvertently introducing bindings into the
e4955559
AW
314macro expansion.
315
316Consider 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))
e006d87b
MW
327 (if t
328 t
e4955559
AW
329 (my-or rest ...))))))
330@end example
331
332A 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
342Which clearly is not what we want. Somehow the @code{t} in the definition is
343distinct from the @code{t} at the site of use; and it is indeed this distinction
344that is maintained by the syntax expander, when expanding hygienic macros.
345
346This discussion is mostly relevant in the context of traditional Lisp macros
347(@pxref{Defmacros}), which do not preserve referential transparency. Hygiene
348adds to the expressive power of Scheme.
349
cd4171d0
AW
350@subsubsection Shorthands
351
352One often ends up writing simple one-clause @code{syntax-rules} macros.
353There 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
357Define @var{keyword} as a new @code{syntax-rules} macro with one clause.
358@end deffn
359
360Cast 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
e4955559
AW
367@subsubsection Further Information
368
369For a formal definition of @code{syntax-rules} and its pattern language, see
370@xref{Macros, , Macros, r5rs, Revised(5) Report on the Algorithmic Language
371Scheme}.
372
373@code{syntax-rules} macros are simple and clean, but do they have limitations.
374They do not lend themselves to expressive error messages: patterns either match
375or they don't. Their ability to generate code is limited to template-driven
376expansion; often one needs to define a number of helper macros to get real work
377done. Sometimes one wants to introduce a binding into the lexical context of the
378generated code; this is impossible with @code{syntax-rules}. Relatedly, they
379cannot programmatically generate identifiers.
380
381The solution to all of these problems is to use @code{syntax-case} if you need
382its features. But if for some reason you're stuck with @code{syntax-rules}, you
383might enjoy Joe Marshall's
384@uref{http://sites.google.com/site/evalapply/eccentric.txt,@code{syntax-rules}
385Primer for the Merely Eccentric}.
386
387@node Syntax Case
388@subsection Support for the @code{syntax-case} System
389
1fc8dcc7
AW
390@code{syntax-case} macros are procedural syntax transformers, with a power
391worthy of Scheme.
392
393@deffn {Syntax} syntax-case syntax literals (pattern [guard] exp)...
394Match 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
398Compare 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
413Clearly, the @code{syntax-case} definition is similar to its @code{syntax-rules}
414counterpart, and equally clearly there are some differences. The
415@code{syntax-case} definition is wrapped in a @code{lambda}, a function of one
416argument; that argument is passed to the @code{syntax-case} invocation; and the
417``return value'' of the macro has a @code{#'} prefix.
418
419All of these differences stem from the fact that @code{syntax-case} does not
420define a syntax transformer itself -- instead, @code{syntax-case} expressions
421provide a way to destructure a @dfn{syntax object}, and to rebuild syntax
422objects as output.
423
424So the @code{lambda} wrapper is simply a leaky implementation detail, that
425syntax transformers are just functions that transform syntax to syntax. This
426should 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
428apart and put together program text, and to be a valid syntax transformer it
429needs to be wrapped in a procedure.
430
431Unlike traditional Lisp macros (@pxref{Defmacros}), @code{syntax-case} macros
432transform 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
444Raw Scheme forms simply don't have enough information to distinguish the first
445two @code{t} instances in @code{(if t t t)} from the third @code{t}. So instead
446of representing identifiers as symbols, the syntax expander represents
447identifiers as annotated syntax objects, attaching such information to those
448syntax objects as is needed to maintain referential transparency.
449
450@deffn {Syntax} syntax form
451Create a syntax object wrapping @var{form} within the current lexical context.
452@end deffn
453
454Syntax objects are typically created internally to the process of expansion, but
455it 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
463However it is more common, and useful, to create syntax objects when building
464output 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
474It is not strictly necessary for a @code{syntax-case} expression to return a
475syntax object, because @code{syntax-case} expressions can be used in helper
476functions, or otherwise used outside of syntax expansion itself. However a
7545ddd4 477syntax transformer procedure must return a syntax object, so most uses of
1fc8dcc7
AW
478@code{syntax-case} do end up returning syntax objects.
479
480Here in this case, the form that built the return value was @code{(syntax (+ exp
4811))}. The interesting thing about this is that within a @code{syntax}
7545ddd4 482expression, any appearance of a pattern variable is substituted into the
1fc8dcc7
AW
483resulting syntax object, carrying with it all relevant metadata from the source
484expression, such as lexical identity and source location.
485
486Indeed, a pattern variable may only be referenced from inside a @code{syntax}
487form. The syntax expander would raise an error when defining @code{add1} if it
488found @var{exp} referenced outside a @code{syntax} form.
489
490Since @code{syntax} appears frequently in macro-heavy code, it has a special
491reader macro: @code{#'}. @code{#'foo} is transformed by the reader into
ecb87335 492@code{(syntax foo)}, just as @code{'foo} is transformed into @code{(quote foo)}.
1fc8dcc7
AW
493
494The pattern language used by @code{syntax-case} is conveniently the same
495language 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
509And that's that.
510
511@subsubsection Why @code{syntax-case}?
512
513The 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
515verbose, 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.
517This has many practical applications.
518
519A common desire is to be able to match a form only if it is an identifier. This
520is 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
a4b4fbbd
JE
524Returns @code{#t} if @var{syntax-object} is an identifier, or @code{#f}
525otherwise.
1fc8dcc7
AW
526@end deffn
527
528@example
7545ddd4 529;; relying on previous add1 definition
1fc8dcc7
AW
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)
538foo @result{} 1
539(add1! "not-an-identifier") @result{} error
540@end example
541
542With @code{syntax-rules}, the error for @code{(add1! "not-an-identifier")} would
543be something like ``invalid @code{set!}''. With @code{syntax-case}, it will say
544something like ``invalid @code{add1!}'', because we attach the @dfn{guard
545clause} to the pattern: @code{(identifier? #'var)}. This becomes more important
546with more complicated macros. It is necessary to use @code{identifier?}, because
547to the expander, an identifier is more than a bare symbol.
548
549Note that even in the guard clause, we reference the @var{var} pattern variable
550within a @code{syntax} form, via @code{#'var}.
551
552Another common desire is to introduce bindings into the lexical context of the
553output expression. One example would be in the so-called ``anaphoric macros'',
554like @code{aif}. Anaphoric macros bind some expression to a well-known
555identifier, 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
558To 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
570The reason that this doesn't work is that, by default, the expander will
571preserve referential transparency; the @var{then} and @var{else} expressions
572won't have access to the binding of @code{it}.
573
574But they can, if we explicitly introduce a binding via @code{datum->syntax}.
575
576@deffn {Scheme Procedure} datum->syntax for-syntax datum
577Create a syntax object that wraps @var{datum}, within the lexical context
578corresponding to the syntax object @var{for-syntax}.
579@end deffn
580
581For completeness, we should mention that it is possible to strip the metadata
582from a syntax object, returning a raw Scheme datum:
583
584@deffn {Scheme Procedure} syntax->datum syntax-object
585Strip the metadata from @var{syntax-object}, returning its contents as a raw
586Scheme datum.
587@end deffn
588
589In this case we want to introduce @code{it} in the context of the whole
590expression, so we can create a syntax object as @code{(datum->syntax x 'it)},
591where @code{x} is the whole expression, as passed to the transformer procedure.
592
593Here'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
09cb3ae2
NL
606The reason that this one doesn't work is that there are really two
607environments at work here -- the environment of pattern variables, as
608bound by @code{syntax-case}, and the environment of lexical variables,
609as bound by normal Scheme. The outer let form establishes a binding in
610the environment of lexical variables, but the inner let form is inside a
611syntax form, where only pattern variables will be substituted. Here we
612need to introduce a piece of the lexical environment into the pattern
613variable environment, and we can do so using @code{syntax-case} itself:
1fc8dcc7
AW
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
632However there are easier ways to write this. @code{with-syntax} is often
633convenient:
634
635@deffn {Syntax} with-syntax ((pat val)...) exp...
636Bind patterns @var{pat} from their corresponding values @var{val}, within the
637lexical 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
651As 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
653Lisp macro hacker, used to building macro output with @code{quasiquote}. The
654issue is that @code{with-syntax} creates a separation between the point of
655definition of a value and its point of substitution.
656
657@pindex quasisyntax
658@pindex unsyntax
659@pindex unsyntax-splicing
660So 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
665For example, to define a macro that inserts a compile-time timestamp into a
666source 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
9b0975f1
AW
679Readers interested in further information on @code{syntax-case} macros should
680see R. Kent Dybvig's excellent @cite{The Scheme Programming Language}, either
681edition 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
688As noted in the previous section, Guile's syntax expander operates on
689syntax objects. Procedural macros consume and produce syntax objects.
690This section describes some of the auxiliary helpers that procedural
691macros can use to compare, generate, and query objects of this data
692type.
1fc8dcc7
AW
693
694@deffn {Scheme Procedure} bound-identifier=? a b
a4b4fbbd
JE
695Return @code{#t} if the syntax objects @var{a} and @var{b} refer to the
696same lexically-bound identifier, or @code{#f} otherwise.
1fc8dcc7
AW
697@end deffn
698
699@deffn {Scheme Procedure} free-identifier=? a b
a4b4fbbd
JE
700Return @code{#t} if the syntax objects @var{a} and @var{b} refer to the
701same free identifier, or @code{#f} otherwise.
1fc8dcc7
AW
702@end deffn
703
704@deffn {Scheme Procedure} generate-temporaries ls
705Return a list of temporary identifiers as long as @var{ls} is long.
706@end deffn
707
9b0975f1
AW
708@deffn {Scheme Procedure} syntax-source x
709Return the source properties that correspond to the syntax object
710@var{x}. @xref{Source Properties}, for more information.
711@end deffn
712
68fcf711
AW
713Guile also offers some more experimental interfaces in a separate
714module. As was the case with the Large Hadron Collider, it is unclear
715to our senior macrologists whether adding these interfaces will result
716in awesomeness or in the destruction of Guile via the creation of a
717singularity. We will preserve their functionality through the 2.0
718series, but we reserve the right to modify them in a future stable
719series, to a more than usual degree.
720
721@example
722(use-modules (system syntax))
723@end example
724
1ace4fbf
AW
725@deffn {Scheme Procedure} syntax-module id
726Return the name of the module whose source contains the identifier
727@var{id}.
728@end deffn
729
8ae26afe 730@deffn {Scheme Procedure} syntax-local-binding id [#:resolve-syntax-parameters?=#t]
9b0975f1
AW
731Resolve the identifer @var{id}, a syntax object, within the current
732lexical environment, and return two values, the binding type and a
733binding value. The binding type is a symbol, which may be one of the
734following:
735
736@table @code
737@item lexical
738A lexically-bound variable. The value is a unique token (in the sense
739of @code{eq?}) identifying this binding.
740@item macro
741A syntax transformer, either local or global. The value is the
742transformer procedure.
8ae26afe
AW
743@item syntax-parameter
744A syntax parameter (@pxref{Syntax Parameters}). By default,
745@code{syntax-local-binding} will resolve syntax parameters, so that this
746value will not be returned. Pass @code{#:resolve-syntax-parameters? #f}
747to indicate that you are interested in syntax parameters. The value is
748the default transformer procedure, as in @code{macro}.
9b0975f1
AW
749@item pattern-variable
750A pattern variable, bound via syntax-case. The value is an opaque
751object, internal to the expander.
752@item displaced-lexical
753A lexical variable that has gone out of scope. This can happen if a
754badly-written procedural macro saves a syntax object, then attempts to
755introduce it in a context in which it is unbound. The value is
756@code{#f}.
757@item global
758A global binding. The value is a pair, whose head is the symbol, and
759whose tail is the name of the module in which to resolve the symbol.
760@item other
761Some other binding, like @code{lambda} or other core bindings. The
762value is @code{#f}.
763@end table
764
765This is a very low-level procedure, with limited uses. One case in
766which it is useful is to build abstractions that associate auxiliary
767information 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)
3d51e57c 774 trans))
9b0975f1
AW
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
795a syntax transformer; to call it otherwise will signal an error.
796@end deffn
1fc8dcc7 797
3d51e57c
AW
798@deffn {Scheme Procedure} syntax-locally-bound-identifiers id
799Return a list of identifiers that were visible lexically when the
800identifier @var{id} was created, in order from outermost to innermost.
801
802This procedure is intended to be used in specialized procedural macros,
803to provide a macro with the set of bound identifiers that the macro can
804reference.
805
806As a technical implementation detail, the identifiers returned by
807@code{syntax-locally-bound-identifiers} will be anti-marked, like the
808syntax object that is given as input to a macro. This is to signal to
809the macro expander that these bindings were present in the original
810source, and do not need to be hygienically renamed, as would be the case
811with other introduced identifiers. See the discussion of hygiene in
812section 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
e4955559
AW
833@node Defmacros
834@subsection Lisp-style Macro Definitions
835
1fc8dcc7
AW
836The traditional way to define macros in Lisp is very similar to procedure
837definitions. The key differences are that the macro definition body should
838return a list that describes the transformed expression, and that the definition
839is marked as a macro definition (rather than a procedure definition) by the use
840of a different definition keyword: in Lisp, @code{defmacro} rather than
841@code{defun}, and in Scheme, @code{define-macro} rather than @code{define}.
e4955559
AW
842
843@fnindex defmacro
844@fnindex define-macro
845Guile supports this style of macro definition using both @code{defmacro}
846and @code{define-macro}. The only difference between them is how the
847macro 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
854is the same as
855
856@lisp
857(define-macro (@var{name} @var{args} @dots{}) @var{body} @dots{})
858@end lisp
859
860@noindent
861The difference is analogous to the corresponding difference between
862Lisp's @code{defun} and Scheme's @code{define}.
863
1fc8dcc7
AW
864Having read the previous section on @code{syntax-case}, it's probably clear that
865Guile actually implements defmacros in terms of @code{syntax-case}, applying the
866transformer on the expression between invocations of @code{syntax->datum} and
867@code{datum->syntax}. This realization leads us to the problem with defmacros,
868that they do not preserve referential transparency. One can be careful to not
869introduce bindings into expanded code, via liberal use of @code{gensym}, but
870there is no getting around the lack of referential transparency for free
871bindings in the macro itself.
e4955559 872
1fc8dcc7 873Even a macro as simple as our @code{when} from before is difficult to get right:
e4955559 874
1fc8dcc7
AW
875@example
876(define-macro (when cond exp . rest)
877 `(if ,cond
878 (begin ,exp . ,rest)))
e4955559 879
1fc8dcc7
AW
880(when #f (display "Launching missiles!\n"))
881@result{} #f
e4955559 882
1fc8dcc7
AW
883(let ((if list))
884 (when #f (display "Launching missiles!\n")))
885@print{} Launching missiles!
886@result{} (#f #<unspecified>)
887@end example
888
889Guile's perspective is that defmacros have had a good run, but that modern
890macros should be written with @code{syntax-rules} or @code{syntax-case}. There
891are still many uses of defmacros within Guile itself, but we will be phasing
892them 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
894them.
e4955559
AW
895
896
897@node Identifier Macros
898@subsection Identifier Macros
899
6ffd4131
AW
900When the syntax expander sees a form in which the first element is a macro, the
901whole form gets passed to the macro's syntax transformer. One may visualize this
902as:
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
911If, on the other hand, a macro is referenced in some other part of a form, the
912syntax transformer is invoked with only the macro reference, not the whole form.
913
914@example
915(define-syntax foo foo-transformer)
916foo
917;; expands via
918(foo-transformer #'foo)
919@end example
920
921This allows bare identifier references to be replaced programmatically via a
922macro. @code{syntax-rules} provides some syntax to effect this transformation
923more easily.
924
925@deffn {Syntax} identifier-syntax exp
ecb87335 926Returns a macro transformer that will replace occurrences of the macro with
6ffd4131
AW
927@var{exp}.
928@end deffn
929
930For example, if you are importing external code written in terms of @code{fx+},
931the fixnum addition operator, but Guile doesn't have @code{fx+}, you may use the
932following to replace @code{fx+} with @code{+}:
933
934@example
935(define-syntax fx+ (identifier-syntax +))
936@end example
937
69724dde
AW
938There is also special support for recognizing identifiers on the
939left-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}))
a4b4fbbd 946;; if foo-transformer is a "variable transformer"
69724dde
AW
947@end example
948
949As the example notes, the transformer procedure must be explicitly
950marked as being a ``variable transformer'', as most macros aren't
7545ddd4 951written to discriminate on the form in the operator position.
69724dde
AW
952
953@deffn {Scheme Procedure} make-variable-transformer transformer
954Mark the @var{transformer} procedure as being a ``variable
955transformer''. In practice this means that, when bound to a syntactic
956keyword, it may detect references to that keyword on the left-hand-side
957of 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
969bar-alias @result{} 10
970(set! bar-alias 20)
971bar @result{} 20
972(set! bar 30)
973bar-alias @result{} 30
974@end example
975@end deffn
976
ecb87335 977There is an extension to identifier-syntax which allows it to handle the
69724dde
AW
978@code{set!} case as well:
979
980@deffn {Syntax} identifier-syntax (var exp1) ((set! var val) exp2)
981Create a variable transformer. The first clause is used for references
982to the variable in operator or operand position, and the second for
983appearances of the variable on the left-hand-side of an assignment.
984
985For example, the previous @code{bar-alias} example could be expressed
986more 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
996As before, the templates in @code{identifier-syntax} forms do not need
997wrapping in @code{#'} syntax forms.
998@end deffn
999
6ffd4131 1000
729b62bd
IP
1001@node Syntax Parameters
1002@subsection Syntax Parameters
1003
866ecf54
AW
1004Syntax parameters@footnote{Described in the paper @cite{Keeping it Clean
1005with Syntax Parameters} by Barzilay, Culpepper and Flatt.} are a
1006mechanism for rebinding a macro definition within the dynamic extent of
1007a macro expansion. This provides a convenient solution to one of the
1008most common types of unhygienic macro: those that introduce a unhygienic
1009binding each time the macro is used. Examples include a @code{lambda}
1010form with a @code{return} keyword, or class macros that introduce a
1011special @code{self} binding.
729b62bd
IP
1012
1013With syntax parameters, instead of introducing the binding
866ecf54
AW
1014unhygienically each time, we instead create one binding for the keyword,
1015which we can then adjust later when we want the keyword to have a
1016different meaning. As no new bindings are introduced, hygiene is
1017preserved. This is similar to the dynamic binding mechanisms we have at
1018run-time (@pxref{SRFI-39, parameters}), except that the dynamic binding
1019only occurs during macro expansion. The code after macro expansion
1020remains lexically scoped.
729b62bd
IP
1021
1022@deffn {Syntax} define-syntax-parameter keyword transformer
866ecf54
AW
1023Binds @var{keyword} to the value obtained by evaluating
1024@var{transformer}. The @var{transformer} provides the default expansion
1025for 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}
1029is supposed to be used in conjunction with another macro, for example:
729b62bd
IP
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{}
1038Adjusts @var{keyword} @dots{} to use the values obtained by evaluating
866ecf54
AW
1039their @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
1042binding is not shadowed, but adjusted, and so uses of the keyword in the
1043expansion of @var{exp} @dots{} use the new transformers. This is
1044somewhat similar to how @code{parameterize} adjusts the values of
1045regular parameters, rather than creating new bindings.
729b62bd
IP
1046
1047@example
1048(define-syntax lambda^
1049 (syntax-rules ()
866ecf54 1050 [(lambda^ argument-list body body* ...)
729b62bd
IP
1051 (lambda argument-list
1052 (call-with-current-continuation
1053 (lambda (escape)
866ecf54
AW
1054 ;; In the body we adjust the 'return' keyword so that calls
1055 ;; to 'return' are replaced with calls to the escape
1056 ;; continuation.
729b62bd
IP
1057 (syntax-parameterize ([return (syntax-rules ()
1058 [(return vals (... ...))
1059 (escape vals (... ...))])])
866ecf54 1060 body body* ...))))]))
729b62bd 1061
866ecf54 1062;; Now we can write functions that return early. Here, 'product' will
729b62bd
IP
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
e4955559
AW
1076@node Eval When
1077@subsection Eval-when
1078
6ffd4131
AW
1079As @code{syntax-case} macros have the whole power of Scheme available to them,
1080they present a problem regarding time: when a macro runs, what parts of the
1081program are available for the macro to use?
e4955559 1082
6ffd4131
AW
1083The 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
1085expansion-time, as well as at run-time. Additionally, top-level syntactic
1086definitions within one compilation unit made by @code{define-syntax} are also
1087evaluated at expansion time, in the order that they appear in the compilation
1088unit (file).
1089
1090But if a syntactic definition needs to call out to a normal procedure at
1091expansion-time, it might well need need special declarations to indicate that
1092the procedure should be made available at expansion-time.
1093
1094For 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
e4955559 1103
6ffd4131
AW
1104It works at a REPL because the expressions are evaluated one-by-one, in order,
1105but if placed in a file, the expressions are expanded one-by-one, but not
1106evaluated until the compiled file is loaded.
1107
1108The 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...
1120Evaluate @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.
1123Other uses of @code{eval-when} may void your warranty or poison your cat.
1124@end deffn
1125
67915ab0
AW
1126@node Macro Expansion
1127@subsection Macro Expansion
1128
1129Usually, macros are expanded on behalf of the user as needed. Macro
1130expansion is an integral part of @code{eval} and @code{compile}. Users
1131can also expand macros at the REPL prompt via the @code{expand} REPL
1132command; @xref{Compile Commands}.
1133
1134Macros can also be expanded programmatically, via @code{macroexpand},
1135but the details get a bit hairy for two reasons.
1136
1137The first complication is that the result of macro-expansion isn't
1138Scheme: it's Tree-IL, Guile's high-level intermediate language.
1139@xref{Tree-IL}. As ``hygienic macros'' can produce identifiers that are
1140distinct but have the same name, the output format needs to be able to
1141represent distinctions between variable identities and names. Again,
1142see @xref{Tree-IL} for all the details. The easiest thing is to just
1143run @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
1156The second complication involves @code{eval-when}. As an example, what
1157would 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
1165The answer is that it depends who is macro-expanding, and why. Do you
1166define the macro in the current environment? Residualize a macro
1167definition? Both? Neither? The default is to expand in ``eval'' mode,
1168which means an @code{eval-when} clauses will only proceed when
1169@code{eval} (or @code{expand}) is in its condition set. Top-level
1170macros will be @code{eval}'d in the top-level environment.
1171
1172In this way @code{(macroexpand @var{foo})} is equivalent to
1173@code{(macroexpand @var{foo} 'e '(eval))}. The second argument is the
1174mode (@code{'e} for ``eval'') and the second is the
1175eval-syntax-expanders-when parameter (only @code{eval} in this default
1176setting).
1177
1178But if you are compiling the macro definition, probably you want to
1179reify the macro definition itself. In that case you pass @code{'c} as
1180the second argument to @code{macroexpand}. But probably you want the
1181macro 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
1185Compiler}.
1186
1187It's a terrible interface; we know. The macroexpander is somewhat
1188tricksy regarding modes, so unless you are building a macro-expanding
1189tool, we suggest to avoid invoking it directly.
1190
1191
6ffd4131
AW
1192@node Internal Macros
1193@subsection Internal Macros
e4955559
AW
1194
1195@deffn {Scheme Procedure} make-syntax-transformer name type binding
6ffd4131
AW
1196Construct a syntax transformer object. This is part of Guile's low-level support
1197for syntax-case.
e4955559
AW
1198@end deffn
1199
1200@deffn {Scheme Procedure} macro? obj
1201@deffnx {C Function} scm_macro_p (obj)
a4b4fbbd
JE
1202Return @code{#t} if @var{obj} is a syntax transformer, or @code{#f}
1203otherwise.
6ffd4131
AW
1204
1205Note that it's a bit difficult to actually get a macro as a first-class object;
1206simply naming it (like @code{case}) will produce a syntax error. But it is
1207possible to get these objects using @code{module-ref}:
1208
1209@example
1210(macro? (module-ref (current-module) 'case))
1211@result{} #t
1212@end example
e4955559
AW
1213@end deffn
1214
1215@deffn {Scheme Procedure} macro-type m
1216@deffnx {C Function} scm_macro_type (m)
6ffd4131
AW
1217Return the @var{type} that was given when @var{m} was constructed, via
1218@code{make-syntax-transformer}.
e4955559
AW
1219@end deffn
1220
1221@deffn {Scheme Procedure} macro-name m
1222@deffnx {C Function} scm_macro_name (m)
1223Return the name of the macro @var{m}.
1224@end deffn
1225
e4955559
AW
1226@deffn {Scheme Procedure} macro-binding m
1227@deffnx {C Function} scm_macro_binding (m)
1228Return the binding of the macro @var{m}.
1229@end deffn
1230
6ffd4131
AW
1231@deffn {Scheme Procedure} macro-transformer m
1232@deffnx {C Function} scm_macro_transformer (m)
1233Return the transformer of the macro @var{m}. This will return a procedure, for
1234which one may ask the docstring. That's the whole reason this section is
1235documented. Actually a part of the result of @code{macro-binding}.
1236@end deffn
1237
e4955559
AW
1238
1239@c Local Variables:
1240@c TeX-master: "guile.texi"
1241@c End: