Commit | Line | Data |
---|---|---|
e4955559 AW |
1 | @c -*-texinfo-*- |
2 | @c This is part of the GNU Guile Reference Manual. | |
2d6a3144 MW |
3 | @c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004, 2009, 2010, 2011, |
4 | @c 2012, 2013, 2014 Free Software Foundation, Inc. | |
e4955559 AW |
5 | @c See the file guile.texi for copying conditions. |
6 | ||
e4955559 AW |
7 | @node Macros |
8 | @section Macros | |
9 | ||
10 | At its best, programming in Lisp is an iterative process of building up a | |
11 | language appropriate to the problem at hand, and then solving the problem in | |
12 | that language. Defining new procedures is part of that, but Lisp also allows | |
13 | the user to extend its syntax, with its famous @dfn{macros}. | |
14 | ||
15 | @cindex macros | |
16 | @cindex transformation | |
17 | Macros are syntactic extensions which cause the expression that they appear in | |
18 | to be transformed in some way @emph{before} being evaluated. In expressions that | |
19 | are intended for macro transformation, the identifier that names the relevant | |
20 | macro must appear as the first element, like this: | |
21 | ||
22 | @lisp | |
23 | (@var{macro-name} @var{macro-args} @dots{}) | |
24 | @end lisp | |
25 | ||
26 | @cindex macro expansion | |
cf14f301 LC |
27 | @cindex domain-specific language |
28 | @cindex embedded domain-specific language | |
29 | @cindex DSL | |
30 | @cindex EDSL | |
e4955559 AW |
31 | Macro expansion is a separate phase of evaluation, run before code is |
32 | interpreted or compiled. A macro is a program that runs on programs, translating | |
cf14f301 LC |
33 | an embedded language into core Scheme@footnote{These days such embedded |
34 | languages are often referred to as @dfn{embedded domain-specific | |
35 | languages}, or EDSLs.}. | |
e4955559 AW |
36 | |
37 | @menu | |
38 | * Defining Macros:: Binding macros, globally and locally. | |
39 | * Syntax Rules:: Pattern-driven macros. | |
40 | * Syntax Case:: Procedural, hygienic macros. | |
9b0975f1 | 41 | * Syntax Transformer Helpers:: Helpers for use in procedural macros. |
e4955559 AW |
42 | * Defmacros:: Lisp-style macros. |
43 | * Identifier Macros:: Identifier macros. | |
9b0975f1 | 44 | * Syntax Parameters:: Syntax Parameters. |
e4955559 | 45 | * Eval When:: Affecting the expand-time environment. |
67915ab0 | 46 | * Macro Expansion:: Procedurally expanding macros. |
e4955559 AW |
47 | * Internal Macros:: Macros as first-class values. |
48 | @end menu | |
49 | ||
50 | @node Defining Macros | |
51 | @subsection Defining Macros | |
52 | ||
53 | A macro is a binding between a keyword and a syntax transformer. Since it's | |
54 | difficult to discuss @code{define-syntax} without discussing the format of | |
55 | transformers, consider the following example macro definition: | |
56 | ||
57 | @example | |
58 | (define-syntax when | |
59 | (syntax-rules () | |
60 | ((when condition exp ...) | |
61 | (if condition | |
62 | (begin exp ...))))) | |
63 | ||
64 | (when #t | |
65 | (display "hey ho\n") | |
66 | (display "let's go\n")) | |
67 | @print{} hey ho | |
68 | @print{} let's go | |
69 | @end example | |
70 | ||
71 | In this example, the @code{when} binding is bound with @code{define-syntax}. | |
72 | Syntax transformers are discussed in more depth in @ref{Syntax Rules} and | |
73 | @ref{Syntax Case}. | |
74 | ||
75 | @deffn {Syntax} define-syntax keyword transformer | |
76 | Bind @var{keyword} to the syntax transformer obtained by evaluating | |
77 | @var{transformer}. | |
78 | ||
79 | After a macro has been defined, further instances of @var{keyword} in Scheme | |
80 | source code will invoke the syntax transformer defined by @var{transformer}. | |
81 | @end deffn | |
82 | ||
83 | One can also establish local syntactic bindings with @code{let-syntax}. | |
84 | ||
df0a1002 BT |
85 | @deffn {Syntax} let-syntax ((keyword transformer) @dots{}) exp1 exp2 @dots{} |
86 | Bind each @var{keyword} to its corresponding @var{transformer} while | |
87 | expanding @var{exp1} @var{exp2} @enddots{}. | |
e4955559 AW |
88 | |
89 | A @code{let-syntax} binding only exists at expansion-time. | |
90 | ||
91 | @example | |
92 | (let-syntax ((unless | |
93 | (syntax-rules () | |
94 | ((unless condition exp ...) | |
95 | (if (not condition) | |
96 | (begin exp ...)))))) | |
97 | (unless #t | |
98 | (primitive-exit 1)) | |
99 | "rock rock rock") | |
100 | @result{} "rock rock rock" | |
101 | @end example | |
102 | @end deffn | |
103 | ||
104 | A @code{define-syntax} form is valid anywhere a definition may appear: at the | |
105 | top-level, or locally. Just as a local @code{define} expands out to an instance | |
106 | of @code{letrec}, a local @code{define-syntax} expands out to | |
107 | @code{letrec-syntax}. | |
108 | ||
df0a1002 BT |
109 | @deffn {Syntax} letrec-syntax ((keyword transformer) @dots{}) exp1 exp2 @dots{} |
110 | Bind each @var{keyword} to its corresponding @var{transformer} while | |
111 | expanding @var{exp1} @var{exp2} @enddots{}. | |
e4955559 AW |
112 | |
113 | In the spirit of @code{letrec} versus @code{let}, an expansion produced by | |
114 | @var{transformer} may reference a @var{keyword} bound by the | |
115 | same @var{letrec-syntax}. | |
116 | ||
117 | @example | |
118 | (letrec-syntax ((my-or | |
119 | (syntax-rules () | |
120 | ((my-or) | |
121 | #t) | |
122 | ((my-or exp) | |
123 | exp) | |
124 | ((my-or exp rest ...) | |
125 | (let ((t exp)) | |
e006d87b MW |
126 | (if t |
127 | t | |
e4955559 AW |
128 | (my-or rest ...))))))) |
129 | (my-or #f "rockaway beach")) | |
130 | @result{} "rockaway beach" | |
131 | @end example | |
132 | @end deffn | |
133 | ||
134 | @node Syntax Rules | |
135 | @subsection Syntax-rules Macros | |
136 | ||
137 | @code{syntax-rules} macros are simple, pattern-driven syntax transformers, with | |
138 | a beauty worthy of Scheme. | |
139 | ||
1624e149 | 140 | @deffn {Syntax} syntax-rules literals (pattern template) @dots{} |
1fc8dcc7 AW |
141 | Create a syntax transformer that will rewrite an expression using the rules |
142 | embodied in the @var{pattern} and @var{template} clauses. | |
143 | @end deffn | |
144 | ||
e4955559 AW |
145 | A @code{syntax-rules} macro consists of three parts: the literals (if any), the |
146 | patterns, and as many templates as there are patterns. | |
147 | ||
148 | When the syntax expander sees the invocation of a @code{syntax-rules} macro, it | |
149 | matches the expression against the patterns, in order, and rewrites the | |
150 | expression using the template from the first matching pattern. If no pattern | |
151 | matches, a syntax error is signalled. | |
e4955559 AW |
152 | |
153 | @subsubsection Patterns | |
154 | ||
155 | We have already seen some examples of patterns in the previous section: | |
156 | @code{(unless condition exp ...)}, @code{(my-or exp)}, and so on. A pattern is | |
157 | structured like the expression that it is to match. It can have nested structure | |
158 | as well, like @code{(let ((var val) ...) exp exp* ...)}. Broadly speaking, | |
159 | patterns are made of lists, improper lists, vectors, identifiers, and datums. | |
160 | Users can match a sequence of patterns using the ellipsis (@code{...}). | |
161 | ||
162 | Identifiers in a pattern are called @dfn{literals} if they are present in the | |
163 | @code{syntax-rules} literals list, and @dfn{pattern variables} otherwise. When | |
164 | building up the macro output, the expander replaces instances of a pattern | |
165 | variable in the template with the matched subexpression. | |
166 | ||
167 | @example | |
168 | (define-syntax kwote | |
169 | (syntax-rules () | |
170 | ((kwote exp) | |
171 | (quote exp)))) | |
172 | (kwote (foo . bar)) | |
173 | @result{} (foo . bar) | |
174 | @end example | |
175 | ||
176 | An improper list of patterns matches as rest arguments do: | |
177 | ||
178 | @example | |
179 | (define-syntax let1 | |
180 | (syntax-rules () | |
181 | ((_ (var val) . exps) | |
182 | (let ((var val)) . exps)))) | |
183 | @end example | |
184 | ||
185 | However this definition of @code{let1} probably isn't what you want, as the tail | |
186 | pattern @var{exps} will match non-lists, like @code{(let1 (foo 'bar) . baz)}. So | |
187 | often instead of using improper lists as patterns, ellipsized patterns are | |
188 | better. Instances of a pattern variable in the template must be followed by an | |
189 | ellipsis. | |
190 | ||
191 | @example | |
192 | (define-syntax let1 | |
193 | (syntax-rules () | |
194 | ((_ (var val) exp ...) | |
195 | (let ((var val)) exp ...)))) | |
196 | @end example | |
197 | ||
198 | This @code{let1} probably still doesn't do what we want, because the body | |
199 | matches sequences of zero expressions, like @code{(let1 (foo 'bar))}. In this | |
200 | case we need to assert we have at least one body expression. A common idiom for | |
201 | this is to name the ellipsized pattern variable with an asterisk: | |
202 | ||
203 | @example | |
204 | (define-syntax let1 | |
205 | (syntax-rules () | |
206 | ((_ (var val) exp exp* ...) | |
207 | (let ((var val)) exp exp* ...)))) | |
208 | @end example | |
209 | ||
210 | A vector of patterns matches a vector whose contents match the patterns, | |
211 | including ellipsizing and tail patterns. | |
212 | ||
213 | @example | |
214 | (define-syntax letv | |
215 | (syntax-rules () | |
216 | ((_ #((var val) ...) exp exp* ...) | |
217 | (let ((var val) ...) exp exp* ...)))) | |
218 | (letv #((foo 'bar)) foo) | |
912f5f34 | 219 | @result{} bar |
e4955559 AW |
220 | @end example |
221 | ||
222 | Literals are used to match specific datums in an expression, like the use of | |
223 | @code{=>} and @code{else} in @code{cond} expressions. | |
224 | ||
225 | @example | |
226 | (define-syntax cond1 | |
227 | (syntax-rules (=> else) | |
228 | ((cond1 test => fun) | |
229 | (let ((exp test)) | |
230 | (if exp (fun exp) #f))) | |
231 | ((cond1 test exp exp* ...) | |
232 | (if test (begin exp exp* ...))) | |
233 | ((cond1 else exp exp* ...) | |
234 | (begin exp exp* ...)))) | |
235 | ||
236 | (define (square x) (* x x)) | |
237 | (cond1 10 => square) | |
238 | @result{} 100 | |
239 | (let ((=> #t)) | |
240 | (cond1 10 => square)) | |
241 | @result{} #<procedure square (x)> | |
242 | @end example | |
243 | ||
244 | A literal matches an input expression if the input expression is an identifier | |
245 | with the same name as the literal, and both are unbound@footnote{Language | |
246 | lawyers probably see the need here for use of @code{literal-identifier=?} rather | |
247 | than @code{free-identifier=?}, and would probably be correct. Patches | |
248 | accepted.}. | |
249 | ||
250 | If a pattern is not a list, vector, or an identifier, it matches as a literal, | |
251 | with @code{equal?}. | |
252 | ||
253 | @example | |
254 | (define-syntax define-matcher-macro | |
255 | (syntax-rules () | |
256 | ((_ name lit) | |
257 | (define-syntax name | |
258 | (syntax-rules () | |
259 | ((_ lit) #t) | |
260 | ((_ else) #f)))))) | |
261 | ||
262 | (define-matcher-macro is-literal-foo? "foo") | |
263 | ||
264 | (is-literal-foo? "foo") | |
265 | @result{} #t | |
266 | (is-literal-foo? "bar") | |
267 | @result{} #f | |
268 | (let ((foo "foo")) | |
269 | (is-literal-foo? foo)) | |
270 | @result{} #f | |
271 | @end example | |
272 | ||
273 | The last example indicates that matching happens at expansion-time, not | |
274 | at run-time. | |
275 | ||
276 | Syntax-rules macros are always used as @code{(@var{macro} . @var{args})}, and | |
277 | the @var{macro} will always be a symbol. Correspondingly, a @code{syntax-rules} | |
278 | pattern must be a list (proper or improper), and the first pattern in that list | |
279 | must be an identifier. Incidentally it can be any identifier -- it doesn't have | |
280 | to actually be the name of the macro. Thus the following three are equivalent: | |
281 | ||
282 | @example | |
283 | (define-syntax when | |
284 | (syntax-rules () | |
285 | ((when c e ...) | |
286 | (if c (begin e ...))))) | |
287 | ||
288 | (define-syntax when | |
289 | (syntax-rules () | |
290 | ((_ c e ...) | |
291 | (if c (begin e ...))))) | |
292 | ||
293 | (define-syntax when | |
294 | (syntax-rules () | |
295 | ((something-else-entirely c e ...) | |
296 | (if c (begin e ...))))) | |
297 | @end example | |
298 | ||
299 | For clarity, use one of the first two variants. Also note that since the pattern | |
300 | variable will always match the macro itself (e.g., @code{cond1}), it is actually | |
301 | left unbound in the template. | |
302 | ||
303 | @subsubsection Hygiene | |
304 | ||
305 | @code{syntax-rules} macros have a magical property: they preserve referential | |
306 | transparency. When you read a macro definition, any free bindings in that macro | |
307 | are resolved relative to the macro definition; and when you read a macro | |
308 | instantiation, all free bindings in that expression are resolved relative to the | |
309 | expression. | |
310 | ||
311 | This property is sometimes known as @dfn{hygiene}, and it does aid in code | |
312 | cleanliness. In your macro definitions, you can feel free to introduce temporary | |
ecb87335 | 313 | variables, without worrying about inadvertently introducing bindings into the |
e4955559 AW |
314 | macro expansion. |
315 | ||
316 | Consider the definition of @code{my-or} from the previous section: | |
317 | ||
318 | @example | |
319 | (define-syntax my-or | |
320 | (syntax-rules () | |
321 | ((my-or) | |
322 | #t) | |
323 | ((my-or exp) | |
324 | exp) | |
325 | ((my-or exp rest ...) | |
326 | (let ((t exp)) | |
e006d87b MW |
327 | (if t |
328 | t | |
e4955559 AW |
329 | (my-or rest ...)))))) |
330 | @end example | |
331 | ||
332 | A naive expansion of @code{(let ((t #t)) (my-or #f t))} would yield: | |
333 | ||
334 | @example | |
335 | (let ((t #t)) | |
336 | (let ((t #f)) | |
337 | (if t t t))) | |
338 | @result{} #f | |
339 | @end example | |
340 | ||
341 | @noindent | |
342 | Which clearly is not what we want. Somehow the @code{t} in the definition is | |
343 | distinct from the @code{t} at the site of use; and it is indeed this distinction | |
344 | that is maintained by the syntax expander, when expanding hygienic macros. | |
345 | ||
346 | This discussion is mostly relevant in the context of traditional Lisp macros | |
347 | (@pxref{Defmacros}), which do not preserve referential transparency. Hygiene | |
348 | adds to the expressive power of Scheme. | |
349 | ||
cd4171d0 AW |
350 | @subsubsection Shorthands |
351 | ||
352 | One often ends up writing simple one-clause @code{syntax-rules} macros. | |
353 | There is a convenient shorthand for this idiom, in the form of | |
354 | @code{define-syntax-rule}. | |
355 | ||
356 | @deffn {Syntax} define-syntax-rule (keyword . pattern) [docstring] template | |
357 | Define @var{keyword} as a new @code{syntax-rules} macro with one clause. | |
358 | @end deffn | |
359 | ||
360 | Cast into this form, our @code{when} example is significantly shorter: | |
361 | ||
362 | @example | |
363 | (define-syntax-rule (when c e ...) | |
364 | (if c (begin e ...))) | |
365 | @end example | |
366 | ||
0e181633 MW |
367 | @subsubsection Reporting Syntax Errors in Macros |
368 | ||
369 | @deffn {Syntax} syntax-error message [arg ...] | |
370 | Report an error at macro-expansion time. @var{message} must be a string | |
371 | literal, and the optional @var{arg} operands can be arbitrary expressions | |
372 | providing additional information. | |
373 | @end deffn | |
374 | ||
375 | @code{syntax-error} is intended to be used within @code{syntax-rules} | |
376 | templates. For example: | |
377 | ||
378 | @example | |
379 | (define-syntax simple-let | |
380 | (syntax-rules () | |
381 | ((_ (head ... ((x . y) val) . tail) | |
382 | body1 body2 ...) | |
383 | (syntax-error | |
384 | "expected an identifier but got" | |
385 | (x . y))) | |
386 | ((_ ((name val) ...) body1 body2 ...) | |
387 | ((lambda (name ...) body1 body2 ...) | |
388 | val ...)))) | |
389 | @end example | |
390 | ||
1624e149 MW |
391 | @subsubsection Specifying a Custom Ellipsis Identifier |
392 | ||
393 | When writing macros that generate macro definitions, it is convenient to | |
394 | use a different ellipsis identifier at each level. Guile allows the | |
395 | desired ellipsis identifier to be specified as the first operand to | |
2d6a3144 | 396 | @code{syntax-rules}, as specified by SRFI-46 and R7RS. For example: |
1624e149 MW |
397 | |
398 | @example | |
399 | (define-syntax define-quotation-macros | |
400 | (syntax-rules () | |
401 | ((_ (macro-name head-symbol) ...) | |
402 | (begin (define-syntax macro-name | |
403 | (syntax-rules ::: () | |
404 | ((_ x :::) | |
405 | (quote (head-symbol x :::))))) | |
406 | ...)))) | |
407 | (define-quotation-macros (quote-a a) (quote-b b) (quote-c c)) | |
408 | (quote-a 1 2 3) @result{} (a 1 2 3) | |
409 | @end example | |
410 | ||
e4955559 AW |
411 | @subsubsection Further Information |
412 | ||
413 | For a formal definition of @code{syntax-rules} and its pattern language, see | |
414 | @xref{Macros, , Macros, r5rs, Revised(5) Report on the Algorithmic Language | |
415 | Scheme}. | |
416 | ||
417 | @code{syntax-rules} macros are simple and clean, but do they have limitations. | |
418 | They do not lend themselves to expressive error messages: patterns either match | |
419 | or they don't. Their ability to generate code is limited to template-driven | |
420 | expansion; often one needs to define a number of helper macros to get real work | |
421 | done. Sometimes one wants to introduce a binding into the lexical context of the | |
422 | generated code; this is impossible with @code{syntax-rules}. Relatedly, they | |
423 | cannot programmatically generate identifiers. | |
424 | ||
425 | The solution to all of these problems is to use @code{syntax-case} if you need | |
426 | its features. But if for some reason you're stuck with @code{syntax-rules}, you | |
427 | might enjoy Joe Marshall's | |
428 | @uref{http://sites.google.com/site/evalapply/eccentric.txt,@code{syntax-rules} | |
429 | Primer for the Merely Eccentric}. | |
430 | ||
431 | @node Syntax Case | |
432 | @subsection Support for the @code{syntax-case} System | |
433 | ||
1fc8dcc7 AW |
434 | @code{syntax-case} macros are procedural syntax transformers, with a power |
435 | worthy of Scheme. | |
436 | ||
1624e149 | 437 | @deffn {Syntax} syntax-case syntax literals (pattern [guard] exp) @dots{} |
1fc8dcc7 AW |
438 | Match the syntax object @var{syntax} against the given patterns, in order. If a |
439 | @var{pattern} matches, return the result of evaluating the associated @var{exp}. | |
440 | @end deffn | |
441 | ||
442 | Compare the following definitions of @code{when}: | |
443 | ||
444 | @example | |
445 | (define-syntax when | |
446 | (syntax-rules () | |
447 | ((_ test e e* ...) | |
448 | (if test (begin e e* ...))))) | |
449 | ||
450 | (define-syntax when | |
451 | (lambda (x) | |
452 | (syntax-case x () | |
453 | ((_ test e e* ...) | |
454 | #'(if test (begin e e* ...)))))) | |
455 | @end example | |
456 | ||
457 | Clearly, the @code{syntax-case} definition is similar to its @code{syntax-rules} | |
458 | counterpart, and equally clearly there are some differences. The | |
459 | @code{syntax-case} definition is wrapped in a @code{lambda}, a function of one | |
460 | argument; that argument is passed to the @code{syntax-case} invocation; and the | |
461 | ``return value'' of the macro has a @code{#'} prefix. | |
462 | ||
463 | All of these differences stem from the fact that @code{syntax-case} does not | |
464 | define a syntax transformer itself -- instead, @code{syntax-case} expressions | |
465 | provide a way to destructure a @dfn{syntax object}, and to rebuild syntax | |
466 | objects as output. | |
467 | ||
468 | So the @code{lambda} wrapper is simply a leaky implementation detail, that | |
469 | syntax transformers are just functions that transform syntax to syntax. This | |
470 | should not be surprising, given that we have already described macros as | |
471 | ``programs that write programs''. @code{syntax-case} is simply a way to take | |
472 | apart and put together program text, and to be a valid syntax transformer it | |
473 | needs to be wrapped in a procedure. | |
474 | ||
475 | Unlike traditional Lisp macros (@pxref{Defmacros}), @code{syntax-case} macros | |
476 | transform syntax objects, not raw Scheme forms. Recall the naive expansion of | |
477 | @code{my-or} given in the previous section: | |
478 | ||
479 | @example | |
480 | (let ((t #t)) | |
481 | (my-or #f t)) | |
482 | ;; naive expansion: | |
483 | (let ((t #t)) | |
484 | (let ((t #f)) | |
485 | (if t t t))) | |
486 | @end example | |
487 | ||
488 | Raw Scheme forms simply don't have enough information to distinguish the first | |
489 | two @code{t} instances in @code{(if t t t)} from the third @code{t}. So instead | |
490 | of representing identifiers as symbols, the syntax expander represents | |
491 | identifiers as annotated syntax objects, attaching such information to those | |
492 | syntax objects as is needed to maintain referential transparency. | |
493 | ||
494 | @deffn {Syntax} syntax form | |
495 | Create a syntax object wrapping @var{form} within the current lexical context. | |
496 | @end deffn | |
497 | ||
498 | Syntax objects are typically created internally to the process of expansion, but | |
499 | it is possible to create them outside of syntax expansion: | |
500 | ||
501 | @example | |
502 | (syntax (foo bar baz)) | |
503 | @result{} #<some representation of that syntax> | |
504 | @end example | |
505 | ||
506 | @noindent | |
507 | However it is more common, and useful, to create syntax objects when building | |
508 | output from a @code{syntax-case} expression. | |
509 | ||
510 | @example | |
511 | (define-syntax add1 | |
512 | (lambda (x) | |
513 | (syntax-case x () | |
514 | ((_ exp) | |
515 | (syntax (+ exp 1)))))) | |
516 | @end example | |
517 | ||
518 | It is not strictly necessary for a @code{syntax-case} expression to return a | |
519 | syntax object, because @code{syntax-case} expressions can be used in helper | |
520 | functions, or otherwise used outside of syntax expansion itself. However a | |
7545ddd4 | 521 | syntax transformer procedure must return a syntax object, so most uses of |
1fc8dcc7 AW |
522 | @code{syntax-case} do end up returning syntax objects. |
523 | ||
524 | Here in this case, the form that built the return value was @code{(syntax (+ exp | |
525 | 1))}. The interesting thing about this is that within a @code{syntax} | |
7545ddd4 | 526 | expression, any appearance of a pattern variable is substituted into the |
1fc8dcc7 AW |
527 | resulting syntax object, carrying with it all relevant metadata from the source |
528 | expression, such as lexical identity and source location. | |
529 | ||
530 | Indeed, a pattern variable may only be referenced from inside a @code{syntax} | |
531 | form. The syntax expander would raise an error when defining @code{add1} if it | |
532 | found @var{exp} referenced outside a @code{syntax} form. | |
533 | ||
534 | Since @code{syntax} appears frequently in macro-heavy code, it has a special | |
535 | reader macro: @code{#'}. @code{#'foo} is transformed by the reader into | |
ecb87335 | 536 | @code{(syntax foo)}, just as @code{'foo} is transformed into @code{(quote foo)}. |
1fc8dcc7 AW |
537 | |
538 | The pattern language used by @code{syntax-case} is conveniently the same | |
539 | language used by @code{syntax-rules}. Given this, Guile actually defines | |
540 | @code{syntax-rules} in terms of @code{syntax-case}: | |
541 | ||
542 | @example | |
543 | (define-syntax syntax-rules | |
544 | (lambda (x) | |
545 | (syntax-case x () | |
546 | ((_ (k ...) ((keyword . pattern) template) ...) | |
547 | #'(lambda (x) | |
548 | (syntax-case x (k ...) | |
549 | ((dummy . pattern) #'template) | |
550 | ...)))))) | |
551 | @end example | |
552 | ||
553 | And that's that. | |
554 | ||
555 | @subsubsection Why @code{syntax-case}? | |
556 | ||
557 | The examples we have shown thus far could just as well have been expressed with | |
558 | @code{syntax-rules}, and have just shown that @code{syntax-case} is more | |
559 | verbose, which is true. But there is a difference: @code{syntax-case} creates | |
560 | @emph{procedural} macros, giving the full power of Scheme to the macro expander. | |
561 | This has many practical applications. | |
562 | ||
563 | A common desire is to be able to match a form only if it is an identifier. This | |
564 | is impossible with @code{syntax-rules}, given the datum matching forms. But with | |
565 | @code{syntax-case} it is easy: | |
566 | ||
567 | @deffn {Scheme Procedure} identifier? syntax-object | |
a4b4fbbd JE |
568 | Returns @code{#t} if @var{syntax-object} is an identifier, or @code{#f} |
569 | otherwise. | |
1fc8dcc7 AW |
570 | @end deffn |
571 | ||
572 | @example | |
7545ddd4 | 573 | ;; relying on previous add1 definition |
1fc8dcc7 AW |
574 | (define-syntax add1! |
575 | (lambda (x) | |
576 | (syntax-case x () | |
577 | ((_ var) (identifier? #'var) | |
578 | #'(set! var (add1 var)))))) | |
579 | ||
580 | (define foo 0) | |
581 | (add1! foo) | |
582 | foo @result{} 1 | |
583 | (add1! "not-an-identifier") @result{} error | |
584 | @end example | |
585 | ||
586 | With @code{syntax-rules}, the error for @code{(add1! "not-an-identifier")} would | |
587 | be something like ``invalid @code{set!}''. With @code{syntax-case}, it will say | |
588 | something like ``invalid @code{add1!}'', because we attach the @dfn{guard | |
589 | clause} to the pattern: @code{(identifier? #'var)}. This becomes more important | |
590 | with more complicated macros. It is necessary to use @code{identifier?}, because | |
591 | to the expander, an identifier is more than a bare symbol. | |
592 | ||
593 | Note that even in the guard clause, we reference the @var{var} pattern variable | |
594 | within a @code{syntax} form, via @code{#'var}. | |
595 | ||
596 | Another common desire is to introduce bindings into the lexical context of the | |
597 | output expression. One example would be in the so-called ``anaphoric macros'', | |
598 | like @code{aif}. Anaphoric macros bind some expression to a well-known | |
599 | identifier, often @code{it}, within their bodies. For example, in @code{(aif | |
600 | (foo) (bar it))}, @code{it} would be bound to the result of @code{(foo)}. | |
601 | ||
602 | To begin with, we should mention a solution that doesn't work: | |
603 | ||
604 | @example | |
605 | ;; doesn't work | |
606 | (define-syntax aif | |
607 | (lambda (x) | |
608 | (syntax-case x () | |
609 | ((_ test then else) | |
610 | #'(let ((it test)) | |
611 | (if it then else)))))) | |
612 | @end example | |
613 | ||
614 | The reason that this doesn't work is that, by default, the expander will | |
615 | preserve referential transparency; the @var{then} and @var{else} expressions | |
616 | won't have access to the binding of @code{it}. | |
617 | ||
618 | But they can, if we explicitly introduce a binding via @code{datum->syntax}. | |
619 | ||
620 | @deffn {Scheme Procedure} datum->syntax for-syntax datum | |
621 | Create a syntax object that wraps @var{datum}, within the lexical context | |
622 | corresponding to the syntax object @var{for-syntax}. | |
623 | @end deffn | |
624 | ||
625 | For completeness, we should mention that it is possible to strip the metadata | |
626 | from a syntax object, returning a raw Scheme datum: | |
627 | ||
628 | @deffn {Scheme Procedure} syntax->datum syntax-object | |
629 | Strip the metadata from @var{syntax-object}, returning its contents as a raw | |
630 | Scheme datum. | |
631 | @end deffn | |
632 | ||
633 | In this case we want to introduce @code{it} in the context of the whole | |
634 | expression, so we can create a syntax object as @code{(datum->syntax x 'it)}, | |
635 | where @code{x} is the whole expression, as passed to the transformer procedure. | |
636 | ||
637 | Here's another solution that doesn't work: | |
638 | ||
639 | @example | |
640 | ;; doesn't work either | |
641 | (define-syntax aif | |
642 | (lambda (x) | |
643 | (syntax-case x () | |
644 | ((_ test then else) | |
645 | (let ((it (datum->syntax x 'it))) | |
646 | #'(let ((it test)) | |
647 | (if it then else))))))) | |
648 | @end example | |
649 | ||
09cb3ae2 NL |
650 | The reason that this one doesn't work is that there are really two |
651 | environments at work here -- the environment of pattern variables, as | |
652 | bound by @code{syntax-case}, and the environment of lexical variables, | |
653 | as bound by normal Scheme. The outer let form establishes a binding in | |
654 | the environment of lexical variables, but the inner let form is inside a | |
655 | syntax form, where only pattern variables will be substituted. Here we | |
656 | need to introduce a piece of the lexical environment into the pattern | |
657 | variable environment, and we can do so using @code{syntax-case} itself: | |
1fc8dcc7 AW |
658 | |
659 | @example | |
660 | ;; works, but is obtuse | |
661 | (define-syntax aif | |
662 | (lambda (x) | |
663 | (syntax-case x () | |
664 | ((_ test then else) | |
665 | ;; invoking syntax-case on the generated | |
666 | ;; syntax object to expose it to `syntax' | |
667 | (syntax-case (datum->syntax x 'it) () | |
668 | (it | |
669 | #'(let ((it test)) | |
670 | (if it then else)))))))) | |
671 | ||
672 | (aif (getuid) (display it) (display "none")) (newline) | |
673 | @print{} 500 | |
674 | @end example | |
675 | ||
676 | However there are easier ways to write this. @code{with-syntax} is often | |
677 | convenient: | |
678 | ||
1624e149 | 679 | @deffn {Syntax} with-syntax ((pat val) @dots{}) exp @dots{} |
1fc8dcc7 | 680 | Bind patterns @var{pat} from their corresponding values @var{val}, within the |
1624e149 | 681 | lexical context of @var{exp} @enddots{}. |
1fc8dcc7 AW |
682 | |
683 | @example | |
684 | ;; better | |
685 | (define-syntax aif | |
686 | (lambda (x) | |
687 | (syntax-case x () | |
688 | ((_ test then else) | |
689 | (with-syntax ((it (datum->syntax x 'it))) | |
690 | #'(let ((it test)) | |
691 | (if it then else))))))) | |
692 | @end example | |
693 | @end deffn | |
694 | ||
695 | As you might imagine, @code{with-syntax} is defined in terms of | |
696 | @code{syntax-case}. But even that might be off-putting to you if you are an old | |
697 | Lisp macro hacker, used to building macro output with @code{quasiquote}. The | |
698 | issue is that @code{with-syntax} creates a separation between the point of | |
699 | definition of a value and its point of substitution. | |
700 | ||
701 | @pindex quasisyntax | |
702 | @pindex unsyntax | |
703 | @pindex unsyntax-splicing | |
704 | So for cases in which a @code{quasiquote} style makes more sense, | |
705 | @code{syntax-case} also defines @code{quasisyntax}, and the related | |
706 | @code{unsyntax} and @code{unsyntax-splicing}, abbreviated by the reader as | |
707 | @code{#`}, @code{#,}, and @code{#,@@}, respectively. | |
708 | ||
709 | For example, to define a macro that inserts a compile-time timestamp into a | |
710 | source file, one may write: | |
711 | ||
712 | @example | |
713 | (define-syntax display-compile-timestamp | |
714 | (lambda (x) | |
715 | (syntax-case x () | |
716 | ((_) | |
717 | #`(begin | |
718 | (display "The compile timestamp was: ") | |
719 | (display #,(current-time)) | |
720 | (newline)))))) | |
721 | @end example | |
722 | ||
9b0975f1 AW |
723 | Readers interested in further information on @code{syntax-case} macros should |
724 | see R. Kent Dybvig's excellent @cite{The Scheme Programming Language}, either | |
725 | edition 3 or 4, in the chapter on syntax. Dybvig was the primary author of the | |
726 | @code{syntax-case} system. The book itself is available online at | |
727 | @uref{http://scheme.com/tspl4/}. | |
728 | ||
1624e149 MW |
729 | @subsubsection Custom Ellipsis Identifiers for syntax-case Macros |
730 | ||
731 | When writing procedural macros that generate macro definitions, it is | |
732 | convenient to use a different ellipsis identifier at each level. Guile | |
733 | supports this for procedural macros using the @code{with-ellipsis} | |
734 | special form: | |
735 | ||
736 | @deffn {Syntax} with-ellipsis ellipsis body @dots{} | |
737 | @var{ellipsis} must be an identifier. Evaluate @var{body} in a special | |
738 | lexical environment such that all macro patterns and templates within | |
739 | @var{body} will use @var{ellipsis} as the ellipsis identifier instead of | |
740 | the usual three dots (@code{...}). | |
741 | @end deffn | |
742 | ||
743 | For example: | |
744 | ||
745 | @example | |
746 | (define-syntax define-quotation-macros | |
747 | (lambda (x) | |
748 | (syntax-case x () | |
749 | ((_ (macro-name head-symbol) ...) | |
750 | #'(begin (define-syntax macro-name | |
751 | (lambda (x) | |
752 | (with-ellipsis ::: | |
753 | (syntax-case x () | |
754 | ((_ x :::) | |
755 | #'(quote (head-symbol x :::))))))) | |
756 | ...))))) | |
757 | (define-quotation-macros (quote-a a) (quote-b b) (quote-c c)) | |
758 | (quote-a 1 2 3) @result{} (a 1 2 3) | |
759 | @end example | |
760 | ||
761 | Note that @code{with-ellipsis} does not affect the ellipsis identifier | |
762 | of the generated code, unless @code{with-ellipsis} is included around | |
763 | the generated code. | |
764 | ||
9b0975f1 AW |
765 | @node Syntax Transformer Helpers |
766 | @subsection Syntax Transformer Helpers | |
767 | ||
768 | As noted in the previous section, Guile's syntax expander operates on | |
769 | syntax objects. Procedural macros consume and produce syntax objects. | |
770 | This section describes some of the auxiliary helpers that procedural | |
771 | macros can use to compare, generate, and query objects of this data | |
772 | type. | |
1fc8dcc7 AW |
773 | |
774 | @deffn {Scheme Procedure} bound-identifier=? a b | |
a4b4fbbd JE |
775 | Return @code{#t} if the syntax objects @var{a} and @var{b} refer to the |
776 | same lexically-bound identifier, or @code{#f} otherwise. | |
1fc8dcc7 AW |
777 | @end deffn |
778 | ||
779 | @deffn {Scheme Procedure} free-identifier=? a b | |
a4b4fbbd JE |
780 | Return @code{#t} if the syntax objects @var{a} and @var{b} refer to the |
781 | same free identifier, or @code{#f} otherwise. | |
1fc8dcc7 AW |
782 | @end deffn |
783 | ||
784 | @deffn {Scheme Procedure} generate-temporaries ls | |
785 | Return a list of temporary identifiers as long as @var{ls} is long. | |
786 | @end deffn | |
787 | ||
9b0975f1 AW |
788 | @deffn {Scheme Procedure} syntax-source x |
789 | Return the source properties that correspond to the syntax object | |
790 | @var{x}. @xref{Source Properties}, for more information. | |
791 | @end deffn | |
792 | ||
68fcf711 AW |
793 | Guile also offers some more experimental interfaces in a separate |
794 | module. As was the case with the Large Hadron Collider, it is unclear | |
795 | to our senior macrologists whether adding these interfaces will result | |
796 | in awesomeness or in the destruction of Guile via the creation of a | |
797 | singularity. We will preserve their functionality through the 2.0 | |
798 | series, but we reserve the right to modify them in a future stable | |
799 | series, to a more than usual degree. | |
800 | ||
801 | @example | |
802 | (use-modules (system syntax)) | |
803 | @end example | |
804 | ||
1ace4fbf AW |
805 | @deffn {Scheme Procedure} syntax-module id |
806 | Return the name of the module whose source contains the identifier | |
807 | @var{id}. | |
808 | @end deffn | |
809 | ||
8ae26afe | 810 | @deffn {Scheme Procedure} syntax-local-binding id [#:resolve-syntax-parameters?=#t] |
9b0975f1 AW |
811 | Resolve the identifer @var{id}, a syntax object, within the current |
812 | lexical environment, and return two values, the binding type and a | |
813 | binding value. The binding type is a symbol, which may be one of the | |
814 | following: | |
815 | ||
816 | @table @code | |
817 | @item lexical | |
818 | A lexically-bound variable. The value is a unique token (in the sense | |
819 | of @code{eq?}) identifying this binding. | |
820 | @item macro | |
821 | A syntax transformer, either local or global. The value is the | |
822 | transformer procedure. | |
8ae26afe AW |
823 | @item syntax-parameter |
824 | A syntax parameter (@pxref{Syntax Parameters}). By default, | |
825 | @code{syntax-local-binding} will resolve syntax parameters, so that this | |
826 | value will not be returned. Pass @code{#:resolve-syntax-parameters? #f} | |
827 | to indicate that you are interested in syntax parameters. The value is | |
828 | the default transformer procedure, as in @code{macro}. | |
9b0975f1 | 829 | @item pattern-variable |
1624e149 MW |
830 | A pattern variable, bound via @code{syntax-case}. The value is an |
831 | opaque object, internal to the expander. | |
832 | @item ellipsis | |
833 | An internal binding, bound via @code{with-ellipsis}. The value is the | |
834 | (anti-marked) local ellipsis identifier. | |
9b0975f1 AW |
835 | @item displaced-lexical |
836 | A lexical variable that has gone out of scope. This can happen if a | |
837 | badly-written procedural macro saves a syntax object, then attempts to | |
838 | introduce it in a context in which it is unbound. The value is | |
839 | @code{#f}. | |
840 | @item global | |
841 | A global binding. The value is a pair, whose head is the symbol, and | |
842 | whose tail is the name of the module in which to resolve the symbol. | |
843 | @item other | |
844 | Some other binding, like @code{lambda} or other core bindings. The | |
845 | value is @code{#f}. | |
846 | @end table | |
847 | ||
848 | This is a very low-level procedure, with limited uses. One case in | |
849 | which it is useful is to build abstractions that associate auxiliary | |
850 | information with macros: | |
851 | ||
852 | @example | |
853 | (define aux-property (make-object-property)) | |
854 | (define-syntax-rule (with-aux aux value) | |
855 | (let ((trans value)) | |
856 | (set! (aux-property trans) aux) | |
3d51e57c | 857 | trans)) |
9b0975f1 AW |
858 | (define-syntax retrieve-aux |
859 | (lambda (x) | |
860 | (syntax-case x () | |
861 | ((x id) | |
862 | (call-with-values (lambda () (syntax-local-binding #'id)) | |
863 | (lambda (type val) | |
864 | (with-syntax ((aux (datum->syntax #'here | |
865 | (and (eq? type 'macro) | |
866 | (aux-property val))))) | |
867 | #''aux))))))) | |
868 | (define-syntax foo | |
869 | (with-aux 'bar | |
870 | (syntax-rules () ((_) 'foo)))) | |
871 | (foo) | |
872 | @result{} foo | |
873 | (retrieve-aux foo) | |
874 | @result{} bar | |
875 | @end example | |
876 | ||
877 | @code{syntax-local-binding} must be called within the dynamic extent of | |
878 | a syntax transformer; to call it otherwise will signal an error. | |
879 | @end deffn | |
1fc8dcc7 | 880 | |
3d51e57c AW |
881 | @deffn {Scheme Procedure} syntax-locally-bound-identifiers id |
882 | Return a list of identifiers that were visible lexically when the | |
883 | identifier @var{id} was created, in order from outermost to innermost. | |
884 | ||
885 | This procedure is intended to be used in specialized procedural macros, | |
886 | to provide a macro with the set of bound identifiers that the macro can | |
887 | reference. | |
888 | ||
889 | As a technical implementation detail, the identifiers returned by | |
890 | @code{syntax-locally-bound-identifiers} will be anti-marked, like the | |
891 | syntax object that is given as input to a macro. This is to signal to | |
892 | the macro expander that these bindings were present in the original | |
893 | source, and do not need to be hygienically renamed, as would be the case | |
894 | with other introduced identifiers. See the discussion of hygiene in | |
895 | section 12.1 of the R6RS, for more information on marks. | |
896 | ||
897 | @example | |
898 | (define (local-lexicals id) | |
899 | (filter (lambda (x) | |
900 | (eq? (syntax-local-binding x) 'lexical)) | |
901 | (syntax-locally-bound-identifiers id))) | |
902 | (define-syntax lexicals | |
903 | (lambda (x) | |
904 | (syntax-case x () | |
905 | ((lexicals) #'(lexicals lexicals)) | |
906 | ((lexicals scope) | |
907 | (with-syntax (((id ...) (local-lexicals #'scope))) | |
908 | #'(list (cons 'id id) ...)))))) | |
909 | ||
910 | (let* ((x 10) (x 20)) (lexicals)) | |
911 | @result{} ((x . 10) (x . 20)) | |
912 | @end example | |
913 | @end deffn | |
914 | ||
915 | ||
e4955559 AW |
916 | @node Defmacros |
917 | @subsection Lisp-style Macro Definitions | |
918 | ||
1fc8dcc7 AW |
919 | The traditional way to define macros in Lisp is very similar to procedure |
920 | definitions. The key differences are that the macro definition body should | |
921 | return a list that describes the transformed expression, and that the definition | |
922 | is marked as a macro definition (rather than a procedure definition) by the use | |
923 | of a different definition keyword: in Lisp, @code{defmacro} rather than | |
924 | @code{defun}, and in Scheme, @code{define-macro} rather than @code{define}. | |
e4955559 AW |
925 | |
926 | @fnindex defmacro | |
927 | @fnindex define-macro | |
928 | Guile supports this style of macro definition using both @code{defmacro} | |
929 | and @code{define-macro}. The only difference between them is how the | |
930 | macro name and arguments are grouped together in the definition: | |
931 | ||
932 | @lisp | |
933 | (defmacro @var{name} (@var{args} @dots{}) @var{body} @dots{}) | |
934 | @end lisp | |
935 | ||
936 | @noindent | |
937 | is the same as | |
938 | ||
939 | @lisp | |
940 | (define-macro (@var{name} @var{args} @dots{}) @var{body} @dots{}) | |
941 | @end lisp | |
942 | ||
943 | @noindent | |
944 | The difference is analogous to the corresponding difference between | |
945 | Lisp's @code{defun} and Scheme's @code{define}. | |
946 | ||
1fc8dcc7 AW |
947 | Having read the previous section on @code{syntax-case}, it's probably clear that |
948 | Guile actually implements defmacros in terms of @code{syntax-case}, applying the | |
949 | transformer on the expression between invocations of @code{syntax->datum} and | |
950 | @code{datum->syntax}. This realization leads us to the problem with defmacros, | |
951 | that they do not preserve referential transparency. One can be careful to not | |
952 | introduce bindings into expanded code, via liberal use of @code{gensym}, but | |
953 | there is no getting around the lack of referential transparency for free | |
954 | bindings in the macro itself. | |
e4955559 | 955 | |
1fc8dcc7 | 956 | Even a macro as simple as our @code{when} from before is difficult to get right: |
e4955559 | 957 | |
1fc8dcc7 AW |
958 | @example |
959 | (define-macro (when cond exp . rest) | |
960 | `(if ,cond | |
961 | (begin ,exp . ,rest))) | |
e4955559 | 962 | |
1fc8dcc7 AW |
963 | (when #f (display "Launching missiles!\n")) |
964 | @result{} #f | |
e4955559 | 965 | |
1fc8dcc7 AW |
966 | (let ((if list)) |
967 | (when #f (display "Launching missiles!\n"))) | |
968 | @print{} Launching missiles! | |
969 | @result{} (#f #<unspecified>) | |
970 | @end example | |
971 | ||
972 | Guile's perspective is that defmacros have had a good run, but that modern | |
973 | macros should be written with @code{syntax-rules} or @code{syntax-case}. There | |
974 | are still many uses of defmacros within Guile itself, but we will be phasing | |
975 | them out over time. Of course we won't take away @code{defmacro} or | |
976 | @code{define-macro} themselves, as there is lots of code out there that uses | |
977 | them. | |
e4955559 AW |
978 | |
979 | ||
980 | @node Identifier Macros | |
981 | @subsection Identifier Macros | |
982 | ||
6ffd4131 AW |
983 | When the syntax expander sees a form in which the first element is a macro, the |
984 | whole form gets passed to the macro's syntax transformer. One may visualize this | |
985 | as: | |
986 | ||
987 | @example | |
988 | (define-syntax foo foo-transformer) | |
989 | (foo @var{arg}...) | |
990 | ;; expands via | |
991 | (foo-transformer #'(foo @var{arg}...)) | |
992 | @end example | |
993 | ||
994 | If, on the other hand, a macro is referenced in some other part of a form, the | |
995 | syntax transformer is invoked with only the macro reference, not the whole form. | |
996 | ||
997 | @example | |
998 | (define-syntax foo foo-transformer) | |
999 | foo | |
1000 | ;; expands via | |
1001 | (foo-transformer #'foo) | |
1002 | @end example | |
1003 | ||
1004 | This allows bare identifier references to be replaced programmatically via a | |
1005 | macro. @code{syntax-rules} provides some syntax to effect this transformation | |
1006 | more easily. | |
1007 | ||
1008 | @deffn {Syntax} identifier-syntax exp | |
ecb87335 | 1009 | Returns a macro transformer that will replace occurrences of the macro with |
6ffd4131 AW |
1010 | @var{exp}. |
1011 | @end deffn | |
1012 | ||
1013 | For example, if you are importing external code written in terms of @code{fx+}, | |
1014 | the fixnum addition operator, but Guile doesn't have @code{fx+}, you may use the | |
1015 | following to replace @code{fx+} with @code{+}: | |
1016 | ||
1017 | @example | |
1018 | (define-syntax fx+ (identifier-syntax +)) | |
1019 | @end example | |
1020 | ||
69724dde AW |
1021 | There is also special support for recognizing identifiers on the |
1022 | left-hand side of a @code{set!} expression, as in the following: | |
1023 | ||
1024 | @example | |
1025 | (define-syntax foo foo-transformer) | |
1026 | (set! foo @var{val}) | |
1027 | ;; expands via | |
1028 | (foo-transformer #'(set! foo @var{val})) | |
a4b4fbbd | 1029 | ;; if foo-transformer is a "variable transformer" |
69724dde AW |
1030 | @end example |
1031 | ||
1032 | As the example notes, the transformer procedure must be explicitly | |
1033 | marked as being a ``variable transformer'', as most macros aren't | |
7545ddd4 | 1034 | written to discriminate on the form in the operator position. |
69724dde AW |
1035 | |
1036 | @deffn {Scheme Procedure} make-variable-transformer transformer | |
1037 | Mark the @var{transformer} procedure as being a ``variable | |
1038 | transformer''. In practice this means that, when bound to a syntactic | |
1039 | keyword, it may detect references to that keyword on the left-hand-side | |
1040 | of a @code{set!}. | |
1041 | ||
1042 | @example | |
1043 | (define bar 10) | |
1044 | (define-syntax bar-alias | |
1045 | (make-variable-transformer | |
1046 | (lambda (x) | |
1047 | (syntax-case x (set!) | |
1048 | ((set! var val) #'(set! bar val)) | |
1049 | ((var arg ...) #'(bar arg ...)) | |
1050 | (var (identifier? #'var) #'bar))))) | |
1051 | ||
1052 | bar-alias @result{} 10 | |
1053 | (set! bar-alias 20) | |
1054 | bar @result{} 20 | |
1055 | (set! bar 30) | |
1056 | bar-alias @result{} 30 | |
1057 | @end example | |
1058 | @end deffn | |
1059 | ||
ecb87335 | 1060 | There is an extension to identifier-syntax which allows it to handle the |
69724dde AW |
1061 | @code{set!} case as well: |
1062 | ||
1063 | @deffn {Syntax} identifier-syntax (var exp1) ((set! var val) exp2) | |
1064 | Create a variable transformer. The first clause is used for references | |
1065 | to the variable in operator or operand position, and the second for | |
1066 | appearances of the variable on the left-hand-side of an assignment. | |
1067 | ||
1068 | For example, the previous @code{bar-alias} example could be expressed | |
1069 | more succinctly like this: | |
1070 | ||
1071 | @example | |
1072 | (define-syntax bar-alias | |
1073 | (identifier-syntax | |
1074 | (var bar) | |
1075 | ((set! var val) (set! bar val)))) | |
1076 | @end example | |
1077 | ||
1078 | @noindent | |
1079 | As before, the templates in @code{identifier-syntax} forms do not need | |
1080 | wrapping in @code{#'} syntax forms. | |
1081 | @end deffn | |
1082 | ||
6ffd4131 | 1083 | |
729b62bd IP |
1084 | @node Syntax Parameters |
1085 | @subsection Syntax Parameters | |
1086 | ||
866ecf54 AW |
1087 | Syntax parameters@footnote{Described in the paper @cite{Keeping it Clean |
1088 | with Syntax Parameters} by Barzilay, Culpepper and Flatt.} are a | |
1089 | mechanism for rebinding a macro definition within the dynamic extent of | |
1090 | a macro expansion. This provides a convenient solution to one of the | |
1091 | most common types of unhygienic macro: those that introduce a unhygienic | |
1092 | binding each time the macro is used. Examples include a @code{lambda} | |
1093 | form with a @code{return} keyword, or class macros that introduce a | |
1094 | special @code{self} binding. | |
729b62bd IP |
1095 | |
1096 | With syntax parameters, instead of introducing the binding | |
866ecf54 AW |
1097 | unhygienically each time, we instead create one binding for the keyword, |
1098 | which we can then adjust later when we want the keyword to have a | |
1099 | different meaning. As no new bindings are introduced, hygiene is | |
1100 | preserved. This is similar to the dynamic binding mechanisms we have at | |
1101 | run-time (@pxref{SRFI-39, parameters}), except that the dynamic binding | |
1102 | only occurs during macro expansion. The code after macro expansion | |
1103 | remains lexically scoped. | |
729b62bd IP |
1104 | |
1105 | @deffn {Syntax} define-syntax-parameter keyword transformer | |
866ecf54 AW |
1106 | Binds @var{keyword} to the value obtained by evaluating |
1107 | @var{transformer}. The @var{transformer} provides the default expansion | |
1108 | for the syntax parameter, and in the absence of | |
1109 | @code{syntax-parameterize}, is functionally equivalent to | |
1110 | @code{define-syntax}. Usually, you will just want to have the | |
1111 | @var{transformer} throw a syntax error indicating that the @var{keyword} | |
1112 | is supposed to be used in conjunction with another macro, for example: | |
729b62bd IP |
1113 | @example |
1114 | (define-syntax-parameter return | |
1115 | (lambda (stx) | |
1116 | (syntax-violation 'return "return used outside of a lambda^" stx))) | |
1117 | @end example | |
1118 | @end deffn | |
1119 | ||
1120 | @deffn {Syntax} syntax-parameterize ((keyword transformer) @dots{}) exp @dots{} | |
1121 | Adjusts @var{keyword} @dots{} to use the values obtained by evaluating | |
866ecf54 AW |
1122 | their @var{transformer} @dots{}, in the expansion of the @var{exp} |
1123 | @dots{} forms. Each @var{keyword} must be bound to a syntax-parameter. | |
1124 | @code{syntax-parameterize} differs from @code{let-syntax}, in that the | |
1125 | binding is not shadowed, but adjusted, and so uses of the keyword in the | |
1126 | expansion of @var{exp} @dots{} use the new transformers. This is | |
1127 | somewhat similar to how @code{parameterize} adjusts the values of | |
1128 | regular parameters, rather than creating new bindings. | |
729b62bd IP |
1129 | |
1130 | @example | |
1131 | (define-syntax lambda^ | |
1132 | (syntax-rules () | |
866ecf54 | 1133 | [(lambda^ argument-list body body* ...) |
729b62bd IP |
1134 | (lambda argument-list |
1135 | (call-with-current-continuation | |
1136 | (lambda (escape) | |
866ecf54 AW |
1137 | ;; In the body we adjust the 'return' keyword so that calls |
1138 | ;; to 'return' are replaced with calls to the escape | |
1139 | ;; continuation. | |
729b62bd IP |
1140 | (syntax-parameterize ([return (syntax-rules () |
1141 | [(return vals (... ...)) | |
1142 | (escape vals (... ...))])]) | |
866ecf54 | 1143 | body body* ...))))])) |
729b62bd | 1144 | |
866ecf54 | 1145 | ;; Now we can write functions that return early. Here, 'product' will |
729b62bd IP |
1146 | ;; return immediately if it sees any 0 element. |
1147 | (define product | |
1148 | (lambda^ (list) | |
1149 | (fold (lambda (n o) | |
1150 | (if (zero? n) | |
1151 | (return 0) | |
1152 | (* n o))) | |
1153 | 1 | |
1154 | list))) | |
1155 | @end example | |
1156 | @end deffn | |
1157 | ||
1158 | ||
e4955559 AW |
1159 | @node Eval When |
1160 | @subsection Eval-when | |
1161 | ||
6ffd4131 AW |
1162 | As @code{syntax-case} macros have the whole power of Scheme available to them, |
1163 | they present a problem regarding time: when a macro runs, what parts of the | |
1164 | program are available for the macro to use? | |
e4955559 | 1165 | |
6ffd4131 AW |
1166 | The default answer to this question is that when you import a module (via |
1167 | @code{define-module} or @code{use-modules}), that module will be loaded up at | |
1168 | expansion-time, as well as at run-time. Additionally, top-level syntactic | |
1169 | definitions within one compilation unit made by @code{define-syntax} are also | |
1170 | evaluated at expansion time, in the order that they appear in the compilation | |
1171 | unit (file). | |
1172 | ||
1173 | But if a syntactic definition needs to call out to a normal procedure at | |
1174 | expansion-time, it might well need need special declarations to indicate that | |
1175 | the procedure should be made available at expansion-time. | |
1176 | ||
1177 | For example, the following code will work at a REPL, but not in a file: | |
1178 | ||
1179 | @example | |
1180 | ;; incorrect | |
1181 | (use-modules (srfi srfi-19)) | |
1182 | (define (date) (date->string (current-date))) | |
1183 | (define-syntax %date (identifier-syntax (date))) | |
1184 | (define *compilation-date* %date) | |
1185 | @end example | |
e4955559 | 1186 | |
6ffd4131 AW |
1187 | It works at a REPL because the expressions are evaluated one-by-one, in order, |
1188 | but if placed in a file, the expressions are expanded one-by-one, but not | |
1189 | evaluated until the compiled file is loaded. | |
1190 | ||
1191 | The fix is to use @code{eval-when}. | |
1192 | ||
1193 | @example | |
1194 | ;; correct: using eval-when | |
1195 | (use-modules (srfi srfi-19)) | |
1196 | (eval-when (compile load eval) | |
1197 | (define (date) (date->string (current-date)))) | |
1198 | (define-syntax %date (identifier-syntax (date))) | |
1199 | (define *compilation-date* %date) | |
1200 | @end example | |
1201 | ||
1202 | @deffn {Syntax} eval-when conditions exp... | |
1203 | Evaluate @var{exp...} under the given @var{conditions}. Valid conditions include | |
1204 | @code{eval}, @code{load}, and @code{compile}. If you need to use | |
1205 | @code{eval-when}, use it with all three conditions, as in the above example. | |
1206 | Other uses of @code{eval-when} may void your warranty or poison your cat. | |
1207 | @end deffn | |
1208 | ||
67915ab0 AW |
1209 | @node Macro Expansion |
1210 | @subsection Macro Expansion | |
1211 | ||
1212 | Usually, macros are expanded on behalf of the user as needed. Macro | |
1213 | expansion is an integral part of @code{eval} and @code{compile}. Users | |
1214 | can also expand macros at the REPL prompt via the @code{expand} REPL | |
1215 | command; @xref{Compile Commands}. | |
1216 | ||
1217 | Macros can also be expanded programmatically, via @code{macroexpand}, | |
1218 | but the details get a bit hairy for two reasons. | |
1219 | ||
1220 | The first complication is that the result of macro-expansion isn't | |
1221 | Scheme: it's Tree-IL, Guile's high-level intermediate language. | |
1222 | @xref{Tree-IL}. As ``hygienic macros'' can produce identifiers that are | |
1223 | distinct but have the same name, the output format needs to be able to | |
1224 | represent distinctions between variable identities and names. Again, | |
660f2775 AW |
1225 | @xref{Tree-IL}, for all the details. The easiest thing is to just run |
1226 | @code{tree-il->scheme} on the result of macro-expansion: | |
67915ab0 AW |
1227 | |
1228 | @lisp | |
1229 | (macroexpand '(+ 1 2)) | |
1230 | @result{} | |
1231 | #<tree-il (call (toplevel +) (const 1) (const 2))> | |
1232 | ||
1233 | (use-modules (language tree-il)) | |
1234 | (tree-il->scheme (macroexpand '(+ 1 2))) | |
1235 | @result{} | |
1236 | (+ 1 2) | |
1237 | @end lisp | |
1238 | ||
1239 | The second complication involves @code{eval-when}. As an example, what | |
1240 | would it mean to macro-expand the definition of a macro? | |
1241 | ||
1242 | @lisp | |
1243 | (macroexpand '(define-syntax qux (identifier-syntax 'bar))) | |
1244 | @result{} | |
1245 | ? | |
1246 | @end lisp | |
1247 | ||
1248 | The answer is that it depends who is macro-expanding, and why. Do you | |
1249 | define the macro in the current environment? Residualize a macro | |
1250 | definition? Both? Neither? The default is to expand in ``eval'' mode, | |
1251 | which means an @code{eval-when} clauses will only proceed when | |
1252 | @code{eval} (or @code{expand}) is in its condition set. Top-level | |
1253 | macros will be @code{eval}'d in the top-level environment. | |
1254 | ||
1255 | In this way @code{(macroexpand @var{foo})} is equivalent to | |
1256 | @code{(macroexpand @var{foo} 'e '(eval))}. The second argument is the | |
1257 | mode (@code{'e} for ``eval'') and the second is the | |
1258 | eval-syntax-expanders-when parameter (only @code{eval} in this default | |
1259 | setting). | |
1260 | ||
1261 | But if you are compiling the macro definition, probably you want to | |
1262 | reify the macro definition itself. In that case you pass @code{'c} as | |
1263 | the second argument to @code{macroexpand}. But probably you want the | |
1264 | macro definition to be present at compile time as well, so you pass | |
1265 | @code{'(compile load eval)} as the @var{esew} parameter. In fact | |
1266 | @code{(compile @var{foo} #:to 'tree-il)} is entirely equivalent to | |
1267 | @code{(macroexpand @var{foo} 'c '(compile load eval))}; @xref{The Scheme | |
1268 | Compiler}. | |
1269 | ||
1270 | It's a terrible interface; we know. The macroexpander is somewhat | |
1271 | tricksy regarding modes, so unless you are building a macro-expanding | |
1272 | tool, we suggest to avoid invoking it directly. | |
1273 | ||
1274 | ||
6ffd4131 AW |
1275 | @node Internal Macros |
1276 | @subsection Internal Macros | |
e4955559 AW |
1277 | |
1278 | @deffn {Scheme Procedure} make-syntax-transformer name type binding | |
6ffd4131 AW |
1279 | Construct a syntax transformer object. This is part of Guile's low-level support |
1280 | for syntax-case. | |
e4955559 AW |
1281 | @end deffn |
1282 | ||
1283 | @deffn {Scheme Procedure} macro? obj | |
1284 | @deffnx {C Function} scm_macro_p (obj) | |
a4b4fbbd JE |
1285 | Return @code{#t} if @var{obj} is a syntax transformer, or @code{#f} |
1286 | otherwise. | |
6ffd4131 AW |
1287 | |
1288 | Note that it's a bit difficult to actually get a macro as a first-class object; | |
1289 | simply naming it (like @code{case}) will produce a syntax error. But it is | |
1290 | possible to get these objects using @code{module-ref}: | |
1291 | ||
1292 | @example | |
1293 | (macro? (module-ref (current-module) 'case)) | |
1294 | @result{} #t | |
1295 | @end example | |
e4955559 AW |
1296 | @end deffn |
1297 | ||
1298 | @deffn {Scheme Procedure} macro-type m | |
1299 | @deffnx {C Function} scm_macro_type (m) | |
6ffd4131 AW |
1300 | Return the @var{type} that was given when @var{m} was constructed, via |
1301 | @code{make-syntax-transformer}. | |
e4955559 AW |
1302 | @end deffn |
1303 | ||
1304 | @deffn {Scheme Procedure} macro-name m | |
1305 | @deffnx {C Function} scm_macro_name (m) | |
1306 | Return the name of the macro @var{m}. | |
1307 | @end deffn | |
1308 | ||
e4955559 AW |
1309 | @deffn {Scheme Procedure} macro-binding m |
1310 | @deffnx {C Function} scm_macro_binding (m) | |
1311 | Return the binding of the macro @var{m}. | |
1312 | @end deffn | |
1313 | ||
6ffd4131 AW |
1314 | @deffn {Scheme Procedure} macro-transformer m |
1315 | @deffnx {C Function} scm_macro_transformer (m) | |
1316 | Return the transformer of the macro @var{m}. This will return a procedure, for | |
1317 | which one may ask the docstring. That's the whole reason this section is | |
1318 | documented. Actually a part of the result of @code{macro-binding}. | |
1319 | @end deffn | |
1320 | ||
e4955559 AW |
1321 | |
1322 | @c Local Variables: | |
1323 | @c TeX-master: "guile.texi" | |
1324 | @c End: |