api-macros.texi 40 KB

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