new syntax procedures to (system syntax)
[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
68fcf711
AW
709Guile also offers some more experimental interfaces in a separate
710module. As was the case with the Large Hadron Collider, it is unclear
711to our senior macrologists whether adding these interfaces will result
712in awesomeness or in the destruction of Guile via the creation of a
713singularity. We will preserve their functionality through the 2.0
714series, but we reserve the right to modify them in a future stable
715series, to a more than usual degree.
716
717@example
718(use-modules (system syntax))
719@end example
720
1ace4fbf
AW
721@deffn {Scheme Procedure} syntax-module id
722Return the name of the module whose source contains the identifier
723@var{id}.
724@end deffn
725
9b0975f1
AW
726@deffn {Scheme Procedure} syntax-local-binding id
727Resolve the identifer @var{id}, a syntax object, within the current
728lexical environment, and return two values, the binding type and a
729binding value. The binding type is a symbol, which may be one of the
730following:
731
732@table @code
733@item lexical
734A lexically-bound variable. The value is a unique token (in the sense
735of @code{eq?}) identifying this binding.
736@item macro
737A syntax transformer, either local or global. The value is the
738transformer procedure.
739@item pattern-variable
740A pattern variable, bound via syntax-case. The value is an opaque
741object, internal to the expander.
742@item displaced-lexical
743A lexical variable that has gone out of scope. This can happen if a
744badly-written procedural macro saves a syntax object, then attempts to
745introduce it in a context in which it is unbound. The value is
746@code{#f}.
747@item global
748A global binding. The value is a pair, whose head is the symbol, and
749whose tail is the name of the module in which to resolve the symbol.
750@item other
751Some other binding, like @code{lambda} or other core bindings. The
752value is @code{#f}.
753@end table
754
755This is a very low-level procedure, with limited uses. One case in
756which it is useful is to build abstractions that associate auxiliary
757information with macros:
758
759@example
760(define aux-property (make-object-property))
761(define-syntax-rule (with-aux aux value)
762 (let ((trans value))
763 (set! (aux-property trans) aux)
3d51e57c 764 trans))
9b0975f1
AW
765(define-syntax retrieve-aux
766 (lambda (x)
767 (syntax-case x ()
768 ((x id)
769 (call-with-values (lambda () (syntax-local-binding #'id))
770 (lambda (type val)
771 (with-syntax ((aux (datum->syntax #'here
772 (and (eq? type 'macro)
773 (aux-property val)))))
774 #''aux)))))))
775(define-syntax foo
776 (with-aux 'bar
777 (syntax-rules () ((_) 'foo))))
778(foo)
779@result{} foo
780(retrieve-aux foo)
781@result{} bar
782@end example
783
784@code{syntax-local-binding} must be called within the dynamic extent of
785a syntax transformer; to call it otherwise will signal an error.
786@end deffn
1fc8dcc7 787
3d51e57c
AW
788@deffn {Scheme Procedure} syntax-locally-bound-identifiers id
789Return a list of identifiers that were visible lexically when the
790identifier @var{id} was created, in order from outermost to innermost.
791
792This procedure is intended to be used in specialized procedural macros,
793to provide a macro with the set of bound identifiers that the macro can
794reference.
795
796As a technical implementation detail, the identifiers returned by
797@code{syntax-locally-bound-identifiers} will be anti-marked, like the
798syntax object that is given as input to a macro. This is to signal to
799the macro expander that these bindings were present in the original
800source, and do not need to be hygienically renamed, as would be the case
801with other introduced identifiers. See the discussion of hygiene in
802section 12.1 of the R6RS, for more information on marks.
803
804@example
805(define (local-lexicals id)
806 (filter (lambda (x)
807 (eq? (syntax-local-binding x) 'lexical))
808 (syntax-locally-bound-identifiers id)))
809(define-syntax lexicals
810 (lambda (x)
811 (syntax-case x ()
812 ((lexicals) #'(lexicals lexicals))
813 ((lexicals scope)
814 (with-syntax (((id ...) (local-lexicals #'scope)))
815 #'(list (cons 'id id) ...))))))
816
817(let* ((x 10) (x 20)) (lexicals))
818@result{} ((x . 10) (x . 20))
819@end example
820@end deffn
821
822
e4955559
AW
823@node Defmacros
824@subsection Lisp-style Macro Definitions
825
1fc8dcc7
AW
826The traditional way to define macros in Lisp is very similar to procedure
827definitions. The key differences are that the macro definition body should
828return a list that describes the transformed expression, and that the definition
829is marked as a macro definition (rather than a procedure definition) by the use
830of a different definition keyword: in Lisp, @code{defmacro} rather than
831@code{defun}, and in Scheme, @code{define-macro} rather than @code{define}.
e4955559
AW
832
833@fnindex defmacro
834@fnindex define-macro
835Guile supports this style of macro definition using both @code{defmacro}
836and @code{define-macro}. The only difference between them is how the
837macro name and arguments are grouped together in the definition:
838
839@lisp
840(defmacro @var{name} (@var{args} @dots{}) @var{body} @dots{})
841@end lisp
842
843@noindent
844is the same as
845
846@lisp
847(define-macro (@var{name} @var{args} @dots{}) @var{body} @dots{})
848@end lisp
849
850@noindent
851The difference is analogous to the corresponding difference between
852Lisp's @code{defun} and Scheme's @code{define}.
853
1fc8dcc7
AW
854Having read the previous section on @code{syntax-case}, it's probably clear that
855Guile actually implements defmacros in terms of @code{syntax-case}, applying the
856transformer on the expression between invocations of @code{syntax->datum} and
857@code{datum->syntax}. This realization leads us to the problem with defmacros,
858that they do not preserve referential transparency. One can be careful to not
859introduce bindings into expanded code, via liberal use of @code{gensym}, but
860there is no getting around the lack of referential transparency for free
861bindings in the macro itself.
e4955559 862
1fc8dcc7 863Even a macro as simple as our @code{when} from before is difficult to get right:
e4955559 864
1fc8dcc7
AW
865@example
866(define-macro (when cond exp . rest)
867 `(if ,cond
868 (begin ,exp . ,rest)))
e4955559 869
1fc8dcc7
AW
870(when #f (display "Launching missiles!\n"))
871@result{} #f
e4955559 872
1fc8dcc7
AW
873(let ((if list))
874 (when #f (display "Launching missiles!\n")))
875@print{} Launching missiles!
876@result{} (#f #<unspecified>)
877@end example
878
879Guile's perspective is that defmacros have had a good run, but that modern
880macros should be written with @code{syntax-rules} or @code{syntax-case}. There
881are still many uses of defmacros within Guile itself, but we will be phasing
882them out over time. Of course we won't take away @code{defmacro} or
883@code{define-macro} themselves, as there is lots of code out there that uses
884them.
e4955559
AW
885
886
887@node Identifier Macros
888@subsection Identifier Macros
889
6ffd4131
AW
890When the syntax expander sees a form in which the first element is a macro, the
891whole form gets passed to the macro's syntax transformer. One may visualize this
892as:
893
894@example
895(define-syntax foo foo-transformer)
896(foo @var{arg}...)
897;; expands via
898(foo-transformer #'(foo @var{arg}...))
899@end example
900
901If, on the other hand, a macro is referenced in some other part of a form, the
902syntax transformer is invoked with only the macro reference, not the whole form.
903
904@example
905(define-syntax foo foo-transformer)
906foo
907;; expands via
908(foo-transformer #'foo)
909@end example
910
911This allows bare identifier references to be replaced programmatically via a
912macro. @code{syntax-rules} provides some syntax to effect this transformation
913more easily.
914
915@deffn {Syntax} identifier-syntax exp
ecb87335 916Returns a macro transformer that will replace occurrences of the macro with
6ffd4131
AW
917@var{exp}.
918@end deffn
919
920For example, if you are importing external code written in terms of @code{fx+},
921the fixnum addition operator, but Guile doesn't have @code{fx+}, you may use the
922following to replace @code{fx+} with @code{+}:
923
924@example
925(define-syntax fx+ (identifier-syntax +))
926@end example
927
69724dde
AW
928There is also special support for recognizing identifiers on the
929left-hand side of a @code{set!} expression, as in the following:
930
931@example
932(define-syntax foo foo-transformer)
933(set! foo @var{val})
934;; expands via
935(foo-transformer #'(set! foo @var{val}))
936;; iff foo-transformer is a "variable transformer"
937@end example
938
939As the example notes, the transformer procedure must be explicitly
940marked as being a ``variable transformer'', as most macros aren't
7545ddd4 941written to discriminate on the form in the operator position.
69724dde
AW
942
943@deffn {Scheme Procedure} make-variable-transformer transformer
944Mark the @var{transformer} procedure as being a ``variable
945transformer''. In practice this means that, when bound to a syntactic
946keyword, it may detect references to that keyword on the left-hand-side
947of a @code{set!}.
948
949@example
950(define bar 10)
951(define-syntax bar-alias
952 (make-variable-transformer
953 (lambda (x)
954 (syntax-case x (set!)
955 ((set! var val) #'(set! bar val))
956 ((var arg ...) #'(bar arg ...))
957 (var (identifier? #'var) #'bar)))))
958
959bar-alias @result{} 10
960(set! bar-alias 20)
961bar @result{} 20
962(set! bar 30)
963bar-alias @result{} 30
964@end example
965@end deffn
966
ecb87335 967There is an extension to identifier-syntax which allows it to handle the
69724dde
AW
968@code{set!} case as well:
969
970@deffn {Syntax} identifier-syntax (var exp1) ((set! var val) exp2)
971Create a variable transformer. The first clause is used for references
972to the variable in operator or operand position, and the second for
973appearances of the variable on the left-hand-side of an assignment.
974
975For example, the previous @code{bar-alias} example could be expressed
976more succinctly like this:
977
978@example
979(define-syntax bar-alias
980 (identifier-syntax
981 (var bar)
982 ((set! var val) (set! bar val))))
983@end example
984
985@noindent
986As before, the templates in @code{identifier-syntax} forms do not need
987wrapping in @code{#'} syntax forms.
988@end deffn
989
6ffd4131 990
729b62bd
IP
991@node Syntax Parameters
992@subsection Syntax Parameters
993
866ecf54
AW
994Syntax parameters@footnote{Described in the paper @cite{Keeping it Clean
995with Syntax Parameters} by Barzilay, Culpepper and Flatt.} are a
996mechanism for rebinding a macro definition within the dynamic extent of
997a macro expansion. This provides a convenient solution to one of the
998most common types of unhygienic macro: those that introduce a unhygienic
999binding each time the macro is used. Examples include a @code{lambda}
1000form with a @code{return} keyword, or class macros that introduce a
1001special @code{self} binding.
729b62bd
IP
1002
1003With syntax parameters, instead of introducing the binding
866ecf54
AW
1004unhygienically each time, we instead create one binding for the keyword,
1005which we can then adjust later when we want the keyword to have a
1006different meaning. As no new bindings are introduced, hygiene is
1007preserved. This is similar to the dynamic binding mechanisms we have at
1008run-time (@pxref{SRFI-39, parameters}), except that the dynamic binding
1009only occurs during macro expansion. The code after macro expansion
1010remains lexically scoped.
729b62bd
IP
1011
1012@deffn {Syntax} define-syntax-parameter keyword transformer
866ecf54
AW
1013Binds @var{keyword} to the value obtained by evaluating
1014@var{transformer}. The @var{transformer} provides the default expansion
1015for the syntax parameter, and in the absence of
1016@code{syntax-parameterize}, is functionally equivalent to
1017@code{define-syntax}. Usually, you will just want to have the
1018@var{transformer} throw a syntax error indicating that the @var{keyword}
1019is supposed to be used in conjunction with another macro, for example:
729b62bd
IP
1020@example
1021(define-syntax-parameter return
1022 (lambda (stx)
1023 (syntax-violation 'return "return used outside of a lambda^" stx)))
1024@end example
1025@end deffn
1026
1027@deffn {Syntax} syntax-parameterize ((keyword transformer) @dots{}) exp @dots{}
1028Adjusts @var{keyword} @dots{} to use the values obtained by evaluating
866ecf54
AW
1029their @var{transformer} @dots{}, in the expansion of the @var{exp}
1030@dots{} forms. Each @var{keyword} must be bound to a syntax-parameter.
1031@code{syntax-parameterize} differs from @code{let-syntax}, in that the
1032binding is not shadowed, but adjusted, and so uses of the keyword in the
1033expansion of @var{exp} @dots{} use the new transformers. This is
1034somewhat similar to how @code{parameterize} adjusts the values of
1035regular parameters, rather than creating new bindings.
729b62bd
IP
1036
1037@example
1038(define-syntax lambda^
1039 (syntax-rules ()
866ecf54 1040 [(lambda^ argument-list body body* ...)
729b62bd
IP
1041 (lambda argument-list
1042 (call-with-current-continuation
1043 (lambda (escape)
866ecf54
AW
1044 ;; In the body we adjust the 'return' keyword so that calls
1045 ;; to 'return' are replaced with calls to the escape
1046 ;; continuation.
729b62bd
IP
1047 (syntax-parameterize ([return (syntax-rules ()
1048 [(return vals (... ...))
1049 (escape vals (... ...))])])
866ecf54 1050 body body* ...))))]))
729b62bd 1051
866ecf54 1052;; Now we can write functions that return early. Here, 'product' will
729b62bd
IP
1053;; return immediately if it sees any 0 element.
1054(define product
1055 (lambda^ (list)
1056 (fold (lambda (n o)
1057 (if (zero? n)
1058 (return 0)
1059 (* n o)))
1060 1
1061 list)))
1062@end example
1063@end deffn
1064
1065
e4955559
AW
1066@node Eval When
1067@subsection Eval-when
1068
6ffd4131
AW
1069As @code{syntax-case} macros have the whole power of Scheme available to them,
1070they present a problem regarding time: when a macro runs, what parts of the
1071program are available for the macro to use?
e4955559 1072
6ffd4131
AW
1073The default answer to this question is that when you import a module (via
1074@code{define-module} or @code{use-modules}), that module will be loaded up at
1075expansion-time, as well as at run-time. Additionally, top-level syntactic
1076definitions within one compilation unit made by @code{define-syntax} are also
1077evaluated at expansion time, in the order that they appear in the compilation
1078unit (file).
1079
1080But if a syntactic definition needs to call out to a normal procedure at
1081expansion-time, it might well need need special declarations to indicate that
1082the procedure should be made available at expansion-time.
1083
1084For example, the following code will work at a REPL, but not in a file:
1085
1086@example
1087;; incorrect
1088(use-modules (srfi srfi-19))
1089(define (date) (date->string (current-date)))
1090(define-syntax %date (identifier-syntax (date)))
1091(define *compilation-date* %date)
1092@end example
e4955559 1093
6ffd4131
AW
1094It works at a REPL because the expressions are evaluated one-by-one, in order,
1095but if placed in a file, the expressions are expanded one-by-one, but not
1096evaluated until the compiled file is loaded.
1097
1098The fix is to use @code{eval-when}.
1099
1100@example
1101;; correct: using eval-when
1102(use-modules (srfi srfi-19))
1103(eval-when (compile load eval)
1104 (define (date) (date->string (current-date))))
1105(define-syntax %date (identifier-syntax (date)))
1106(define *compilation-date* %date)
1107@end example
1108
1109@deffn {Syntax} eval-when conditions exp...
1110Evaluate @var{exp...} under the given @var{conditions}. Valid conditions include
1111@code{eval}, @code{load}, and @code{compile}. If you need to use
1112@code{eval-when}, use it with all three conditions, as in the above example.
1113Other uses of @code{eval-when} may void your warranty or poison your cat.
1114@end deffn
1115
1116@node Internal Macros
1117@subsection Internal Macros
e4955559
AW
1118
1119@deffn {Scheme Procedure} make-syntax-transformer name type binding
6ffd4131
AW
1120Construct a syntax transformer object. This is part of Guile's low-level support
1121for syntax-case.
e4955559
AW
1122@end deffn
1123
1124@deffn {Scheme Procedure} macro? obj
1125@deffnx {C Function} scm_macro_p (obj)
6ffd4131
AW
1126Return @code{#t} iff @var{obj} is a syntax transformer.
1127
1128Note that it's a bit difficult to actually get a macro as a first-class object;
1129simply naming it (like @code{case}) will produce a syntax error. But it is
1130possible to get these objects using @code{module-ref}:
1131
1132@example
1133(macro? (module-ref (current-module) 'case))
1134@result{} #t
1135@end example
e4955559
AW
1136@end deffn
1137
1138@deffn {Scheme Procedure} macro-type m
1139@deffnx {C Function} scm_macro_type (m)
6ffd4131
AW
1140Return the @var{type} that was given when @var{m} was constructed, via
1141@code{make-syntax-transformer}.
e4955559
AW
1142@end deffn
1143
1144@deffn {Scheme Procedure} macro-name m
1145@deffnx {C Function} scm_macro_name (m)
1146Return the name of the macro @var{m}.
1147@end deffn
1148
e4955559
AW
1149@deffn {Scheme Procedure} macro-binding m
1150@deffnx {C Function} scm_macro_binding (m)
1151Return the binding of the macro @var{m}.
1152@end deffn
1153
6ffd4131
AW
1154@deffn {Scheme Procedure} macro-transformer m
1155@deffnx {C Function} scm_macro_transformer (m)
1156Return the transformer of the macro @var{m}. This will return a procedure, for
1157which one may ask the docstring. That's the whole reason this section is
1158documented. Actually a part of the result of @code{macro-binding}.
1159@end deffn
1160
e4955559
AW
1161
1162@c Local Variables:
1163@c TeX-master: "guile.texi"
1164@c End: