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