* posix.texi (Pipes): Expand and clarify a bit. Describe port
[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
201@c FIXME::martin: Review me!
202
203@code{let-keywords} and @code{let-keywords*} are used for extracting
204values from argument lists which use keywords instead of argument
205position for binding local variables to argument values.
206
207@code{let-keywords} binds all variables simultaneously, while
208@code{let-keywords*} binds them sequentially, consistent with @code{let}
209and @code{let*} (@pxref{Local Bindings}).
210
211@deffn {library syntax} let-keywords rest-arg allow-other-keys? (binding @dots{}) expr @dots{}
0ef5ee46 212@deffnx {library syntax} let-keywords* rest-arg allow-other-keys? (binding @dots{}) expr @dots{}
07d83abe
MV
213These macros pick out keyword arguments from @var{rest-arg}, but do not
214modify it. This is consistent at least with Common Lisp, which
215duplicates keyword arguments in the rest argument. More explanation of what
216keyword arguments in a lambda list look like can be found below in
217the documentation for @code{lambda*}
218 (@pxref{lambda* Reference}). @var{binding}s can have the same form as
219for @code{let-optional}. If @var{allow-other-keys?} is false, an error
220will be thrown if anything that looks like a keyword argument but does
221not match a known keyword parameter will result in an error.
222
223After binding the variables, the expressions @var{expr} @dots{} are
224evaluated in order.
225@end deffn
226
227
228@node lambda* Reference
229@subsubsection lambda* Reference
230
edcd3e83
KR
231When using optional and keyword argument lists, @code{lambda} for
232creating a procedure then @code{let-optional} or @code{let-keywords}
233is a bit lengthy. @code{lambda*} combines the features of those
234macros into a single convenient syntax.
07d83abe 235
edcd3e83
KR
236@deffn {library syntax} lambda* ([var@dots{}] @* [#:optional vardef@dots{}] @* [#:key vardef@dots{} [#:allow-other-keys]] @* [#:rest var | . var]) @* body
237@sp 1
238Create a procedure which takes optional and/or keyword arguments
239specified with @code{#:optional} and @code{#:key}. For example,
07d83abe
MV
240
241@lisp
242(lambda* (a b #:optional c d . e) '())
243@end lisp
244
edcd3e83
KR
245is a procedure with fixed arguments @var{a} and @var{b}, optional
246arguments @var{c} and @var{d}, and rest argument @var{e}. If the
07d83abe
MV
247optional arguments are omitted in a call, the variables for them are
248bound to @code{#f}.
249
edcd3e83 250@code{lambda*} can also take keyword arguments. For example, a procedure
07d83abe
MV
251defined like this:
252
253@lisp
254(lambda* (#:key xyzzy larch) '())
255@end lisp
256
edcd3e83
KR
257can be called with any of the argument lists @code{(#:xyzzy 11)},
258@code{(#:larch 13)}, @code{(#:larch 42 #:xyzzy 19)}, @code{()}.
259Whichever arguments are given as keywords are bound to values (and
260those not given are @code{#f}).
07d83abe 261
edcd3e83
KR
262Optional and keyword arguments can also have default values to take
263when not present in a call, by giving a two-element list of variable
264name and expression. For example in
07d83abe
MV
265
266@lisp
267(lambda* (foo #:optional (bar 42) #:key (baz 73))
268 (list foo bar baz))
269@end lisp
270
271@var{foo} is a fixed argument, @var{bar} is an optional argument with
272default value 42, and baz is a keyword argument with default value 73.
edcd3e83
KR
273Default value expressions are not evaluated unless they are needed,
274and until the procedure is called.
07d83abe 275
edcd3e83
KR
276Normally it's an error if a call has keywords other than those
277specified by @code{#:key}, but adding @code{#:allow-other-keys} to the
278definition (after the keyword argument declarations) will ignore
279unknown keywords.
07d83abe 280
edcd3e83
KR
281If a call has a keyword given twice, the last value is used. For
282example,
07d83abe
MV
283
284@lisp
edcd3e83
KR
285((lambda* (#:key (heads 0) (tails 0))
286 (display (list heads tails)))
287 #:heads 37 #:tails 42 #:heads 99)
288@print{} (99 42)
07d83abe
MV
289@end lisp
290
edcd3e83
KR
291@code{#:rest} is a synonym for the dotted syntax rest argument. The
292argument lists @code{(a . b)} and @code{(a #:rest b)} are equivalent
293in all respects. This is provided for more similarity to DSSSL,
294MIT-Scheme and Kawa among others, as well as for refugees from other
295Lisp dialects.
296
297When @code{#:key} is used together with a rest argument, the keyword
298parameters in a call all remain in the rest list. This is the same as
299Common Lisp. For example,
07d83abe 300
edcd3e83
KR
301@lisp
302((lambda* (#:key (x 0) #:allow-other-keys #:rest r)
303 (display r))
304 #:x 123 #:y 456)
305@print{} (#:x 123 #:y 456)
306@end lisp
307
308@code{#:optional} and @code{#:key} establish their bindings
309successively, from left to right, as per @code{let-optional*} and
310@code{let-keywords*}. This means default expressions can refer back
311to prior parameters, for example
312
313@lisp
314(lambda* (start #:optional (end (+ 10 start)))
315 (do ((i start (1+ i)))
316 ((> i end))
317 (display i)))
318@end lisp
07d83abe
MV
319@end deffn
320
321
322@node define* Reference
323@subsubsection define* Reference
324
325@c FIXME::martin: Review me!
326
327Just like @code{define} has a shorthand notation for defining procedures
328(@pxref{Lambda Alternatives}), @code{define*} is provided as an
329abbreviation of the combination of @code{define} and @code{lambda*}.
330
331@code{define*-public} is the @code{lambda*} version of
332@code{define-public}; @code{defmacro*} and @code{defmacro*-public} exist
333for defining macros with the improved argument list handling
334possibilities. The @code{-public} versions not only define the
335procedures/macros, but also export them from the current module.
336
337@deffn {library syntax} define* formals body
338@deffnx {library syntax} define*-public formals body
339@code{define*} and @code{define*-public} support optional arguments with
340a similar syntax to @code{lambda*}. They also support arbitrary-depth
341currying, just like Guile's define. Some examples:
342
343@lisp
344(define* (x y #:optional a (z 3) #:key w . u)
345 (display (list y z u)))
346@end lisp
347defines a procedure @code{x} with a fixed argument @var{y}, an optional
348argument @var{a}, another optional argument @var{z} with default value 3,
349a keyword argument @var{w}, and a rest argument @var{u}.
350
351@lisp
352(define-public* ((foo #:optional bar) #:optional baz) '())
353@end lisp
354
355This illustrates currying. A procedure @code{foo} is defined, which,
356when called with an optional argument @var{bar}, returns a procedure
357that takes an optional argument @var{baz}.
358
359Of course, @code{define*[-public]} also supports @code{#:rest} and
360@code{#:allow-other-keys} in the same way as @code{lambda*}.
361@end deffn
362
363@deffn {library syntax} defmacro* name formals body
364@deffnx {library syntax} defmacro*-public name formals body
365These are just like @code{defmacro} and @code{defmacro-public} except that they
366take @code{lambda*}-style extended parameter lists, where @code{#:optional},
367@code{#:key}, @code{#:allow-other-keys} and @code{#:rest} are allowed with the usual
368semantics. Here is an example of a macro with an optional argument:
369
370@lisp
371(defmacro* transmorgify (a #:optional b)
372 (a 1))
373@end lisp
374@end deffn
375
376
377@node Procedure Properties
378@subsection Procedure Properties and Meta-information
379
380@c FIXME::martin: Review me!
381
382Procedures always have attached the environment in which they were
383created and information about how to apply them to actual arguments. In
384addition to that, properties and meta-information can be stored with
385procedures. The procedures in this section can be used to test whether
386a given procedure satisfies a condition; and to access and set a
387procedure's property.
388
389The first group of procedures are predicates to test whether a Scheme
390object is a procedure, or a special procedure, respectively.
391@code{procedure?} is the most general predicates, it returns @code{#t}
392for any kind of procedure. @code{closure?} does not return @code{#t}
393for primitive procedures, and @code{thunk?} only returns @code{#t} for
394procedures which do not accept any arguments.
395
396@rnindex procedure?
397@deffn {Scheme Procedure} procedure? obj
398@deffnx {C Function} scm_procedure_p (obj)
399Return @code{#t} if @var{obj} is a procedure.
400@end deffn
401
402@deffn {Scheme Procedure} closure? obj
403@deffnx {C Function} scm_closure_p (obj)
404Return @code{#t} if @var{obj} is a closure.
405@end deffn
406
407@deffn {Scheme Procedure} thunk? obj
408@deffnx {C Function} scm_thunk_p (obj)
409Return @code{#t} if @var{obj} is a thunk.
410@end deffn
411
412@c FIXME::martin: Is that true?
413@cindex procedure properties
414Procedure properties are general properties to be attached to
415procedures. These can be the name of a procedure or other relevant
416information, such as debug hints.
417
418@deffn {Scheme Procedure} procedure-name proc
419@deffnx {C Function} scm_procedure_name (proc)
420Return the name of the procedure @var{proc}
421@end deffn
422
423@deffn {Scheme Procedure} procedure-source proc
424@deffnx {C Function} scm_procedure_source (proc)
425Return the source of the procedure @var{proc}.
426@end deffn
427
428@deffn {Scheme Procedure} procedure-environment proc
429@deffnx {C Function} scm_procedure_environment (proc)
430Return the environment of the procedure @var{proc}.
431@end deffn
432
433@deffn {Scheme Procedure} procedure-properties proc
434@deffnx {C Function} scm_procedure_properties (proc)
435Return @var{obj}'s property list.
436@end deffn
437
438@deffn {Scheme Procedure} procedure-property obj key
439@deffnx {C Function} scm_procedure_property (obj, key)
440Return the property of @var{obj} with name @var{key}.
441@end deffn
442
443@deffn {Scheme Procedure} set-procedure-properties! proc alist
444@deffnx {C Function} scm_set_procedure_properties_x (proc, alist)
445Set @var{obj}'s property list to @var{alist}.
446@end deffn
447
448@deffn {Scheme Procedure} set-procedure-property! obj key value
449@deffnx {C Function} scm_set_procedure_property_x (obj, key, value)
450In @var{obj}'s property list, set the property named @var{key} to
451@var{value}.
452@end deffn
453
454@cindex procedure documentation
455Documentation for a procedure can be accessed with the procedure
456@code{procedure-documentation}.
457
458@deffn {Scheme Procedure} procedure-documentation proc
459@deffnx {C Function} scm_procedure_documentation (proc)
460Return the documentation string associated with @code{proc}. By
461convention, if a procedure contains more than one expression and the
462first expression is a string constant, that string is assumed to contain
463documentation for that procedure.
464@end deffn
465
466@cindex source properties
467@c FIXME::martin: Is the following true?
468Source properties are properties which are related to the source code of
469a procedure, such as the line and column numbers, the file name etc.
470
471@deffn {Scheme Procedure} set-source-properties! obj plist
472@deffnx {C Function} scm_set_source_properties_x (obj, plist)
473Install the association list @var{plist} as the source property
474list for @var{obj}.
475@end deffn
476
477@deffn {Scheme Procedure} set-source-property! obj key datum
478@deffnx {C Function} scm_set_source_property_x (obj, key, datum)
479Set the source property of object @var{obj}, which is specified by
480@var{key} to @var{datum}. Normally, the key will be a symbol.
481@end deffn
482
483@deffn {Scheme Procedure} source-properties obj
484@deffnx {C Function} scm_source_properties (obj)
485Return the source property association list of @var{obj}.
486@end deffn
487
488
489@deffn {Scheme Procedure} source-property obj key
490@deffnx {C Function} scm_source_property (obj, key)
491Return the source property specified by @var{key} from
492@var{obj}'s source property list.
493@end deffn
494
495
496@node Procedures with Setters
497@subsection Procedures with Setters
498
499@c FIXME::martin: Review me!
500
501@c FIXME::martin: Document `operator struct'.
502
503@cindex procedure with setter
504@cindex setter
505A @dfn{procedure with setter} is a special kind of procedure which
506normally behaves like any accessor procedure, that is a procedure which
507accesses a data structure. The difference is that this kind of
508procedure has a so-called @dfn{setter} attached, which is a procedure
509for storing something into a data structure.
510
511Procedures with setters are treated specially when the procedure appears
512in the special form @code{set!} (REFFIXME). How it works is best shown
513by example.
514
515Suppose we have a procedure called @code{foo-ref}, which accepts two
516arguments, a value of type @code{foo} and an integer. The procedure
517returns the value stored at the given index in the @code{foo} object.
518Let @code{f} be a variable containing such a @code{foo} data
519structure.@footnote{Working definitions would be:
520@lisp
521(define foo-ref vector-ref)
522(define foo-set! vector-set!)
523(define f (make-vector 2 #f))
524@end lisp
525}
526
527@lisp
528(foo-ref f 0) @result{} bar
529(foo-ref f 1) @result{} braz
530@end lisp
531
532Also suppose that a corresponding setter procedure called
533@code{foo-set!} does exist.
534
535@lisp
536(foo-set! f 0 'bla)
537(foo-ref f 0) @result{} bla
538@end lisp
539
540Now we could create a new procedure called @code{foo}, which is a
541procedure with setter, by calling @code{make-procedure-with-setter} with
542the accessor and setter procedures @code{foo-ref} and @code{foo-set!}.
543Let us call this new procedure @code{foo}.
544
545@lisp
546(define foo (make-procedure-with-setter foo-ref foo-set!))
547@end lisp
548
549@code{foo} can from now an be used to either read from the data
550structure stored in @code{f}, or to write into the structure.
551
552@lisp
553(set! (foo f 0) 'dum)
554(foo f 0) @result{} dum
555@end lisp
556
557@deffn {Scheme Procedure} make-procedure-with-setter procedure setter
558@deffnx {C Function} scm_make_procedure_with_setter (procedure, setter)
559Create a new procedure which behaves like @var{procedure}, but
560with the associated setter @var{setter}.
561@end deffn
562
563@deffn {Scheme Procedure} procedure-with-setter? obj
564@deffnx {C Function} scm_procedure_with_setter_p (obj)
565Return @code{#t} if @var{obj} is a procedure with an
566associated setter procedure.
567@end deffn
568
569@deffn {Scheme Procedure} procedure proc
570@deffnx {C Function} scm_procedure (proc)
571Return the procedure of @var{proc}, which must be either a
572procedure with setter, or an operator struct.
573@end deffn
574
575@deffn {Scheme Procedure} setter proc
576Return the setter of @var{proc}, which must be either a procedure with
577setter or an operator struct.
578@end deffn
579
580
581@node Macros
582@subsection Lisp Style Macro Definitions
583
584@cindex macros
585@cindex transformation
586Macros are objects which cause the expression that they appear in to be
587transformed in some way @emph{before} being evaluated. In expressions
588that are intended for macro transformation, the identifier that names
589the relevant macro must appear as the first element, like this:
590
591@lisp
592(@var{macro-name} @var{macro-args} @dots{})
593@end lisp
594
595In Lisp-like languages, the traditional way to define macros is very
596similar to procedure definitions. The key differences are that the
597macro definition body should return a list that describes the
598transformed expression, and that the definition is marked as a macro
599definition (rather than a procedure definition) by the use of a
600different definition keyword: in Lisp, @code{defmacro} rather than
601@code{defun}, and in Scheme, @code{define-macro} rather than
602@code{define}.
603
604@fnindex defmacro
605@fnindex define-macro
606Guile supports this style of macro definition using both @code{defmacro}
607and @code{define-macro}. The only difference between them is how the
608macro name and arguments are grouped together in the definition:
609
610@lisp
611(defmacro @var{name} (@var{args} @dots{}) @var{body} @dots{})
612@end lisp
613
614@noindent
615is the same as
616
617@lisp
618(define-macro (@var{name} @var{args} @dots{}) @var{body} @dots{})
619@end lisp
620
621@noindent
622The difference is analogous to the corresponding difference between
623Lisp's @code{defun} and Scheme's @code{define}.
624
625@code{false-if-exception}, from the @file{boot-9.scm} file in the Guile
626distribution, is a good example of macro definition using
627@code{defmacro}:
628
629@lisp
630(defmacro false-if-exception (expr)
631 `(catch #t
632 (lambda () ,expr)
633 (lambda args #f)))
634@end lisp
635
636@noindent
637The effect of this definition is that expressions beginning with the
638identifier @code{false-if-exception} are automatically transformed into
639a @code{catch} expression following the macro definition specification.
640For example:
641
642@lisp
643(false-if-exception (open-input-file "may-not-exist"))
644@equiv{}
645(catch #t
646 (lambda () (open-input-file "may-not-exist"))
647 (lambda args #f))
648@end lisp
649
650
651@node Syntax Rules
652@subsection The R5RS @code{syntax-rules} System
653@cindex R5RS syntax-rules system
654
655R5RS defines an alternative system for macro and syntax transformations
656using the keywords @code{define-syntax}, @code{let-syntax},
657@code{letrec-syntax} and @code{syntax-rules}.
658
659The main difference between the R5RS system and the traditional macros
660of the previous section is how the transformation is specified. In
661R5RS, rather than permitting a macro definition to return an arbitrary
662expression, the transformation is specified in a pattern language that
663
664@itemize @bullet
665@item
666does not require complicated quoting and extraction of components of the
667source expression using @code{caddr} etc.
668
669@item
670is designed such that the bindings associated with identifiers in the
671transformed expression are well defined, and such that it is impossible
672for the transformed expression to construct new identifiers.
673@end itemize
674
675@noindent
676The last point is commonly referred to as being @dfn{hygienic}: the R5RS
677@code{syntax-case} system provides @dfn{hygienic macros}.
678
679For example, the R5RS pattern language for the @code{false-if-exception}
680example of the previous section looks like this:
681
682@lisp
683(syntax-rules ()
684 ((_ expr)
685 (catch #t
686 (lambda () expr)
687 (lambda args #f))))
688@end lisp
689
690@cindex @code{syncase}
691In Guile, the @code{syntax-rules} system is provided by the @code{(ice-9
692syncase)} module. To make these facilities available in your code,
693include the expression @code{(use-syntax (ice-9 syncase))} (@pxref{Using
694Guile Modules}) before the first usage of @code{define-syntax} etc. If
695you are writing a Scheme module, you can alternatively include the form
696@code{#:use-syntax (ice-9 syncase)} in your @code{define-module}
697declaration (@pxref{Creating Guile Modules}).
698
699@menu
700* Pattern Language:: The @code{syntax-rules} pattern language.
701* Define-Syntax:: Top level syntax definitions.
702* Let-Syntax:: Local syntax definitions.
703@end menu
704
705
706@node Pattern Language
707@subsubsection The @code{syntax-rules} Pattern Language
708
709
710@node Define-Syntax
711@subsubsection Top Level Syntax Definitions
712
713define-syntax: The gist is
714
715 (define-syntax <keyword> <transformer-spec>)
716
717makes the <keyword> into a macro so that
718
719 (<keyword> ...)
720
721expands at _compile_ or _read_ time (i.e. before any
722evaluation begins) into some expression that is
723given by the <transformer-spec>.
724
725
726@node Let-Syntax
727@subsubsection Local Syntax Definitions
728
729
730@node Syntax Case
731@subsection Support for the @code{syntax-case} System
732
733
734
735@node Internal Macros
736@subsection Internal Representation of Macros and Syntax
737
738Internally, Guile uses three different flavors of macros. The three
739flavors are called @dfn{acro} (or @dfn{syntax}), @dfn{macro} and
740@dfn{mmacro}.
741
742Given the expression
743
744@lisp
745(foo @dots{})
746@end lisp
747
748@noindent
749with @code{foo} being some flavor of macro, one of the following things
750will happen when the expression is evaluated.
751
752@itemize @bullet
753@item
754When @code{foo} has been defined to be an @dfn{acro}, the procedure used
755in the acro definition of @code{foo} is passed the whole expression and
756the current lexical environment, and whatever that procedure returns is
757the value of evaluating the expression. You can think of this a
758procedure that receives its argument as an unevaluated expression.
759
760@item
761When @code{foo} has been defined to be a @dfn{macro}, the procedure used
762in the macro definition of @code{foo} is passed the whole expression and
763the current lexical environment, and whatever that procedure returns is
764evaluated again. That is, the procedure should return a valid Scheme
765expression.
766
767@item
768When @code{foo} has been defined to be a @dfn{mmacro}, the procedure
769used in the mmacro definition of `foo' is passed the whole expression
770and the current lexical environment, and whatever that procedure returns
771replaces the original expression. Evaluation then starts over from the
772new expression that has just been returned.
773@end itemize
774
775The key difference between a @dfn{macro} and a @dfn{mmacro} is that the
776expression returned by a @dfn{mmacro} procedure is remembered (or
777@dfn{memoized}) so that the expansion does not need to be done again
778next time the containing code is evaluated.
779
780The primitives @code{procedure->syntax}, @code{procedure->macro} and
781@code{procedure->memoizing-macro} are used to construct acros, macros
782and mmacros respectively. However, if you do not have a very special
783reason to use one of these primitives, you should avoid them: they are
784very specific to Guile's current implementation and therefore likely to
785change. Use @code{defmacro}, @code{define-macro} (@pxref{Macros}) or
786@code{define-syntax} (@pxref{Syntax Rules}) instead. (In low level
787terms, @code{defmacro}, @code{define-macro} and @code{define-syntax} are
788all implemented as mmacros.)
789
790@deffn {Scheme Procedure} procedure->syntax code
791@deffnx {C Function} scm_makacro (code)
792Return a macro which, when a symbol defined to this value appears as the
793first symbol in an expression, returns the result of applying @var{code}
794to the expression and the environment.
795@end deffn
796
797@deffn {Scheme Procedure} procedure->macro code
798@deffnx {C Function} scm_makmacro (code)
799Return a macro which, when a symbol defined to this value appears as the
800first symbol in an expression, evaluates the result of applying
801@var{code} to the expression and the environment. For example:
802
803@lisp
804(define trace
805 (procedure->macro
806 (lambda (x env)
807 `(set! ,(cadr x) (tracef ,(cadr x) ',(cadr x))))))
808
809(trace @i{foo})
810@equiv{}
811(set! @i{foo} (tracef @i{foo} '@i{foo})).
812@end lisp
813@end deffn
814
815@deffn {Scheme Procedure} procedure->memoizing-macro code
816@deffnx {C Function} scm_makmmacro (code)
817Return a macro which, when a symbol defined to this value appears as the
818first symbol in an expression, evaluates the result of applying
819@var{code} to the expression and the environment.
820@code{procedure->memoizing-macro} is the same as
821@code{procedure->macro}, except that the expression returned by
822@var{code} replaces the original macro expression in the memoized form
823of the containing code.
824@end deffn
825
826In the following primitives, @dfn{acro} flavor macros are referred to
827as @dfn{syntax transformers}.
828
829@deffn {Scheme Procedure} macro? obj
830@deffnx {C Function} scm_macro_p (obj)
831Return @code{#t} if @var{obj} is a regular macro, a memoizing macro or a
832syntax transformer.
833@end deffn
834
835@deffn {Scheme Procedure} macro-type m
836@deffnx {C Function} scm_macro_type (m)
837Return one of the symbols @code{syntax}, @code{macro} or
838@code{macro!}, depending on whether @var{m} is a syntax
839transformer, a regular macro, or a memoizing macro,
840respectively. If @var{m} is not a macro, @code{#f} is
841returned.
842@end deffn
843
844@deffn {Scheme Procedure} macro-name m
845@deffnx {C Function} scm_macro_name (m)
846Return the name of the macro @var{m}.
847@end deffn
848
849@deffn {Scheme Procedure} macro-transformer m
850@deffnx {C Function} scm_macro_transformer (m)
851Return the transformer of the macro @var{m}.
852@end deffn
853
854@deffn {Scheme Procedure} cons-source xorig x y
855@deffnx {C Function} scm_cons_source (xorig, x, y)
856Create and return a new pair whose car and cdr are @var{x} and @var{y}.
857Any source properties associated with @var{xorig} are also associated
858with the new pair.
859@end deffn
860
861
862@c Local Variables:
863@c TeX-master: "guile.texi"
864@c End: