api-macros.texi 54 KB

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