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