api-macros.texi 53 KB

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