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