api-macros.texi 41 KB

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