A start at syntax-rules docs
[bpt/guile.git] / doc / ref / api-macros.texi
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
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}.
15
16 @cindex 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:
22
23 @lisp
24 (@var{macro-name} @var{macro-args} @dots{})
25 @end lisp
26
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.
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
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:
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
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
65 @ref{Syntax Case}.
66
67 @deffn {Syntax} define-syntax keyword transformer
68 Bind @var{keyword} to the syntax transformer obtained by evaluating
69 @var{transformer}.
70
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}.
73 @end deffn
74
75 One can also establish local syntactic bindings with @code{let-syntax}.
76
77 @deffn {Syntax} let-syntax ((keyword transformer) ...) exp...
78 Bind @var{keyword...} to @var{transformer...} while expanding @var{exp...}.
79
80 A @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
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
98 @code{letrec-syntax}.
99
100 @deffn {Syntax} letrec-syntax ((keyword transformer) ...) exp...
101 Bind @var{keyword...} to @var{transformer...} while expanding @var{exp...}.
102
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}.
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
128 a beauty worthy of Scheme.
129
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.
133
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.
138 @end deffn
139
140 @subsubsection Patterns
141
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{...}).
148
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.
153
154 @example
155 (define-syntax kwote
156 (syntax-rules ()
157 ((kwote exp)
158 (quote exp))))
159 (kwote (foo . bar))
160 @result{} (foo . bar)
161 @end example
162
163 An improper list of patterns matches as rest arguments do:
164
165 @example
166 (define-syntax let1
167 (syntax-rules ()
168 ((_ (var val) . exps)
169 (let ((var val)) . exps))))
170 @end example
171
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
176 ellipsis.
177
178 @example
179 (define-syntax let1
180 (syntax-rules ()
181 ((_ (var val) exp ...)
182 (let ((var val)) exp ...))))
183 @end example
184
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:
189
190 @example
191 (define-syntax let1
192 (syntax-rules ()
193 ((_ (var val) exp exp* ...)
194 (let ((var val)) exp exp* ...))))
195 @end example
196
197 A vector of patterns matches a vector whose contents match the patterns,
198 including ellipsizing and tail patterns.
199
200 @example
201 (define-syntax letv
202 (syntax-rules ()
203 ((_ #((var val) ...) exp exp* ...)
204 (let ((var val) ...) exp exp* ...))))
205 (letv #((foo 'bar)) foo)
206 @result{} foo
207 @end example
208
209 Literals are used to match specific datums in an expression, like the use of
210 @code{=>} and @code{else} in @code{cond} expressions.
211
212 @example
213 (define-syntax cond1
214 (syntax-rules (=> else)
215 ((cond1 test => fun)
216 (let ((exp test))
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* ...))))
222
223 (define (square x) (* x x))
224 (cond1 10 => square)
225 @result{} 100
226 (let ((=> #t))
227 (cond1 10 => square))
228 @result{} #<procedure square (x)>
229 @end example
230
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
235 accepted.}.
236
237 If a pattern is not a list, vector, or an identifier, it matches as a literal,
238 with @code{equal?}.
239
240 @example
241 (define-syntax define-matcher-macro
242 (syntax-rules ()
243 ((_ name lit)
244 (define-syntax name
245 (syntax-rules ()
246 ((_ lit) #t)
247 ((_ else) #f))))))
248
249 (define-matcher-macro is-literal-foo? "foo")
250
251 (is-literal-foo? "foo")
252 @result{} #t
253 (is-literal-foo? "bar")
254 @result{} #f
255 (let ((foo "foo"))
256 (is-literal-foo? foo))
257 @result{} #f
258 @end example
259
260 The last example indicates that matching happens at expansion-time, not
261 at run-time.
262
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:
268
269 @example
270 (define-syntax when
271 (syntax-rules ()
272 ((when c e ...)
273 (if c (begin e ...)))))
274
275 (define-syntax when
276 (syntax-rules ()
277 ((_ c e ...)
278 (if c (begin e ...)))))
279
280 (define-syntax when
281 (syntax-rules ()
282 ((something-else-entirely c e ...)
283 (if c (begin e ...)))))
284 @end example
285
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.
289
290 @subsubsection Hygiene
291
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
296 expression.
297
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
301 macro expansion.
302
303 Consider the definition of @code{my-or} from the previous section:
304
305 @example
306 (define-syntax my-or
307 (syntax-rules ()
308 ((my-or)
309 #t)
310 ((my-or exp)
311 exp)
312 ((my-or exp rest ...)
313 (let ((t exp))
314 (if exp
315 exp
316 (my-or rest ...))))))
317 @end example
318
319 A naive expansion of @code{(let ((t #t)) (my-or #f t))} would yield:
320
321 @example
322 (let ((t #t))
323 (let ((t #f))
324 (if t t t)))
325 @result{} #f
326 @end example
327
328 @noindent
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.
332
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.
336
337 @subsubsection Further Information
338
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
341 Scheme}.
342
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.
350
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}.
356
357 @node Syntax Case
358 @subsection Support for the @code{syntax-case} System
359
360 @node Defmacros
361 @subsection Lisp-style Macro Definitions
362
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
370 @code{define}.
371
372 @fnindex defmacro
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:
377
378 @lisp
379 (defmacro @var{name} (@var{args} @dots{}) @var{body} @dots{})
380 @end lisp
381
382 @noindent
383 is the same as
384
385 @lisp
386 (define-macro (@var{name} @var{args} @dots{}) @var{body} @dots{})
387 @end lisp
388
389 @noindent
390 The difference is analogous to the corresponding difference between
391 Lisp's @code{defun} and Scheme's @code{define}.
392
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
395 @code{defmacro}:
396
397 @lisp
398 (defmacro false-if-exception (expr)
399 `(catch #t
400 (lambda () ,expr)
401 (lambda args #f)))
402 @end lisp
403
404 @noindent
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.
408 For example:
409
410 @lisp
411 (false-if-exception (open-input-file "may-not-exist"))
412 @equiv{}
413 (catch #t
414 (lambda () (open-input-file "may-not-exist"))
415 (lambda args #f))
416 @end lisp
417
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
422 with the new pair.
423 @end deffn
424
425
426 @node Identifier Macros
427 @subsection Identifier Macros
428
429 @node Eval When
430 @subsection Eval-when
431
432 @node Internal Macros
433 @subsection Internal Macros
434
435
436 Internally, Guile represents macros using a disjoint type.
437
438 @deffn {Scheme Procedure} make-syntax-transformer name type binding
439 @end deffn
440
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.
445 @end deffn
446
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.
454 @end deffn
455
456 @deffn {Scheme Procedure} macro-name m
457 @deffnx {C Function} scm_macro_name (m)
458 Return the name of the macro @var{m}.
459 @end deffn
460
461 @deffn {Scheme Procedure} macro-transformer m
462 @deffnx {C Function} scm_macro_transformer (m)
463 Return the transformer of the macro @var{m}.
464 @end deffn
465
466 @deffn {Scheme Procedure} macro-binding m
467 @deffnx {C Function} scm_macro_binding (m)
468 Return the binding of the macro @var{m}.
469 @end deffn
470
471
472 @c Local Variables:
473 @c TeX-master: "guile.texi"
474 @c End: