bd49aa2a43cd933796c00a9bd31f3de8c6a9f089
[bpt/guile.git] / doc / ref / scheme-procedures.texi
1 @page
2 @node Procedures and Macros
3 @chapter Procedures and Macros
4
5 @menu
6 * Lambda:: Basic procedure creation using lambda.
7 * Primitive Procedures:: Procedures defined in C.
8 * Optional Arguments:: Handling keyword, optional and rest arguments.
9 * Procedure Properties:: Procedure properties and meta-information.
10 * Procedures with Setters:: Procedures with setters.
11 * Macros:: Lisp style macro definitions.
12 * Syntax Rules:: Support for R5RS @code{syntax-rules}.
13 * Syntax Case:: Support for the @code{syntax-case} system.
14 * Internal Macros:: Guile's internal representation.
15 @end menu
16
17
18 @node Lambda
19 @section Lambda: Basic Procedure Creation
20 @cindex lambda
21
22 @c FIXME::martin: Review me!
23
24 A @code{lambda} expression evaluates to a procedure. The environment
25 which is in effect when a @code{lambda} expression is evaluated is
26 enclosed in the newly created procedure, this is referred to as a
27 @dfn{closure} (@pxref{About Closure}).
28
29 When a procedure created by @code{lambda} is called with some actual
30 arguments, the environment enclosed in the procedure is extended by
31 binding the variables named in the formal argument list to new locations
32 and storing the actual arguments into these locations. Then the body of
33 the @code{lambda} expression is evaluation sequentially. The result of
34 the last expression in the procedure body is then the result of the
35 procedure invocation.
36
37 The following examples will show how procedures can be created using
38 @code{lambda}, and what you can do with these procedures.
39
40 @lisp
41 (lambda (x) (+ x x)) @result{} @r{a procedure}
42 ((lambda (x) (+ x x)) 4) @result{} 8
43 @end lisp
44
45 The fact that the environment in effect when creating a procedure is
46 enclosed in the procedure is shown with this example:
47
48 @lisp
49 (define add4
50 (let ((x 4))
51 (lambda (y) (+ x y))))
52 (add4 6) @result{} 10
53 @end lisp
54
55
56 @deffn syntax lambda formals body
57 @var{formals} should be a formal argument list as described in the
58 following table.
59
60 @table @code
61 @item (@var{variable1} @dots{})
62 The procedure takes a fixed number of arguments; when the procedure is
63 called, the arguments will be stored into the newly created location for
64 the formal variables.
65 @item @var{variable}
66 The procedure takes any number of arguments; when the procedure is
67 called, the sequence of actual arguments will converted into a list and
68 stored into the newly created location for the formal variable.
69 @item (@var{variable1} @dots{} @var{variablen} . @var{variablen+1})
70 If a space-delimited period precedes the last variable, then the
71 procedure takes @var{n} or more variables where @var{n} is the number
72 of formal arguments before the period. There must be at least one
73 argument before the period. The first @var{n} actual arguments will be
74 stored into the newly allocated locations for the first @var{n} formal
75 arguments and the sequence of the remaining actual arguments is
76 converted into a list and the stored into the location for the last
77 formal argument. If there are exactly @var{n} actual arguments, the
78 empty list is stored into the location of the last formal argument.
79 @end table
80
81 @var{body} is a sequence of Scheme expressions which are evaluated in
82 order when the procedure is invoked.
83 @end deffn
84
85 @node Primitive Procedures
86 @section Primitive Procedures
87 @cindex primitives
88 @cindex primitive procedures
89
90 Procedures written in C can be registered for use from Scheme,
91 provided they take only arguments of type @code{SCM} and return
92 @code{SCM} values. @code{scm_c_define_gsubr} is likely to be the most
93 useful mechanism, combining the process of registration
94 (@code{scm_c_make_gsubr}) and definition (@code{scm_define}).
95
96 @deftypefun SCM scm_c_make_gsubr (const char *name, int req, int opt, int rst, fcn)
97 Register a C procedure @var{FCN} as a ``subr'' --- a primitive
98 subroutine that can be called from Scheme. It will be associated with
99 the given @var{name} but no environment binding will be created. The
100 arguments @var{req}, @var{opt} and @var{rst} specify the number of
101 required, optional and ``rest'' arguments respectively. The total
102 number of these arguments should match the actual number of arguments
103 to @var{fcn}. The number of rest arguments should be 0 or 1.
104 @code{scm_c_make_gsubr} returns a value of type @code{SCM} which is a
105 ``handle'' for the procedure.
106 @end deftypefun
107
108 @deftypefun SCM scm_c_define_gsubr (const char *name, int req, int opt, int rst, fcn)
109 Register a C procedure @var{FCN}, as for @code{scm_c_make_gsubr}
110 above, and additionally create a top-level Scheme binding for the
111 procedure in the ``current environment'' using @code{scm_define}.
112 @code{scm_c_define_gsubr} returns a handle for the procedure in the
113 same way as @code{scm_c_make_gsubr}, which is usually not further
114 required.
115 @end deftypefun
116
117 @code{scm_c_make_gsubr} and @code{scm_c_define_gsubr} automatically
118 use @code{scm_c_make_subr} and also @code{scm_makcclo} if necessary.
119 It is advisable to use the gsubr variants since they provide a
120 slightly higher-level abstraction of the Guile implementation.
121
122 @node Optional Arguments
123 @section Optional Arguments
124
125 @c FIXME::martin: Review me!
126
127 Scheme procedures, as defined in R5RS, can either handle a fixed number
128 of actual arguments, or a fixed number of actual arguments followed by
129 arbitrarily many additional arguments. Writing procedures of variable
130 arity can be useful, but unfortunately, the syntactic means for handling
131 argument lists of varying length is a bit inconvenient. It is possible
132 to give names to the fixed number of argument, but the remaining
133 (optional) arguments can be only referenced as a list of values
134 (@pxref{Lambda}).
135
136 Guile comes with the module @code{(ice-9 optargs)}, which makes using
137 optional arguments much more convenient. In addition, this module
138 provides syntax for handling keywords in argument lists
139 (@pxref{Keywords}).
140
141 Before using any of the procedures or macros defined in this section,
142 you have to load the module @code{(ice-9 optargs)} with the statement:
143
144 @cindex @code{optargs}
145 @lisp
146 (use-modules (ice-9 optargs))
147 @end lisp
148
149 @menu
150 * let-optional Reference:: Locally binding optional arguments.
151 * let-keywords Reference:: Locally binding keywords arguments.
152 * lambda* Reference:: Creating advanced argument handling procedures.
153 * define* Reference:: Defining procedures and macros.
154 @end menu
155
156
157 @node let-optional Reference
158 @subsection let-optional Reference
159
160 @c FIXME::martin: Review me!
161
162 The syntax @code{let-optional} and @code{let-optional*} are for
163 destructuring rest argument lists and giving names to the various list
164 elements. @code{let-optional} binds all variables simultaneously, while
165 @code{let-optional*} binds them sequentially, consistent with @code{let}
166 and @code{let*} (@pxref{Local Bindings}).
167
168 @deffn {library syntax} let-optional rest-arg (binding @dots{}) expr @dots{}
169 @deffnx {library syntax} let-optional* rest-arg (binding @dots{}) expr @dots{}
170 These two macros give you an optional argument interface that is very
171 @dfn{Schemey} and introduces no fancy syntax. They are compatible with
172 the scsh macros of the same name, but are slightly extended. Each of
173 @var{binding} may be of one of the forms @var{var} or @code{(@var{var}
174 @var{default-value})}. @var{rest-arg} should be the rest-argument of the
175 procedures these are used from. The items in @var{rest-arg} are
176 sequentially bound to the variable names are given. When @var{rest-arg}
177 runs out, the remaining vars are bound either to the default values or
178 @code{#f} if no default value was specified. @var{rest-arg} remains
179 bound to whatever may have been left of @var{rest-arg}.
180
181 After binding the variables, the expressions @var{expr} @dots{} are
182 evaluated in order.
183 @end deffn
184
185
186 @node let-keywords Reference
187 @subsection let-keywords Reference
188
189 @c FIXME::martin: Review me!
190
191 @code{let-keywords} and @code{let-keywords*} are used for extracting
192 values from argument lists which use keywords instead of argument
193 position for binding local variables to argument values.
194
195 @code{let-keywords} binds all variables simultaneously, while
196 @code{let-keywords*} binds them sequentially, consistent with @code{let}
197 and @code{let*} (@pxref{Local Bindings}).
198
199 @deffn {library syntax} let-keywords rest-arg allow-other-keys? (binding @dots{}) expr @dots{}
200 @deffnx {library syntax} let-keywords rest-arg allow-other-keys? (binding @dots{}) expr @dots{}
201 These macros pick out keyword arguments from @var{rest-arg}, but do not
202 modify it. This is consistent at least with Common Lisp, which
203 duplicates keyword arguments in the rest argument. More explanation of what
204 keyword arguments in a lambda list look like can be found below in
205 the documentation for @code{lambda*}
206 (@pxref{lambda* Reference}). @var{binding}s can have the same form as
207 for @code{let-optional}. If @var{allow-other-keys?} is false, an error
208 will be thrown if anything that looks like a keyword argument but does
209 not match a known keyword parameter will result in an error.
210
211 After binding the variables, the expressions @var{expr} @dots{} are
212 evaluated in order.
213 @end deffn
214
215
216 @node lambda* Reference
217 @subsection lambda* Reference
218
219 @c FIXME::martin: Review me!
220
221 When using optional and keyword argument lists, using @code{lambda} for
222 creating procedures and using @code{let-optional} or @code{let-keywords}
223 is a bit lengthy. Therefore, @code{lambda*} is provided, which combines
224 the features of those macros into a single convenient syntax.
225
226 For quick reference, here is the syntax of the formal argument list for
227 @code{lambda*} (brackets are used to indicate grouping only):
228
229 @example
230 ext-param-list ::= [identifier]* [#:optional [ext-var-decl]+]?
231 [#:key [ext-var-decl]+ [#:allow-other-keys]?]?
232 [[#:rest identifier]|[. identifier]]?
233
234 ext-var-decl ::= identifier | ( identifier expression )
235 @end example
236
237 The characters `*', `+' and `?' are not to be taken literally; they mean
238 respectively, zero or more occurrences, one or more occurrences, and one
239 or zero occurrences.
240
241 @deffn {library syntax} lambda* formals body
242 @code{lambda*} creates a procedure that takes optional arguments. These
243 are specified by putting them inside brackets at the end of the
244 parameter list, but before any dotted rest argument. For example,
245
246 @lisp
247 (lambda* (a b #:optional c d . e) '())
248 @end lisp
249
250 creates a procedure with fixed arguments @var{a} and @var{b}, optional
251 arguments @var{c} and @var{d}, and rest argument @var{e}. If the
252 optional arguments are omitted in a call, the variables for them are
253 bound to @code{#f}.
254
255 @code{lambda*} can also take keyword arguments. For example, a procedure
256 defined like this:
257
258 @lisp
259 (lambda* (#:key xyzzy larch) '())
260 @end lisp
261
262 can be called with any of the argument lists @code{(#:xyzzy 11)}
263 @code{(#:larch 13)} @code{(#:larch 42 #:xyzzy 19)} @code{()}. Whichever
264 arguments are given as keywords are bound to values.
265
266 Optional and keyword arguments can also be given default values
267 which they take on when they are not present in a call, by giving a
268 two-item list in place of an optional argument, for example in:
269
270 @lisp
271 (lambda* (foo #:optional (bar 42) #:key (baz 73))
272 (list foo bar baz))
273 @end lisp
274
275 @var{foo} is a fixed argument, @var{bar} is an optional argument with
276 default value 42, and baz is a keyword argument with default value 73.
277 Default value expressions are not evaluated unless they are needed and
278 until the procedure is called.
279
280 @code{lambda*} also supports two more special parameter list keywords.
281
282 @code{lambda*}-defined procedures now throw an error by default if a
283 keyword other than one of those specified is found in the actual
284 passed arguments. However, specifying @code{#:allow-other-keys}
285 immediately after the keyword argument declarations restores the
286 previous behavior of ignoring unknown keywords. @code{lambda*} also now
287 guarantees that if the same keyword is passed more than once, the
288 last one passed is the one that takes effect. For example,
289
290 @lisp
291 ((lambda* (#:key (heads 0) (tails 0)) (display (list heads tails)))
292 #:heads 37 #:tails 42 #:heads 99)
293 @end lisp
294
295 would result in (99 47) being displayed.
296
297 @code{#:rest} is also now provided as a synonym for the dotted syntax
298 rest argument. The argument lists @code{(a . b)} and @code{(a #:rest b)}
299 are equivalent in all respects to @code{lambda*}. This is provided for
300 more similarity to DSSSL, MIT-Scheme and Kawa among others, as well as
301 for refugees from other Lisp dialects.
302 @end deffn
303
304
305 @node define* Reference
306 @subsection define* Reference
307
308 @c FIXME::martin: Review me!
309
310 Just like @code{define} has a shorthand notation for defining procedures
311 (@pxref{Lambda Alternatives}), @code{define*} is provided as an
312 abbreviation of the combination of @code{define} and @code{lambda*}.
313
314 @code{define*-public} is the @code{lambda*} version of
315 @code{define-public}; @code{defmacro*} and @code{defmacro*-public} exist
316 for defining macros with the improved argument list handling
317 possibilities. The @code{-public} versions not only define the
318 procedures/macros, but also export them from the current module.
319
320 @deffn {library syntax} define* formals body
321 @deffnx {library syntax} define*-public formals body
322 @code{define*} and @code{define*-public} support optional arguments with
323 a similar syntax to @code{lambda*}. They also support arbitrary-depth
324 currying, just like Guile's define. Some examples:
325
326 @lisp
327 (define* (x y #:optional a (z 3) #:key w . u)
328 (display (list y z u)))
329 @end lisp
330 defines a procedure @code{x} with a fixed argument @var{y}, an optional
331 argument @var{a}, another optional argument @var{z} with default value 3,
332 a keyword argument @var{w}, and a rest argument @var{u}.
333
334 @lisp
335 (define-public* ((foo #:optional bar) #:optional baz) '())
336 @end lisp
337
338 This illustrates currying. A procedure @code{foo} is defined, which,
339 when called with an optional argument @var{bar}, returns a procedure
340 that takes an optional argument @var{baz}.
341
342 Of course, @code{define*[-public]} also supports @code{#:rest} and
343 @code{#:allow-other-keys} in the same way as @code{lambda*}.
344 @end deffn
345
346 @deffn {library syntax} defmacro* name formals body
347 @deffnx {library syntax} defmacro*-public name formals body
348 These are just like @code{defmacro} and @code{defmacro-public} except that they
349 take @code{lambda*}-style extended parameter lists, where @code{#:optional},
350 @code{#:key}, @code{#:allow-other-keys} and @code{#:rest} are allowed with the usual
351 semantics. Here is an example of a macro with an optional argument:
352
353 @lisp
354 (defmacro* transmorgify (a #:optional b)
355 (a 1))
356 @end lisp
357 @end deffn
358
359
360 @node Procedure Properties
361 @section Procedure Properties and Meta-information
362
363 @c FIXME::martin: Review me!
364
365 Procedures always have attached the environment in which they were
366 created and information about how to apply them to actual arguments. In
367 addition to that, properties and meta-information can be stored with
368 procedures. The procedures in this section can be used to test whether
369 a given procedure satisfies a condition; and to access and set a
370 procedure's property.
371
372 The first group of procedures are predicates to test whether a Scheme
373 object is a procedure, or a special procedure, respectively.
374 @code{procedure?} is the most general predicates, it returns @code{#t}
375 for any kind of procedure. @code{closure?} does not return @code{#t}
376 for primitive procedures, and @code{thunk?} only returns @code{#t} for
377 procedures which do not accept any arguments.
378
379 @rnindex procedure?
380 @deffn {Scheme Procedure} procedure? obj
381 @deffnx {C Function} scm_procedure_p (obj)
382 Return @code{#t} if @var{obj} is a procedure.
383 @end deffn
384
385 @deffn {Scheme Procedure} closure? obj
386 @deffnx {C Function} scm_closure_p (obj)
387 Return @code{#t} if @var{obj} is a closure.
388 @end deffn
389
390 @deffn {Scheme Procedure} thunk? obj
391 @deffnx {C Function} scm_thunk_p (obj)
392 Return @code{#t} if @var{obj} is a thunk.
393 @end deffn
394
395 @c FIXME::martin: Is that true?
396 @cindex procedure properties
397 Procedure properties are general properties to be attached to
398 procedures. These can be the name of a procedure or other relevant
399 information, such as debug hints.
400
401 @deffn {Scheme Procedure} procedure-name proc
402 @deffnx {C Function} scm_procedure_name (proc)
403 Return the name of the procedure @var{proc}
404 @end deffn
405
406 @deffn {Scheme Procedure} procedure-source proc
407 @deffnx {C Function} scm_procedure_source (proc)
408 Return the source of the procedure @var{proc}.
409 @end deffn
410
411 @deffn {Scheme Procedure} procedure-environment proc
412 @deffnx {C Function} scm_procedure_environment (proc)
413 Return the environment of the procedure @var{proc}.
414 @end deffn
415
416 @deffn {Scheme Procedure} procedure-properties proc
417 @deffnx {C Function} scm_procedure_properties (proc)
418 Return @var{obj}'s property list.
419 @end deffn
420
421 @deffn {Scheme Procedure} procedure-property obj key
422 @deffnx {C Function} scm_procedure_property (obj, key)
423 Return the property of @var{obj} with name @var{key}.
424 @end deffn
425
426 @deffn {Scheme Procedure} set-procedure-properties! proc alist
427 @deffnx {C Function} scm_set_procedure_properties_x (proc, alist)
428 Set @var{obj}'s property list to @var{alist}.
429 @end deffn
430
431 @deffn {Scheme Procedure} set-procedure-property! obj key value
432 @deffnx {C Function} scm_set_procedure_property_x (obj, key, value)
433 In @var{obj}'s property list, set the property named @var{key} to
434 @var{value}.
435 @end deffn
436
437 @cindex procedure documentation
438 Documentation for a procedure can be accessed with the procedure
439 @code{procedure-documentation}.
440
441 @deffn {Scheme Procedure} procedure-documentation proc
442 @deffnx {C Function} scm_procedure_documentation (proc)
443 Return the documentation string associated with @code{proc}. By
444 convention, if a procedure contains more than one expression and the
445 first expression is a string constant, that string is assumed to contain
446 documentation for that procedure.
447 @end deffn
448
449 @cindex source properties
450 @c FIXME::martin: Is the following true?
451 Source properties are properties which are related to the source code of
452 a procedure, such as the line and column numbers, the file name etc.
453
454 @deffn {Scheme Procedure} set-source-properties! obj plist
455 @deffnx {C Function} scm_set_source_properties_x (obj, plist)
456 Install the association list @var{plist} as the source property
457 list for @var{obj}.
458 @end deffn
459
460 @deffn {Scheme Procedure} set-source-property! obj key datum
461 @deffnx {C Function} scm_set_source_property_x (obj, key, datum)
462 Set the source property of object @var{obj}, which is specified by
463 @var{key} to @var{datum}. Normally, the key will be a symbol.
464 @end deffn
465
466 @deffn {Scheme Procedure} source-properties obj
467 @deffnx {C Function} scm_source_properties (obj)
468 Return the source property association list of @var{obj}.
469 @end deffn
470
471
472 @deffn {Scheme Procedure} source-property obj key
473 @deffnx {C Function} scm_source_property (obj, key)
474 Return the source property specified by @var{key} from
475 @var{obj}'s source property list.
476 @end deffn
477
478
479 @node Procedures with Setters
480 @section Procedures with Setters
481
482 @c FIXME::martin: Review me!
483
484 @c FIXME::martin: Document `operator struct'.
485
486 @cindex procedure with setter
487 @cindex setter
488 A @dfn{procedure with setter} is a special kind of procedure which
489 normally behaves like any accessor procedure, that is a procedure which
490 accesses a data structure. The difference is that this kind of
491 procedure has a so-called @dfn{setter} attached, which is a procedure
492 for storing something into a data structure.
493
494 Procedures with setters are treated specially when the procedure appears
495 in the special form @code{set!} (REFFIXME). How it works is best shown
496 by example.
497
498 Suppose we have a procedure called @code{foo-ref}, which accepts two
499 arguments, a value of type @code{foo} and an integer. The procedure
500 returns the value stored at the given index in the @code{foo} object.
501 Let @code{f} be a variable containing such a @code{foo} data
502 structure.@footnote{Working definitions would be:
503 @lisp
504 (define foo-ref vector-ref)
505 (define foo-set! vector-set!)
506 (define f (make-vector 2 #f))
507 @end lisp
508 }
509
510 @lisp
511 (foo-ref f 0) @result{} bar
512 (foo-ref f 1) @result{} braz
513 @end lisp
514
515 Also suppose that a corresponding setter procedure called
516 @code{foo-set!} does exist.
517
518 @lisp
519 (foo-set! f 0 'bla)
520 (foo-ref f 0) @result{} bla
521 @end lisp
522
523 Now we could create a new procedure called @code{foo}, which is a
524 procedure with setter, by calling @code{make-procedure-with-setter} with
525 the accessor and setter procedures @code{foo-ref} and @code{foo-set!}.
526 Let us call this new procedure @code{foo}.
527
528 @lisp
529 (define foo (make-procedure-with-setter foo-ref foo-set!))
530 @end lisp
531
532 @code{foo} can from now an be used to either read from the data
533 structure stored in @code{f}, or to write into the structure.
534
535 @lisp
536 (set! (foo f 0) 'dum)
537 (foo f 0) @result{} dum
538 @end lisp
539
540 @deffn {Scheme Procedure} make-procedure-with-setter procedure setter
541 @deffnx {C Function} scm_make_procedure_with_setter (procedure, setter)
542 Create a new procedure which behaves like @var{procedure}, but
543 with the associated setter @var{setter}.
544 @end deffn
545
546 @deffn {Scheme Procedure} procedure-with-setter? obj
547 @deffnx {C Function} scm_procedure_with_setter_p (obj)
548 Return @code{#t} if @var{obj} is a procedure with an
549 associated setter procedure.
550 @end deffn
551
552 @deffn {Scheme Procedure} procedure proc
553 @deffnx {C Function} scm_procedure (proc)
554 Return the procedure of @var{proc}, which must be either a
555 procedure with setter, or an operator struct.
556 @end deffn
557
558 @deffn {Scheme Procedure} setter proc
559 Return the setter of @var{proc}, which must be either a procedure with
560 setter or an operator struct.
561 @end deffn
562
563
564 @node Macros
565 @section Lisp Style Macro Definitions
566
567 @cindex macros
568 @cindex transformation
569 Macros are objects which cause the expression that they appear in to be
570 transformed in some way @emph{before} being evaluated. In expressions
571 that are intended for macro transformation, the identifier that names
572 the relevant macro must appear as the first element, like this:
573
574 @lisp
575 (@var{macro-name} @var{macro-args} @dots{})
576 @end lisp
577
578 In Lisp-like languages, the traditional way to define macros is very
579 similar to procedure definitions. The key differences are that the
580 macro definition body should return a list that describes the
581 transformed expression, and that the definition is marked as a macro
582 definition (rather than a procedure definition) by the use of a
583 different definition keyword: in Lisp, @code{defmacro} rather than
584 @code{defun}, and in Scheme, @code{define-macro} rather than
585 @code{define}.
586
587 @fnindex defmacro
588 @fnindex define-macro
589 Guile supports this style of macro definition using both @code{defmacro}
590 and @code{define-macro}. The only difference between them is how the
591 macro name and arguments are grouped together in the definition:
592
593 @lisp
594 (defmacro @var{name} (@var{args} @dots{}) @var{body} @dots{})
595 @end lisp
596
597 @noindent
598 is the same as
599
600 @lisp
601 (define-macro (@var{name} @var{args} @dots{}) @var{body} @dots{})
602 @end lisp
603
604 @noindent
605 The difference is analogous to the corresponding difference between
606 Lisp's @code{defun} and Scheme's @code{define}.
607
608 @code{false-if-exception}, from the @file{boot-9.scm} file in the Guile
609 distribution, is a good example of macro definition using
610 @code{defmacro}:
611
612 @lisp
613 (defmacro false-if-exception (expr)
614 `(catch #t
615 (lambda () ,expr)
616 (lambda args #f)))
617 @end lisp
618
619 @noindent
620 The effect of this definition is that expressions beginning with the
621 identifier @code{false-if-exception} are automatically transformed into
622 a @code{catch} expression following the macro definition specification.
623 For example:
624
625 @lisp
626 (false-if-exception (open-input-file "may-not-exist"))
627 @equiv{}
628 (catch #t
629 (lambda () (open-input-file "may-not-exist"))
630 (lambda args #f))
631 @end lisp
632
633
634 @node Syntax Rules
635 @section The R5RS @code{syntax-rules} System
636 @cindex R5RS syntax-rules system
637
638 R5RS defines an alternative system for macro and syntax transformations
639 using the keywords @code{define-syntax}, @code{let-syntax},
640 @code{letrec-syntax} and @code{syntax-rules}.
641
642 The main difference between the R5RS system and the traditional macros
643 of the previous section is how the transformation is specified. In
644 R5RS, rather than permitting a macro definition to return an arbitrary
645 expression, the transformation is specified in a pattern language that
646
647 @itemize @bullet
648 @item
649 does not require complicated quoting and extraction of components of the
650 source expression using @code{caddr} etc.
651
652 @item
653 is designed such that the bindings associated with identifiers in the
654 transformed expression are well defined, and such that it is impossible
655 for the transformed expression to construct new identifiers.
656 @end itemize
657
658 @noindent
659 The last point is commonly referred to as being @dfn{hygienic}: the R5RS
660 @code{syntax-case} system provides @dfn{hygienic macros}.
661
662 For example, the R5RS pattern language for the @code{false-if-exception}
663 example of the previous section looks like this:
664
665 @lisp
666 (syntax-rules ()
667 ((_ expr)
668 (catch #t
669 (lambda () expr)
670 (lambda args #f))))
671 @end lisp
672
673 @cindex @code{syncase}
674 In Guile, the @code{syntax-rules} system is provided by the @code{(ice-9
675 syncase)} module. To make these facilities available in your code,
676 include the expression @code{(use-syntax (ice-9 syncase))} (@pxref{Using
677 Guile Modules}) before the first usage of @code{define-syntax} etc. If
678 you are writing a Scheme module, you can alternatively include the form
679 @code{#:use-syntax (ice-9 syncase)} in your @code{define-module}
680 declaration (@pxref{Creating Guile Modules}).
681
682 @menu
683 * Pattern Language:: The @code{syntax-rules} pattern language.
684 * Define-Syntax:: Top level syntax definitions.
685 * Let-Syntax:: Local syntax definitions.
686 @end menu
687
688
689 @node Pattern Language
690 @subsection The @code{syntax-rules} Pattern Language
691
692
693 @node Define-Syntax
694 @subsection Top Level Syntax Definitions
695
696 define-syntax: The gist is
697
698 (define-syntax <keyword> <transformer-spec>)
699
700 makes the <keyword> into a macro so that
701
702 (<keyword> ...)
703
704 expands at _compile_ or _read_ time (i.e. before any
705 evaluation begins) into some expression that is
706 given by the <transformer-spec>.
707
708
709 @node Let-Syntax
710 @subsection Local Syntax Definitions
711
712
713 @node Syntax Case
714 @section Support for the @code{syntax-case} System
715
716
717
718 @node Internal Macros
719 @section Internal Representation of Macros and Syntax
720
721 Internally, Guile uses three different flavors of macros. The three
722 flavors are called @dfn{acro} (or @dfn{syntax}), @dfn{macro} and
723 @dfn{mmacro}.
724
725 Given the expression
726
727 @lisp
728 (foo @dots{})
729 @end lisp
730
731 @noindent
732 with @code{foo} being some flavor of macro, one of the following things
733 will happen when the expression is evaluated.
734
735 @itemize @bullet
736 @item
737 When @code{foo} has been defined to be an @dfn{acro}, the procedure used
738 in the acro definition of @code{foo} is passed the whole expression and
739 the current lexical environment, and whatever that procedure returns is
740 the value of evaluating the expression. You can think of this a
741 procedure that receives its argument as an unevaluated expression.
742
743 @item
744 When @code{foo} has been defined to be a @dfn{macro}, the procedure used
745 in the macro definition of @code{foo} is passed the whole expression and
746 the current lexical environment, and whatever that procedure returns is
747 evaluated again. That is, the procedure should return a valid Scheme
748 expression.
749
750 @item
751 When @code{foo} has been defined to be a @dfn{mmacro}, the procedure
752 used in the mmacro definition of `foo' is passed the whole expression
753 and the current lexical environment, and whatever that procedure returns
754 replaces the original expression. Evaluation then starts over from the
755 new expression that has just been returned.
756 @end itemize
757
758 The key difference between a @dfn{macro} and a @dfn{mmacro} is that the
759 expression returned by a @dfn{mmacro} procedure is remembered (or
760 @dfn{memoized}) so that the expansion does not need to be done again
761 next time the containing code is evaluated.
762
763 The primitives @code{procedure->syntax}, @code{procedure->macro} and
764 @code{procedure->memoizing-macro} are used to construct acros, macros
765 and mmacros respectively. However, if you do not have a very special
766 reason to use one of these primitives, you should avoid them: they are
767 very specific to Guile's current implementation and therefore likely to
768 change. Use @code{defmacro}, @code{define-macro} (@pxref{Macros}) or
769 @code{define-syntax} (@pxref{Syntax Rules}) instead. (In low level
770 terms, @code{defmacro}, @code{define-macro} and @code{define-syntax} are
771 all implemented as mmacros.)
772
773 @deffn {Scheme Procedure} procedure->syntax code
774 @deffnx {C Function} scm_makacro (code)
775 Return a macro which, when a symbol defined to this value appears as the
776 first symbol in an expression, returns the result of applying @var{code}
777 to the expression and the environment.
778 @end deffn
779
780 @deffn {Scheme Procedure} procedure->macro code
781 @deffnx {C Function} scm_makmacro (code)
782 Return a macro which, when a symbol defined to this value appears as the
783 first symbol in an expression, evaluates the result of applying
784 @var{code} to the expression and the environment. For example:
785
786 @lisp
787 (define trace
788 (procedure->macro
789 (lambda (x env)
790 `(set! ,(cadr x) (tracef ,(cadr x) ',(cadr x))))))
791
792 (trace @i{foo})
793 @equiv{}
794 (set! @i{foo} (tracef @i{foo} '@i{foo})).
795 @end lisp
796 @end deffn
797
798 @deffn {Scheme Procedure} procedure->memoizing-macro code
799 @deffnx {C Function} scm_makmmacro (code)
800 Return a macro which, when a symbol defined to this value appears as the
801 first symbol in an expression, evaluates the result of applying
802 @var{code} to the expression and the environment.
803 @code{procedure->memoizing-macro} is the same as
804 @code{procedure->macro}, except that the expression returned by
805 @var{code} replaces the original macro expression in the memoized form
806 of the containing code.
807 @end deffn
808
809 In the following primitives, @dfn{acro} flavor macros are referred to
810 as @dfn{syntax transformers}.
811
812 @deffn {Scheme Procedure} macro? obj
813 @deffnx {C Function} scm_macro_p (obj)
814 Return @code{#t} if @var{obj} is a regular macro, a memoizing macro or a
815 syntax transformer.
816 @end deffn
817
818 @deffn {Scheme Procedure} macro-type m
819 @deffnx {C Function} scm_macro_type (m)
820 Return one of the symbols @code{syntax}, @code{macro} or
821 @code{macro!}, depending on whether @var{m} is a syntax
822 transformer, a regular macro, or a memoizing macro,
823 respectively. If @var{m} is not a macro, @code{#f} is
824 returned.
825 @end deffn
826
827 @deffn {Scheme Procedure} macro-name m
828 @deffnx {C Function} scm_macro_name (m)
829 Return the name of the macro @var{m}.
830 @end deffn
831
832 @deffn {Scheme Procedure} macro-transformer m
833 @deffnx {C Function} scm_macro_transformer (m)
834 Return the transformer of the macro @var{m}.
835 @end deffn
836
837 @deffn {Scheme Procedure} cons-source xorig x y
838 @deffnx {C Function} scm_cons_source (xorig, x, y)
839 Create and return a new pair whose car and cdr are @var{x} and @var{y}.
840 Any source properties associated with @var{xorig} are also associated
841 with the new pair.
842 @end deffn
843
844
845 @c Local Variables:
846 @c TeX-master: "guile.texi"
847 @c End: