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