api-macros.texi 32 KB

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