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