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.
11 At its best, programming in Lisp is an iterative process of building up a
12 language appropriate to the problem at hand, and then solving the problem in
13 that language. Defining new procedures is part of that, but Lisp also allows
14 the user to extend its syntax, with its famous @dfn{macros}.
17 @cindex transformation
18 Macros are syntactic extensions which cause the expression that they appear in
19 to be transformed in some way @emph{before} being evaluated. In expressions that
20 are intended for macro transformation, the identifier that names the relevant
21 macro must appear as the first element, like this:
24 (@var{macro-name} @var{macro-args} @dots{})
27 @cindex macro expansion
28 Macro expansion is a separate phase of evaluation, run before code is
29 interpreted or compiled. A macro is a program that runs on programs, translating
30 an embedded language into core Scheme.
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.
43 @subsection Defining Macros
45 A macro is a binding between a keyword and a syntax transformer. Since it's
46 difficult to discuss @code{define-syntax} without discussing the format of
47 transformers, consider the following example macro definition:
52 ((when condition exp ...)
58 (display "let's go\n"))
63 In this example, the @code{when} binding is bound with @code{define-syntax}.
64 Syntax transformers are discussed in more depth in @ref{Syntax Rules} and
67 @deffn {Syntax} define-syntax keyword transformer
68 Bind @var{keyword} to the syntax transformer obtained by evaluating
71 After a macro has been defined, further instances of @var{keyword} in Scheme
72 source code will invoke the syntax transformer defined by @var{transformer}.
75 One can also establish local syntactic bindings with @code{let-syntax}.
77 @deffn {Syntax} let-syntax ((keyword transformer) ...) exp...
78 Bind @var{keyword...} to @var{transformer...} while expanding @var{exp...}.
80 A @code{let-syntax} binding only exists at expansion-time.
85 ((unless condition exp ...)
91 @result{} "rock rock rock"
95 A @code{define-syntax} form is valid anywhere a definition may appear: at the
96 top-level, or locally. Just as a local @code{define} expands out to an instance
97 of @code{letrec}, a local @code{define-syntax} expands out to
100 @deffn {Syntax} letrec-syntax ((keyword transformer) ...) exp...
101 Bind @var{keyword...} to @var{transformer...} while expanding @var{exp...}.
103 In the spirit of @code{letrec} versus @code{let}, an expansion produced by
104 @var{transformer} may reference a @var{keyword} bound by the
105 same @var{letrec-syntax}.
108 (letrec-syntax ((my-or
114 ((my-or exp rest ...)
118 (my-or rest ...)))))))
119 (my-or #f "rockaway beach"))
120 @result{} "rockaway beach"
125 @subsection Syntax-rules Macros
127 @code{syntax-rules} macros are simple, pattern-driven syntax transformers, with
128 a beauty worthy of Scheme.
130 @deffn {Syntax} syntax-rules literals (pattern template)...
131 A @code{syntax-rules} macro consists of three parts: the literals (if any), the
132 patterns, and as many templates as there are patterns.
134 When the syntax expander sees the invocation of a @code{syntax-rules} macro, it
135 matches the expression against the patterns, in order, and rewrites the
136 expression using the template from the first matching pattern. If no pattern
137 matches, a syntax error is signalled.
140 @subsubsection Patterns
142 We have already seen some examples of patterns in the previous section:
143 @code{(unless condition exp ...)}, @code{(my-or exp)}, and so on. A pattern is
144 structured like the expression that it is to match. It can have nested structure
145 as well, like @code{(let ((var val) ...) exp exp* ...)}. Broadly speaking,
146 patterns are made of lists, improper lists, vectors, identifiers, and datums.
147 Users can match a sequence of patterns using the ellipsis (@code{...}).
149 Identifiers in a pattern are called @dfn{literals} if they are present in the
150 @code{syntax-rules} literals list, and @dfn{pattern variables} otherwise. When
151 building up the macro output, the expander replaces instances of a pattern
152 variable in the template with the matched subexpression.
160 @result{} (foo . bar)
163 An improper list of patterns matches as rest arguments do:
168 ((_ (var val) . exps)
169 (let ((var val)) . exps))))
172 However this definition of @code{let1} probably isn't what you want, as the tail
173 pattern @var{exps} will match non-lists, like @code{(let1 (foo 'bar) . baz)}. So
174 often instead of using improper lists as patterns, ellipsized patterns are
175 better. Instances of a pattern variable in the template must be followed by an
181 ((_ (var val) exp ...)
182 (let ((var val)) exp ...))))
185 This @code{let1} probably still doesn't do what we want, because the body
186 matches sequences of zero expressions, like @code{(let1 (foo 'bar))}. In this
187 case we need to assert we have at least one body expression. A common idiom for
188 this is to name the ellipsized pattern variable with an asterisk:
193 ((_ (var val) exp exp* ...)
194 (let ((var val)) exp exp* ...))))
197 A vector of patterns matches a vector whose contents match the patterns,
198 including ellipsizing and tail patterns.
203 ((_ #((var val) ...) exp exp* ...)
204 (let ((var val) ...) exp exp* ...))))
205 (letv #((foo 'bar)) foo)
209 Literals are used to match specific datums in an expression, like the use of
210 @code{=>} and @code{else} in @code{cond} expressions.
214 (syntax-rules (=> else)
217 (if exp (fun exp) #f)))
218 ((cond1 test exp exp* ...)
219 (if test (begin exp exp* ...)))
220 ((cond1 else exp exp* ...)
221 (begin exp exp* ...))))
223 (define (square x) (* x x))
227 (cond1 10 => square))
228 @result{} #<procedure square (x)>
231 A literal matches an input expression if the input expression is an identifier
232 with the same name as the literal, and both are unbound@footnote{Language
233 lawyers probably see the need here for use of @code{literal-identifier=?} rather
234 than @code{free-identifier=?}, and would probably be correct. Patches
237 If a pattern is not a list, vector, or an identifier, it matches as a literal,
241 (define-syntax define-matcher-macro
249 (define-matcher-macro is-literal-foo? "foo")
251 (is-literal-foo? "foo")
253 (is-literal-foo? "bar")
256 (is-literal-foo? foo))
260 The last example indicates that matching happens at expansion-time, not
263 Syntax-rules macros are always used as @code{(@var{macro} . @var{args})}, and
264 the @var{macro} will always be a symbol. Correspondingly, a @code{syntax-rules}
265 pattern must be a list (proper or improper), and the first pattern in that list
266 must be an identifier. Incidentally it can be any identifier -- it doesn't have
267 to actually be the name of the macro. Thus the following three are equivalent:
273 (if c (begin e ...)))))
278 (if c (begin e ...)))))
282 ((something-else-entirely c e ...)
283 (if c (begin e ...)))))
286 For clarity, use one of the first two variants. Also note that since the pattern
287 variable will always match the macro itself (e.g., @code{cond1}), it is actually
288 left unbound in the template.
290 @subsubsection Hygiene
292 @code{syntax-rules} macros have a magical property: they preserve referential
293 transparency. When you read a macro definition, any free bindings in that macro
294 are resolved relative to the macro definition; and when you read a macro
295 instantiation, all free bindings in that expression are resolved relative to the
298 This property is sometimes known as @dfn{hygiene}, and it does aid in code
299 cleanliness. In your macro definitions, you can feel free to introduce temporary
300 variables, without worrying about inadvertantly introducing bindings into the
303 Consider the definition of @code{my-or} from the previous section:
312 ((my-or exp rest ...)
316 (my-or rest ...))))))
319 A naive expansion of @code{(let ((t #t)) (my-or #f t))} would yield:
329 Which clearly is not what we want. Somehow the @code{t} in the definition is
330 distinct from the @code{t} at the site of use; and it is indeed this distinction
331 that is maintained by the syntax expander, when expanding hygienic macros.
333 This discussion is mostly relevant in the context of traditional Lisp macros
334 (@pxref{Defmacros}), which do not preserve referential transparency. Hygiene
335 adds to the expressive power of Scheme.
337 @subsubsection Further Information
339 For a formal definition of @code{syntax-rules} and its pattern language, see
340 @xref{Macros, , Macros, r5rs, Revised(5) Report on the Algorithmic Language
343 @code{syntax-rules} macros are simple and clean, but do they have limitations.
344 They do not lend themselves to expressive error messages: patterns either match
345 or they don't. Their ability to generate code is limited to template-driven
346 expansion; often one needs to define a number of helper macros to get real work
347 done. Sometimes one wants to introduce a binding into the lexical context of the
348 generated code; this is impossible with @code{syntax-rules}. Relatedly, they
349 cannot programmatically generate identifiers.
351 The solution to all of these problems is to use @code{syntax-case} if you need
352 its features. But if for some reason you're stuck with @code{syntax-rules}, you
353 might enjoy Joe Marshall's
354 @uref{http://sites.google.com/site/evalapply/eccentric.txt,@code{syntax-rules}
355 Primer for the Merely Eccentric}.
358 @subsection Support for the @code{syntax-case} System
361 @subsection Lisp-style Macro Definitions
363 In Lisp-like languages, the traditional way to define macros is very
364 similar to procedure definitions. The key differences are that the
365 macro definition body should return a list that describes the
366 transformed expression, and that the definition is marked as a macro
367 definition (rather than a procedure definition) by the use of a
368 different definition keyword: in Lisp, @code{defmacro} rather than
369 @code{defun}, and in Scheme, @code{define-macro} rather than
373 @fnindex define-macro
374 Guile supports this style of macro definition using both @code{defmacro}
375 and @code{define-macro}. The only difference between them is how the
376 macro name and arguments are grouped together in the definition:
379 (defmacro @var{name} (@var{args} @dots{}) @var{body} @dots{})
386 (define-macro (@var{name} @var{args} @dots{}) @var{body} @dots{})
390 The difference is analogous to the corresponding difference between
391 Lisp's @code{defun} and Scheme's @code{define}.
393 @code{false-if-exception}, from the @file{boot-9.scm} file in the Guile
394 distribution, is a good example of macro definition using
398 (defmacro false-if-exception (expr)
405 The effect of this definition is that expressions beginning with the
406 identifier @code{false-if-exception} are automatically transformed into
407 a @code{catch} expression following the macro definition specification.
411 (false-if-exception (open-input-file "may-not-exist"))
414 (lambda () (open-input-file "may-not-exist"))
418 @deffn {Scheme Procedure} cons-source xorig x y
419 @deffnx {C Function} scm_cons_source (xorig, x, y)
420 Create and return a new pair whose car and cdr are @var{x} and @var{y}.
421 Any source properties associated with @var{xorig} are also associated
426 @node Identifier Macros
427 @subsection Identifier Macros
430 @subsection Eval-when
432 @node Internal Macros
433 @subsection Internal Macros
436 Internally, Guile represents macros using a disjoint type.
438 @deffn {Scheme Procedure} make-syntax-transformer name type binding
441 @deffn {Scheme Procedure} macro? obj
442 @deffnx {C Function} scm_macro_p (obj)
443 Return @code{#t} if @var{obj} is a regular macro, a memoizing macro, a
444 syntax transformer, or a syntax-case macro.
447 @deffn {Scheme Procedure} macro-type m
448 @deffnx {C Function} scm_macro_type (m)
449 Return one of the symbols @code{syntax}, @code{macro},
450 @code{macro!}, or @code{syntax-case}, depending on whether
451 @var{m} is a syntax transformer, a regular macro, a memoizing
452 macro, or a syntax-case macro, respectively. If @var{m} is
453 not a macro, @code{#f} is returned.
456 @deffn {Scheme Procedure} macro-name m
457 @deffnx {C Function} scm_macro_name (m)
458 Return the name of the macro @var{m}.
461 @deffn {Scheme Procedure} macro-transformer m
462 @deffnx {C Function} scm_macro_transformer (m)
463 Return the transformer of the macro @var{m}.
466 @deffn {Scheme Procedure} macro-binding m
467 @deffnx {C Function} scm_macro_binding (m)
468 Return the binding of the macro @var{m}.
473 @c TeX-master: "guile.texi"