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