code:
@c -*-texinfo-*-
@c This is part of the GNU Guile Reference Manual.
@c Copyright (C)  1996, 1997, 2000, 2001, 2002, 2003, 2004
@c   Free Software Foundation, Inc.
@c See the file guile.texi for copying conditions.

@page
@node Procedures and Macros
@section Procedures and Macros

@menu
* Lambda::                      Basic procedure creation using lambda.
* Primitive Procedures::        Procedures defined in C.
* Optional Arguments::          Handling keyword, optional and rest arguments.
* Procedure Properties::        Procedure properties and meta-information.
* Procedures with Setters::     Procedures with setters.
* Macros::                      Lisp style macro definitions.
* Syntax Rules::                Support for R5RS @code{syntax-rules}.
* Syntax Case::                 Support for the @code{syntax-case} system.
* Internal Macros::             Guile's internal representation.
@end menu

@node Lambda
@subsection Lambda: Basic Procedure Creation
@cindex lambda

@c FIXME::martin: Review me!

A @code{lambda} expression evaluates to a procedure.  The environment
which is in effect when a @code{lambda} expression is evaluated is
enclosed in the newly created procedure, this is referred to as a
@dfn{closure} (@pxref{About Closure}).

When a procedure created by @code{lambda} is called with some actual
arguments, the environment enclosed in the procedure is extended by
binding the variables named in the formal argument list to new locations
and storing the actual arguments into these locations.  Then the body of
the @code{lambda} expression is evaluation sequentially.  The result of
the last expression in the procedure body is then the result of the
procedure invocation.

The following examples will show how procedures can be created using
@code{lambda}, and what you can do with these procedures.

@lisp
(lambda (x) (+ x x))       @result{} @r{a procedure}
((lambda (x) (+ x x)) 4)   @result{} 8
@end lisp

The fact that the environment in effect when creating a procedure is
enclosed in the procedure is shown with this example:

@lisp
(define add4
  (let ((x 4))
    (lambda (y) (+ x y))))
(add4 6)                   @result{} 10
@end lisp

@deffn syntax lambda formals body
@var{formals} should be a formal argument list as described in the
following table.

@table @code
@item (@var{variable1} @dots{})
The procedure takes a fixed number of arguments; when the procedure is
called, the arguments will be stored into the newly created location for
the formal variables.
@item @var{variable}
The procedure takes any number of arguments; when the procedure is
called, the sequence of actual arguments will converted into a list and
stored into the newly created location for the formal variable.
@item (@var{variable1} @dots{} @var{variablen} . @var{variablen+1})
If a space-delimited period precedes the last variable, then the
procedure takes @var{n} or more variables where @var{n} is the number
of formal arguments before the period.  There must be at least one
argument before the period.  The first @var{n} actual arguments will be
stored into the newly allocated locations for the first @var{n} formal
arguments and the sequence of the remaining actual arguments is
converted into a list and the stored into the location for the last
formal argument.  If there are exactly @var{n} actual arguments, the
empty list is stored into the location of the last formal argument.
@end table

The list in @var{variable} or @var{variablen+1} is always newly
created and the procedure can modify it if desired.  This is the case
even when the procedure is invoked via @code{apply}, the required part
of the list argument there will be copied (@pxref{Fly Evaluation,,
Procedures for On the Fly Evaluation}).

@var{body} is a sequence of Scheme expressions which are evaluated in
order when the procedure is invoked.
@end deffn

@node Primitive Procedures
@subsection Primitive Procedures
@cindex primitives
@cindex primitive procedures

Procedures written in C can be registered for use from Scheme,
provided they take only arguments of type @code{SCM} and return
@code{SCM} values.  @code{scm_c_define_gsubr} is likely to be the most
useful mechanism, combining the process of registration
(@code{scm_c_make_gsubr}) and definition (@code{scm_define}).

@deftypefun SCM scm_c_make_gsubr (const char *name, int req, int opt, int rst, fcn)
Register a C procedure @var{FCN} as a ``subr'' --- a primitive
subroutine that can be called from Scheme.  It will be associated with
the given @var{name} but no environment binding will be created.  The
arguments @var{req}, @var{opt} and @var{rst} specify the number of
required, optional and ``rest'' arguments respectively.  The total
number of these arguments should match the actual number of arguments
to @var{fcn}.  The number of rest arguments should be 0 or 1.
@code{scm_c_make_gsubr} returns a value of type @code{SCM} which is a
``handle'' for the procedure.
@end deftypefun

@deftypefun SCM scm_c_define_gsubr (const char *name, int req, int opt, int rst, fcn)
Register a C procedure @var{FCN}, as for @code{scm_c_make_gsubr}
above, and additionally create a top-level Scheme binding for the
procedure in the ``current environment'' using @code{scm_define}.
@code{scm_c_define_gsubr} returns a handle for the procedure in the
same way as @code{scm_c_make_gsubr}, which is usually not further
required.
@end deftypefun

@code{scm_c_make_gsubr} and @code{scm_c_define_gsubr} automatically
use @code{scm_c_make_subr} and also @code{scm_makcclo} if necessary.
It is advisable to use the gsubr variants since they provide a
slightly higher-level abstraction of the Guile implementation.

@node Optional Arguments
@subsection Optional Arguments

@c FIXME::martin: Review me!

Scheme procedures, as defined in R5RS, can either handle a fixed number
of actual arguments, or a fixed number of actual arguments followed by
arbitrarily many additional arguments.  Writing procedures of variable
arity can be useful, but unfortunately, the syntactic means for handling
argument lists of varying length is a bit inconvenient.  It is possible
to give names to the fixed number of argument, but the remaining
(optional) arguments can be only referenced as a list of values
(@pxref{Lambda}).

Guile comes with the module @code{(ice-9 optargs)}, which makes using
optional arguments much more convenient.  In addition, this module
provides syntax for handling keywords in argument lists
(@pxref{Keywords}).

Before using any of the procedures or macros defined in this section,
you have to load the module @code{(ice-9 optargs)} with the statement:

@cindex @code{optargs}
@lisp
(use-modules (ice-9 optargs))
@end lisp

@menu
* let-optional Reference::      Locally binding optional arguments.
* let-keywords Reference::      Locally binding keywords arguments.
* lambda* Reference::           Creating advanced argument handling procedures.
* define* Reference::           Defining procedures and macros.
@end menu

@node let-optional Reference
@subsubsection let-optional Reference

@c FIXME::martin: Review me!

The syntax @code{let-optional} and @code{let-optional*} are for
destructuring rest argument lists and giving names to the various list
elements.  @code{let-optional} binds all variables simultaneously, while
@code{let-optional*} binds them sequentially, consistent with @code{let}
and @code{let*} (@pxref{Local Bindings}).

@deffn {library syntax} let-optional rest-arg (binding @dots{}) expr @dots{}
@deffnx {library syntax} let-optional* rest-arg (binding @dots{}) expr @dots{}
These two macros give you an optional argument interface that is very
@dfn{Schemey} and introduces no fancy syntax. They are compatible with
the scsh macros of the same name, but are slightly extended. Each of
@var{binding} may be of one of the forms @var{var} or @code{(@var{var}
@var{default-value})}. @var{rest-arg} should be the rest-argument of the
procedures these are used from.  The items in @var{rest-arg} are
sequentially bound to the variable names are given. When @var{rest-arg}
runs out, the remaining vars are bound either to the default values or
@code{#f} if no default value was specified. @var{rest-arg} remains
bound to whatever may have been left of @var{rest-arg}.

After binding the variables, the expressions @var{expr} @dots{} are
evaluated in order.
@end deffn

@node let-keywords Reference
@subsubsection let-keywords Reference

@code{let-keywords} and @code{let-keywords*} extract values from
keyword style argument lists, binding local variables to those values
or to defaults.

@deffn {library syntax} let-keywords args allow-other-keys? (binding @dots{})  body @dots{}
@deffnx {library syntax} let-keywords* args allow-other-keys? (binding @dots{})  body @dots{}
@var{args} is evaluated and should give a list of the form
@code{(#:keyword1 value1 #:keyword2 value2 @dots{})}.  The
@var{binding}s are variables and default expressions, with the
variables to be set (by name) from the keyword values.  The @var{body}
forms are then evaluated and the last is the result.  An example will
make the syntax clearest,

@example
(define args '(#:xyzzy "hello" #:foo "world"))

(let-keywords args #t
      ((foo  "default for foo")
       (bar  (string-append "default" "for" "bar")))
  (display foo)
  (display ", ")
  (display bar))
@print{} world, defaultforbar
@end example

The binding for @code{foo} comes from the @code{#:foo} keyword in
@code{args}.  But the binding for @code{bar} is the default in the
@code{let-keywords}, since there's no @code{#:bar} in the args.

@var{allow-other-keys?} is evaluated and controls whether unknown
keywords are allowed in the @var{args} list.  When true other keys are
ignored (such as @code{#:xyzzy} in the example), when @code{#f} an
error is thrown for anything unknown.

@code{let-keywords} is like @code{let} (@pxref{Local Bindings}) in
that all bindings are made at once, the defaults expressions are
evaluated (if needed) outside the scope of the @code{let-keywords}.

@code{let-keywords*} is like @code{let*}, each binding is made
successively, and the default expressions see the bindings previously
made.  This is the style used by @code{lambda*} keywords
(@pxref{lambda* Reference}).  For example,

@example
(define args '(#:foo 3))

(let-keywords* args #f
      ((foo  99)
       (bar  (+ foo 6)))
  (display bar))
@print{} 9
@end example

The expression for each default is only evaluated if it's needed,
ie. if the keyword doesn't appear in @var{args}.  So one way to make a
keyword mandatory is to throw an error of some sort as the default.

@example
(define args '(#:start 7 #:finish 13))

(let-keywords* args #t
      ((start 0)
       (stop  (error "missing #:stop argument")))
  ...)
@result{} ERROR: missing #:stop argument
@end example
@end deffn

@node lambda* Reference
@subsubsection lambda* Reference

When using optional and keyword argument lists, @code{lambda} for
creating a procedure then @code{let-optional} or @code{let-keywords}
is a bit lengthy.  @code{lambda*} combines the features of those
macros into a single convenient syntax.

@deffn {library syntax} lambda* ([var@dots{}] @* [#:optional vardef@dots{}] @* [#:key  vardef@dots{} [#:allow-other-keys]] @* [#:rest var | . var]) @* body
@sp 1
Create a procedure which takes optional and/or keyword arguments
specified with @code{#:optional} and @code{#:key}.  For example,

@lisp
(lambda* (a b #:optional c d . e) '())
@end lisp

is a procedure with fixed arguments @var{a} and @var{b}, optional
arguments @var{c} and @var{d}, and rest argument @var{e}.  If the
optional arguments are omitted in a call, the variables for them are
bound to @code{#f}.

@code{lambda*} can also take keyword arguments.  For example, a procedure
defined like this:

@lisp
(lambda* (#:key xyzzy larch) '())
@end lisp

can be called with any of the argument lists @code{(#:xyzzy 11)},
@code{(#:larch 13)}, @code{(#:larch 42 #:xyzzy 19)}, @code{()}.
Whichever arguments are given as keywords are bound to values (and
those not given are @code{#f}).

Optional and keyword arguments can also have default values to take
when not present in a call, by giving a two-element list of variable
name and expression.  For example in

@lisp
(lambda* (foo #:optional (bar 42) #:key (baz 73))
     (list foo bar baz))
@end lisp

@var{foo} is a fixed argument, @var{bar} is an optional argument with
default value 42, and baz is a keyword argument with default value 73.
Default value expressions are not evaluated unless they are needed,
and until the procedure is called.

Normally it's an error if a call has keywords other than those
specified by @code{#:key}, but adding @code{#:allow-other-keys} to the
definition (after the keyword argument declarations) will ignore
unknown keywords.

If a call has a keyword given twice, the last value is used.  For
example,

@lisp
((lambda* (#:key (heads 0) (tails 0))
   (display (list heads tails)))
 #:heads 37 #:tails 42 #:heads 99)
@print{} (99 42)
@end lisp

@code{#:rest} is a synonym for the dotted syntax rest argument.  The
argument lists @code{(a . b)} and @code{(a #:rest b)} are equivalent
in all respects.  This is provided for more similarity to DSSSL,
MIT-Scheme and Kawa among others, as well as for refugees from other
Lisp dialects.

When @code{#:key} is used together with a rest argument, the keyword
parameters in a call all remain in the rest list.  This is the same as
Common Lisp.  For example,

@lisp
((lambda* (#:key (x 0) #:allow-other-keys #:rest r)
   (display r))
 #:x 123 #:y 456)
@print{} (#:x 123 #:y 456)
@end lisp

@code{#:optional} and @code{#:key} establish their bindings
successively, from left to right, as per @code{let-optional*} and
@code{let-keywords*}.  This means default expressions can refer back
to prior parameters, for example

@lisp
(lambda* (start #:optional (end (+ 10 start)))
  (do ((i start (1+ i)))
      ((> i end))
    (display i)))
@end lisp
@end deffn

@node define* Reference
@subsubsection define* Reference

@c FIXME::martin: Review me!

Just like @code{define} has a shorthand notation for defining procedures
(@pxref{Lambda Alternatives}), @code{define*} is provided as an
abbreviation of the combination of @code{define} and @code{lambda*}.

@code{define*-public} is the @code{lambda*} version of
@code{define-public}; @code{defmacro*} and @code{defmacro*-public} exist
for defining macros with the improved argument list handling
possibilities.  The @code{-public} versions not only define the
procedures/macros, but also export them from the current module.

@deffn {library syntax} define* formals body
@deffnx {library syntax} define*-public formals body
@code{define*} and @code{define*-public} support optional arguments with
a similar syntax to @code{lambda*}. They also support arbitrary-depth
currying, just like Guile's define. Some examples:

@lisp
(define* (x y #:optional a (z 3) #:key w . u)
   (display (list y z u)))
@end lisp
defines a procedure @code{x} with a fixed argument @var{y}, an optional
argument @var{a}, another optional argument @var{z} with default value 3,
a keyword argument @var{w}, and a rest argument @var{u}.

@lisp
(define-public* ((foo #:optional bar) #:optional baz) '())
@end lisp

This illustrates currying. A procedure @code{foo} is defined, which,
when called with an optional argument @var{bar}, returns a procedure
that takes an optional argument @var{baz}.

Of course, @code{define*[-public]} also supports @code{#:rest} and
@code{#:allow-other-keys} in the same way as @code{lambda*}.
@end deffn

@deffn {library syntax} defmacro* name formals body
@deffnx {library syntax} defmacro*-public name formals body
These are just like @code{defmacro} and @code{defmacro-public} except that they
take @code{lambda*}-style extended parameter lists, where @code{#:optional},
@code{#:key}, @code{#:allow-other-keys} and @code{#:rest} are allowed with the usual
semantics. Here is an example of a macro with an optional argument:

@lisp
(defmacro* transmorgify (a #:optional b)
    (a 1))
@end lisp
@end deffn

@node Procedure Properties
@subsection Procedure Properties and Meta-information

@c FIXME::martin: Review me!

Procedures always have attached the environment in which they were
created and information about how to apply them to actual arguments.  In
addition to that, properties and meta-information can be stored with
procedures.  The procedures in this section can be used to test whether
a given procedure satisfies a condition; and to access and set a
procedure's property.

The first group of procedures are predicates to test whether a Scheme
object is a procedure, or a special procedure, respectively.
@code{procedure?} is the most general predicates, it returns @code{#t}
for any kind of procedure.  @code{closure?} does not return @code{#t}
for primitive procedures, and @code{thunk?} only returns @code{#t} for
procedures which do not accept any arguments.

@rnindex procedure?
@deffn {Scheme Procedure} procedure? obj
@deffnx {C Function} scm_procedure_p (obj)
Return @code{#t} if @var{obj} is a procedure.
@end deffn

@deffn {Scheme Procedure} closure? obj
@deffnx {C Function} scm_closure_p (obj)
Return @code{#t} if @var{obj} is a closure.
@end deffn

@deffn {Scheme Procedure} thunk? obj
@deffnx {C Function} scm_thunk_p (obj)
Return @code{#t} if @var{obj} is a thunk.
@end deffn

@c FIXME::martin: Is that true?
@cindex procedure properties
Procedure properties are general properties to be attached to
procedures.  These can be the name of a procedure or other relevant
information, such as debug hints.

@deffn {Scheme Procedure} procedure-name proc
@deffnx {C Function} scm_procedure_name (proc)
Return the name of the procedure @var{proc}
@end deffn

@deffn {Scheme Procedure} procedure-source proc
@deffnx {C Function} scm_procedure_source (proc)
Return the source of the procedure @var{proc}.
@end deffn

@deffn {Scheme Procedure} procedure-environment proc
@deffnx {C Function} scm_procedure_environment (proc)
Return the environment of the procedure @var{proc}.
@end deffn

@deffn {Scheme Procedure} procedure-properties proc
@deffnx {C Function} scm_procedure_properties (proc)
Return @var{obj}'s property list.
@end deffn

@deffn {Scheme Procedure} procedure-property obj key
@deffnx {C Function} scm_procedure_property (obj, key)
Return the property of @var{obj} with name @var{key}.
@end deffn

@deffn {Scheme Procedure} set-procedure-properties! proc alist
@deffnx {C Function} scm_set_procedure_properties_x (proc, alist)
Set @var{obj}'s property list to @var{alist}.
@end deffn

@deffn {Scheme Procedure} set-procedure-property! obj key value
@deffnx {C Function} scm_set_procedure_property_x (obj, key, value)
In @var{obj}'s property list, set the property named @var{key} to
@var{value}.
@end deffn

@cindex procedure documentation
Documentation for a procedure can be accessed with the procedure
@code{procedure-documentation}.

@deffn {Scheme Procedure} procedure-documentation proc
@deffnx {C Function} scm_procedure_documentation (proc)
Return the documentation string associated with @code{proc}.  By
convention, if a procedure contains more than one expression and the
first expression is a string constant, that string is assumed to contain
documentation for that procedure.
@end deffn

@node Procedures with Setters
@subsection Procedures with Setters

@c FIXME::martin: Review me!

@c FIXME::martin: Document `operator struct'.

@cindex procedure with setter
@cindex setter
A @dfn{procedure with setter} is a special kind of procedure which
normally behaves like any accessor procedure, that is a procedure which
accesses a data structure.  The difference is that this kind of
procedure has a so-called @dfn{setter} attached, which is a procedure
for storing something into a data structure.

Procedures with setters are treated specially when the procedure appears
in the special form @code{set!} (REFFIXME).  How it works is best shown
by example.

Suppose we have a procedure called @code{foo-ref}, which accepts two
arguments, a value of type @code{foo} and an integer.  The procedure
returns the value stored at the given index in the @code{foo} object.
Let @code{f} be a variable containing such a @code{foo} data
structure.@footnote{Working definitions would be:
@lisp
(define foo-ref vector-ref)
(define foo-set! vector-set!)
(define f (make-vector 2 #f))
@end lisp
}

@lisp
(foo-ref f 0)       @result{} bar
(foo-ref f 1)       @result{} braz
@end lisp

Also suppose that a corresponding setter procedure called
@code{foo-set!} does exist.

@lisp
(foo-set! f 0 'bla)
(foo-ref f 0)       @result{} bla
@end lisp

Now we could create a new procedure called @code{foo}, which is a
procedure with setter, by calling @code{make-procedure-with-setter} with
the accessor and setter procedures @code{foo-ref} and @code{foo-set!}.
Let us call this new procedure @code{foo}.

@lisp
(define foo (make-procedure-with-setter foo-ref foo-set!))
@end lisp

@code{foo} can from now an be used to either read from the data
structure stored in @code{f}, or to write into the structure.

@lisp
(set! (foo f 0) 'dum)
(foo f 0)          @result{} dum
@end lisp

@deffn {Scheme Procedure} make-procedure-with-setter procedure setter
@deffnx {C Function} scm_make_procedure_with_setter (procedure, setter)
Create a new procedure which behaves like @var{procedure}, but
with the associated setter @var{setter}.
@end deffn

@deffn {Scheme Procedure} procedure-with-setter? obj
@deffnx {C Function} scm_procedure_with_setter_p (obj)
Return @code{#t} if @var{obj} is a procedure with an
associated setter procedure.
@end deffn

@deffn {Scheme Procedure} procedure proc
@deffnx {C Function} scm_procedure (proc)
Return the procedure of @var{proc}, which must be either a
procedure with setter, or an operator struct.
@end deffn

@deffn {Scheme Procedure} setter proc
Return the setter of @var{proc}, which must be either a procedure with
setter or an operator struct.
@end deffn

@node Macros
@subsection Lisp Style Macro Definitions

@cindex macros
@cindex transformation
Macros are objects which cause the expression that they appear in to be
transformed in some way @emph{before} being evaluated.  In expressions
that are intended for macro transformation, the identifier that names
the relevant macro must appear as the first element, like this:

@lisp
(@var{macro-name} @var{macro-args} @dots{})
@end lisp

In Lisp-like languages, the traditional way to define macros is very
similar to procedure definitions.  The key differences are that the
macro definition body should return a list that describes the
transformed expression, and that the definition is marked as a macro
definition (rather than a procedure definition) by the use of a
different definition keyword: in Lisp, @code{defmacro} rather than
@code{defun}, and in Scheme, @code{define-macro} rather than
@code{define}.

@fnindex defmacro
@fnindex define-macro
Guile supports this style of macro definition using both @code{defmacro}
and @code{define-macro}.  The only difference between them is how the
macro name and arguments are grouped together in the definition:

@lisp
(defmacro @var{name} (@var{args} @dots{}) @var{body} @dots{})
@end lisp

@noindent
is the same as

@lisp
(define-macro (@var{name} @var{args} @dots{}) @var{body} @dots{})
@end lisp

@noindent
The difference is analogous to the corresponding difference between
Lisp's @code{defun} and Scheme's @code{define}.

@code{false-if-exception}, from the @file{boot-9.scm} file in the Guile
distribution, is a good example of macro definition using
@code{defmacro}:

@lisp
(defmacro false-if-exception (expr)
  `(catch #t
          (lambda () ,expr)
          (lambda args #f)))
@end lisp

@noindent
The effect of this definition is that expressions beginning with the
identifier @code{false-if-exception} are automatically transformed into
a @code{catch} expression following the macro definition specification.
For example:

@lisp
(false-if-exception (open-input-file "may-not-exist"))
@equiv{}
(catch #t
       (lambda () (open-input-file "may-not-exist"))
       (lambda args #f))
@end lisp

@node Syntax Rules
@subsection The R5RS @code{syntax-rules} System
@cindex R5RS syntax-rules system

R5RS defines an alternative system for macro and syntax transformations
using the keywords @code{define-syntax}, @code{let-syntax},
@code{letrec-syntax} and @code{syntax-rules}.

The main difference between the R5RS system and the traditional macros
of the previous section is how the transformation is specified.  In
R5RS, rather than permitting a macro definition to return an arbitrary
expression, the transformation is specified in a pattern language that

@itemize @bullet
@item
does not require complicated quoting and extraction of components of the
source expression using @code{caddr} etc.

@item
is designed such that the bindings associated with identifiers in the
transformed expression are well defined, and such that it is impossible
for the transformed expression to construct new identifiers.
@end itemize

@noindent
The last point is commonly referred to as being @dfn{hygienic}: the R5RS
@code{syntax-case} system provides @dfn{hygienic macros}.

For example, the R5RS pattern language for the @code{false-if-exception}
example of the previous section looks like this:

@lisp
(syntax-rules ()
  ((_ expr)
   (catch #t
          (lambda () expr)
          (lambda args #f))))
@end lisp

@cindex @code{syncase}
In Guile, the @code{syntax-rules} system is provided by the @code{(ice-9
syncase)} module.  To make these facilities available in your code,
include the expression @code{(use-syntax (ice-9 syncase))} (@pxref{Using
Guile Modules}) before the first usage of @code{define-syntax} etc.  If
you are writing a Scheme module, you can alternatively include the form
@code{#:use-syntax (ice-9 syncase)} in your @code{define-module}
declaration (@pxref{Creating Guile Modules}).

@menu
* Pattern Language::            The @code{syntax-rules} pattern language.
* Define-Syntax::               Top level syntax definitions.
* Let-Syntax::                  Local syntax definitions.
@end menu

@node Pattern Language
@subsubsection The @code{syntax-rules} Pattern Language

@node Define-Syntax
@subsubsection Top Level Syntax Definitions

define-syntax:  The gist is

  (define-syntax <keyword> <transformer-spec>)

makes the <keyword> into a macro so that

  (<keyword> ...)

expands at _compile_ or _read_ time (i.e. before any
evaluation begins) into some expression that is
given by the <transformer-spec>.

@node Let-Syntax
@subsubsection Local Syntax Definitions

@node Syntax Case
@subsection Support for the @code{syntax-case} System

@node Internal Macros
@subsection Internal Representation of Macros and Syntax

Internally, Guile uses three different flavors of macros.  The three
flavors are called @dfn{acro} (or @dfn{syntax}), @dfn{macro} and
@dfn{mmacro}.

Given the expression

@lisp
(foo @dots{})
@end lisp

@noindent
with @code{foo} being some flavor of macro, one of the following things
will happen when the expression is evaluated.

@itemize @bullet
@item
When @code{foo} has been defined to be an @dfn{acro}, the procedure used
in the acro definition of @code{foo} is passed the whole expression and
the current lexical environment, and whatever that procedure returns is
the value of evaluating the expression.  You can think of this a
procedure that receives its argument as an unevaluated expression.

@item
When @code{foo} has been defined to be a @dfn{macro}, the procedure used
in the macro definition of @code{foo} is passed the whole expression and
the current lexical environment, and whatever that procedure returns is
evaluated again.  That is, the procedure should return a valid Scheme
expression.

@item
When @code{foo} has been defined to be a @dfn{mmacro}, the procedure
used in the mmacro definition of `foo' is passed the whole expression
and the current lexical environment, and whatever that procedure returns
replaces the original expression.  Evaluation then starts over from the
new expression that has just been returned.
@end itemize

The key difference between a @dfn{macro} and a @dfn{mmacro} is that the
expression returned by a @dfn{mmacro} procedure is remembered (or
@dfn{memoized}) so that the expansion does not need to be done again
next time the containing code is evaluated.

The primitives @code{procedure->syntax}, @code{procedure->macro} and
@code{procedure->memoizing-macro} are used to construct acros, macros
and mmacros respectively.  However, if you do not have a very special
reason to use one of these primitives, you should avoid them: they are
very specific to Guile's current implementation and therefore likely to
change.  Use @code{defmacro}, @code{define-macro} (@pxref{Macros}) or
@code{define-syntax} (@pxref{Syntax Rules}) instead.  (In low level
terms, @code{defmacro}, @code{define-macro} and @code{define-syntax} are
all implemented as mmacros.)

@deffn {Scheme Procedure} procedure->syntax code
@deffnx {C Function} scm_makacro (code)
Return a macro which, when a symbol defined to this value appears as the
first symbol in an expression, returns the result of applying @var{code}
to the expression and the environment.
@end deffn

@deffn {Scheme Procedure} procedure->macro code
@deffnx {C Function} scm_makmacro (code)
Return a macro which, when a symbol defined to this value appears as the
first symbol in an expression, evaluates the result of applying
@var{code} to the expression and the environment.  For example:

@lisp
(define trace
  (procedure->macro
    (lambda (x env)
      `(set! ,(cadr x) (tracef ,(cadr x) ',(cadr x))))))

(trace @i{foo})
@equiv{}
(set! @i{foo} (tracef @i{foo} '@i{foo})).
@end lisp
@end deffn

@deffn {Scheme Procedure} procedure->memoizing-macro code
@deffnx {C Function} scm_makmmacro (code)
Return a macro which, when a symbol defined to this value appears as the
first symbol in an expression, evaluates the result of applying
@var{code} to the expression and the environment.
@code{procedure->memoizing-macro} is the same as
@code{procedure->macro}, except that the expression returned by
@var{code} replaces the original macro expression in the memoized form
of the containing code.
@end deffn

In the following primitives, @dfn{acro} flavor macros are referred to
as @dfn{syntax transformers}.

@deffn {Scheme Procedure} macro? obj
@deffnx {C Function} scm_macro_p (obj)
Return @code{#t} if @var{obj} is a regular macro, a memoizing macro or a
syntax transformer.
@end deffn

@deffn {Scheme Procedure} macro-type m
@deffnx {C Function} scm_macro_type (m)
Return one of the symbols @code{syntax}, @code{macro} or
@code{macro!}, depending on whether @var{m} is a syntax
transformer, a regular macro, or a memoizing macro,
respectively.  If @var{m} is not a macro, @code{#f} is
returned.
@end deffn

@deffn {Scheme Procedure} macro-name m
@deffnx {C Function} scm_macro_name (m)
Return the name of the macro @var{m}.
@end deffn

@deffn {Scheme Procedure} macro-transformer m
@deffnx {C Function} scm_macro_transformer (m)
Return the transformer of the macro @var{m}.
@end deffn

@deffn {Scheme Procedure} cons-source xorig x y
@deffnx {C Function} scm_cons_source (xorig, x, y)
Create and return a new pair whose car and cdr are @var{x} and @var{y}.
Any source properties associated with @var{xorig} are also associated
with the new pair.
@end deffn

@c Local Variables:
@c TeX-master: "guile.texi"
@c End:


code:
@c -*-texinfo-*-
@c This is part of the GNU Guile Reference Manual.
@c Copyright (C)  1996, 1997, 2000, 2001, 2002, 2003, 2004, 2008
@c   Free Software Foundation, Inc.
@c See the file guile.texi for copying conditions.

@page
@node Scheduling
@section Threads, Mutexes, Asyncs and Dynamic Roots

[FIXME: This is pasted in from Tom Lord's original guile.texi chapter
plus the Cygnus programmer's manual; it should be *very* carefully
reviewed and largely reorganized.]

@menu
* Arbiters::                    Synchronization primitives.
* Asyncs::                      Asynchronous procedure invocation.
* Continuation Barriers::       Protection from non-local control flow.
* Threads::                     Multiple threads of execution.
* Mutexes and Condition Variables:: Synchronization primitives.
* Blocking::                    How to block properly in guile mode.
* Critical Sections::           Avoiding concurrency and reentries.
* Fluids and Dynamic States::   Thread-local variables, etc.
* Parallel Forms::              Parallel execution of forms.
@end menu

@node Arbiters
@subsection Arbiters
@cindex arbiters

Arbiters are synchronization objects, they can be used by threads to
control access to a shared resource.  An arbiter can be locked to
indicate a resource is in use, and unlocked when done.

An arbiter is like a light-weight mutex (@pxref{Mutexes and Condition
Variables}).  It uses less memory and may be faster, but there's no
way for a thread to block waiting on an arbiter, it can only test and
get the status returned.

@deffn {Scheme Procedure} make-arbiter name
@deffnx {C Function} scm_make_arbiter (name)
Return an object of type arbiter and name @var{name}. Its
state is initially unlocked.  Arbiters are a way to achieve
process synchronization.
@end deffn

@deffn {Scheme Procedure} try-arbiter arb
@deffnx {C Function} scm_try_arbiter (arb)
@deffnx {C Function} scm_try_arbiter (arb)
If @var{arb} is unlocked, then lock it and return @code{#t}.
If @var{arb} is already locked, then do nothing and return
@code{#f}.
@end deffn

@deffn {Scheme Procedure} release-arbiter arb
@deffnx {C Function} scm_release_arbiter (arb)
If @var{arb} is locked, then unlock it and return @code{#t}.  If
@var{arb} is already unlocked, then do nothing and return @code{#f}.

Typical usage is for the thread which locked an arbiter to later
release it, but that's not required, any thread can release it.
@end deffn

@node Asyncs
@subsection Asyncs

@cindex asyncs
@cindex user asyncs
@cindex system asyncs

Asyncs are a means of deferring the excution of Scheme code until it is
safe to do so.

Guile provides two kinds of asyncs that share the basic concept but are
otherwise quite different: system asyncs and user asyncs.  System asyncs
are integrated into the core of Guile and are executed automatically
when the system is in a state to allow the execution of Scheme code.
For example, it is not possible to execute Scheme code in a POSIX signal
handler, but such a signal handler can queue a system async to be
executed in the near future, when it is safe to do so.

System asyncs can also be queued for threads other than the current one.
This way, you can cause threads to asynchronously execute arbitrary
code.

User asyncs offer a convenient means of queueing procedures for future
execution and triggering this execution.  They will not be executed
automatically.

@menu
* System asyncs::
* User asyncs::
@end menu

@node System asyncs
@subsubsection System asyncs

To cause the future asynchronous execution of a procedure in a given
thread, use @code{system-async-mark}.

Automatic invocation of system asyncs can be temporarily disabled by
calling @code{call-with-blocked-asyncs}.  This function works by
temporarily increasing the @emph{async blocking level} of the current
thread while a given procedure is running.  The blocking level starts
out at zero, and whenever a safe point is reached, a blocking level
greater than zero will prevent the execution of queued asyncs.

Analogously, the procedure @code{call-with-unblocked-asyncs} will
temporarily decrease the blocking level of the current thread.  You
can use it when you want to disable asyncs by default and only allow
them temporarily.

In addition to the C versions of @code{call-with-blocked-asyncs} and
@code{call-with-unblocked-asyncs}, C code can use
@code{scm_dynwind_block_asyncs} and @code{scm_dynwind_unblock_asyncs}
inside a @dfn{dynamic context} (@pxref{Dynamic Wind}) to block or
unblock system asyncs temporarily.

@deffn {Scheme Procedure} system-async-mark proc [thread]
@deffnx {C Function} scm_system_async_mark (proc)
@deffnx {C Function} scm_system_async_mark_for_thread (proc, thread)
Mark @var{proc} (a procedure with zero arguments) for future execution
in @var{thread}.  When @var{proc} has already been marked for
@var{thread} but has not been executed yet, this call has no effect.
When @var{thread} is omitted, the thread that called
@code{system-async-mark} is used.

This procedure is not safe to be called from signal handlers.  Use
@code{scm_sigaction} or @code{scm_sigaction_for_thread} to install
signal handlers.
@end deffn

@c  FIXME: The use of @deffnx for scm_c_call_with_blocked_asyncs and
@c  scm_c_call_with_unblocked_asyncs puts "void" into the function
@c  index.  Would prefer to use @deftypefnx if makeinfo allowed that,
@c  or a @deftypefn with an empty return type argument if it didn't
@c  introduce an extra space.

@deffn {Scheme Procedure} call-with-blocked-asyncs proc
@deffnx {C Function} scm_call_with_blocked_asyncs (proc)
@deffnx {C Function} {void *} scm_c_call_with_blocked_asyncs (void * (*proc) (void *data), void *data)
@findex scm_c_call_with_blocked_asyncs
Call @var{proc} and block the execution of system asyncs by one level
for the current thread while it is running.  Return the value returned
by @var{proc}.  For the first two variants, call @var{proc} with no
arguments; for the third, call it with @var{data}.
@end deffn

@deffn {Scheme Procedure} call-with-unblocked-asyncs proc
@deffnx {C Function} scm_call_with_unblocked_asyncs (proc)
@deffnx {C Function} {void *} scm_c_call_with_unblocked_asyncs (void *(*p) (void *d), void *d)
@findex scm_c_call_with_unblocked_asyncs
Call @var{proc} and unblock the execution of system asyncs by one
level for the current thread while it is running.  Return the value
returned by @var{proc}.  For the first two variants, call @var{proc}
with no arguments; for the third, call it with @var{data}.
@end deffn

@deftypefn {C Function} void scm_dynwind_block_asyncs ()
This function must be used inside a pair of calls to
@code{scm_dynwind_begin} and @code{scm_dynwind_end} (@pxref{Dynamic
Wind}).  During the dynwind context, asyncs are blocked by one level.
@end deftypefn

@deftypefn {C Function} void scm_dynwind_unblock_asyncs ()
This function must be used inside a pair of calls to
@code{scm_dynwind_begin} and @code{scm_dynwind_end} (@pxref{Dynamic
Wind}).  During the dynwind context, asyncs are unblocked by one
level.
@end deftypefn

@node User asyncs
@subsubsection User asyncs

A user async is a pair of a thunk (a parameterless procedure) and a
mark.  Setting the mark on a user async will cause the thunk to be
executed when the user async is passed to @code{run-asyncs}.  Setting
the mark more than once is satisfied by one execution of the thunk.

User asyncs are created with @code{async}.  They are marked with
@code{async-mark}.

@deffn {Scheme Procedure} async thunk
@deffnx {C Function} scm_async (thunk)
Create a new user async for the procedure @var{thunk}.
@end deffn

@deffn {Scheme Procedure} async-mark a
@deffnx {C Function} scm_async_mark (a)
Mark the user async @var{a} for future execution.
@end deffn

@deffn {Scheme Procedure} run-asyncs list_of_a
@deffnx {C Function} scm_run_asyncs (list_of_a)
Execute all thunks from the marked asyncs of the list @var{list_of_a}.
@end deffn

@node Continuation Barriers
@subsection Continuation Barriers

The non-local flow of control caused by continuations might sometimes
not be wanted.  You can use @code{with-continuation-barrier} etc to
errect fences that continuations can not pass.

@deffn {Scheme Procedure} with-continuation-barrier proc
@deffnx {C Function} scm_with_continuation_barrier (proc)
Call @var{proc} and return its result.  Do not allow the invocation of
continuations that would leave or enter the dynamic extent of the call
to @code{with-continuation-barrier}.  Such an attempt causes an error
to be signaled.

Throws (such as errors) that are not caught from within @var{proc} are
caught by @code{with-continuation-barrier}.  In that case, a short
message is printed to the current error port and @code{#f} is returned.

Thus, @code{with-continuation-barrier} returns exactly once.
@end deffn

@deftypefn {C Function} {void *} scm_c_with_continuation_barrier (void *(*func) (void *), void *data)
Like @code{scm_with_continuation_barrier} but call @var{func} on
@var{data}.  When an error is caught, @code{NULL} is returned.
@end deftypefn

@node Threads
@subsection Threads
@cindex threads
@cindex Guile threads
@cindex POSIX threads

@deffn {Scheme Procedure} all-threads
@deffnx {C Function} scm_all_threads ()
Return a list of all threads.
@end deffn

@deffn {Scheme Procedure} current-thread
@deffnx {C Function} scm_current_thread ()
Return the thread that called this function.
@end deffn

@c begin (texi-doc-string "guile" "call-with-new-thread")
@deffn {Scheme Procedure} call-with-new-thread thunk [handler]
Call @code{thunk} in a new thread and with a new dynamic state,
returning the new thread.  The procedure @var{thunk} is called via
@code{with-continuation-barrier}.

When @var{handler} is specified, then @var{thunk} is called from
within a @code{catch} with tag @code{#t} that has @var{handler} as its
handler.  This catch is established inside the continuation barrier.

Once @var{thunk} or @var{handler} returns, the return value is made
the @emph{exit value} of the thread and the thread is terminated.
@end deffn

@deftypefn {C Function} SCM scm_spawn_thread (scm_t_catch_body body, void *body_data, scm_t_catch_handler handler, void *handler_data)
Call @var{body} in a new thread, passing it @var{body_data}, returning
the new thread.  The function @var{body} is called via
@code{scm_c_with_continuation_barrier}.

When @var{handler} is non-@code{NULL}, @var{body} is called via
@code{scm_internal_catch} with tag @code{SCM_BOOL_T} that has
@var{handler} and @var{handler_data} as the handler and its data.  This
catch is established inside the continuation barrier.

Once @var{body} or @var{handler} returns, the return value is made the
@emph{exit value} of the thread and the thread is terminated.
@end deftypefn

@c begin (texi-doc-string "guile" "join-thread")
@deffn {Scheme Procedure} join-thread thread
@deffnx {C Function} scm_join_thread (thread)
Wait for @var{thread} to terminate and return its exit value.  Threads
that have not been created with @code{call-with-new-thread} or
@code{scm_spawn_thread} have an exit value of @code{#f}.
@end deffn

@deffn {Scheme Procedure} thread-exited? thread
@deffnx {C Function} scm_thread_exited_p (thread)
Return @code{#t} iff @var{thread} has exited.
@end deffn

@c begin (texi-doc-string "guile" "yield")
@deffn {Scheme Procedure} yield
If one or more threads are waiting to execute, calling yield forces an
immediate context switch to one of them. Otherwise, yield has no effect.
@end deffn

Higher level thread procedures are available by loading the
@code{(ice-9 threads)} module.  These provide standardized
thread creation.

@deffn macro make-thread proc [args@dots{}]
Apply @var{proc} to @var{args} in a new thread formed by
@code{call-with-new-thread} using a default error handler that display
the error to the current error port.  The @var{args@dots{}}
expressions are evaluated in the new thread.
@end deffn

@deffn macro begin-thread first [rest@dots{}]
Evaluate forms @var{first} and @var{rest} in a new thread formed by
@code{call-with-new-thread} using a default error handler that display
the error to the current error port.
@end deffn

@node Mutexes and Condition Variables
@subsection Mutexes and Condition Variables
@cindex mutex
@cindex condition variable

A mutex is a thread synchronization object, it can be used by threads
to control access to a shared resource.  A mutex can be locked to
indicate a resource is in use, and other threads can then block on the
mutex to wait for the resource (or can just test and do something else
if not available).  ``Mutex'' is short for ``mutual exclusion''.

There are two types of mutexes in Guile, ``standard'' and
``recursive''.  They're created by @code{make-mutex} and
@code{make-recursive-mutex} respectively, the operation functions are
then common to both.

Note that for both types of mutex there's no protection against a
``deadly embrace''.  For instance if one thread has locked mutex A and
is waiting on mutex B, but another thread owns B and is waiting on A,
then an endless wait will occur (in the current implementation).
Acquiring requisite mutexes in a fixed order (like always A before B)
in all threads is one way to avoid such problems.

@sp 1
@deffn {Scheme Procedure} make-mutex
@deffnx {C Function} scm_make_mutex ()
Return a new standard mutex.  It is initially unlocked.
@end deffn

@deffn {Scheme Procedure} make-recursive-mutex
@deffnx {C Function} scm_make_recursive_mutex ()
Create a new recursive mutex.  It is initialloy unlocked.
@end deffn

@deffn {Scheme Procedure} lock-mutex mutex
@deffnx {C Function} scm_lock_mutex (mutex)
Lock @var{mutex}.  If the mutex is already locked by another thread
then block and return only when @var{mutex} has been acquired.

For standard mutexes (@code{make-mutex}), and error is signalled if
the thread has itself already locked @var{mutex}.

For a recursive mutex (@code{make-recursive-mutex}), if the thread has
itself already locked @var{mutex}, then a further @code{lock-mutex}
call increments the lock count.  An additional @code{unlock-mutex}
will be required to finally release.

When a system async (@pxref{System asyncs}) is activated for a thread
blocked in @code{lock-mutex}, the wait is interrupted and the async is
executed.  When the async returns, the wait resumes.
@end deffn

@deftypefn {C Function} void scm_dynwind_lock_mutex (SCM mutex)
Arrange for @var{mutex} to be locked whenever the current dynwind
context is entered and to be unlocked when it is exited.
@end deftypefn

@deffn {Scheme Procedure} try-mutex mx
@deffnx {C Function} scm_try_mutex (mx)
Try to lock @var{mutex} as per @code{lock-mutex}.  If @var{mutex} can
be acquired immediately then this is done and the return is @code{#t}.
If @var{mutex} is locked by some other thread then nothing is done and
the return is @code{#f}.
@end deffn

@deffn {Scheme Procedure} unlock-mutex mutex
@deffnx {C Function} scm_unlock_mutex (mutex)
Unlock @var{mutex}.  An error is signalled if @var{mutex} is not
locked by the calling thread.
@end deffn

@deffn {Scheme Procedure} make-condition-variable
@deffnx {C Function} scm_make_condition_variable ()
Return a new condition variable.
@end deffn

@deffn {Scheme Procedure} wait-condition-variable condvar mutex [time]
@deffnx {C Function} scm_wait_condition_variable (condvar, mutex, time)
Wait until @var{condvar} has been signalled.  While waiting,
@var{mutex} is atomically unlocked (as with @code{unlock-mutex}) and
is locked again when this function returns.  When @var{time} is given,
it specifies a point in time where the waiting should be aborted.  It
can be either a integer as returned by @code{current-time} or a pair
as returned by @code{gettimeofday}.  When the waiting is aborted,
@code{#f} is returned.  When the condition variable has in fact been
signalled, @code{#t} is returned.  The mutex is re-locked in any case
before @code{wait-condition-variable} returns.

When a system async is activated for a thread that is blocked in a
call to @code{wait-condition-variable}, the waiting is interrupted,
the mutex is locked, and the async is executed.  When the async
returns, the mutex is unlocked again and the waiting is resumed.  When
the thread block while re-acquiring the mutex, execution of asyncs is
blocked.
@end deffn

@deffn {Scheme Procedure} signal-condition-variable condvar
@deffnx {C Function} scm_signal_condition_variable (condvar)
Wake up one thread that is waiting for @var{condvar}.
@end deffn

@deffn {Scheme Procedure} broadcast-condition-variable condvar
@deffnx {C Function} scm_broadcast_condition_variable (condvar)
Wake up all threads that are waiting for @var{condvar}.
@end deffn

@sp 1
The following are higher level operations on mutexes.  These are
available from

@example
(use-modules (ice-9 threads))
@end example

@deffn macro with-mutex mutex [body@dots{}]
Lock @var{mutex}, evaluate the @var{body} forms, then unlock
@var{mutex}.  The return value is the return from the last @var{body}
form.

The lock, body and unlock form the branches of a @code{dynamic-wind}
(@pxref{Dynamic Wind}), so @var{mutex} is automatically unlocked if an
error or new continuation exits @var{body}, and is re-locked if
@var{body} is re-entered by a captured continuation.
@end deffn

@deffn macro monitor body@dots{}
Evaluate the @var{body} forms, with a mutex locked so only one thread
can execute that code at any one time.  The return value is the return
from the last @var{body} form.

Each @code{monitor} form has its own private mutex and the locking and
evaluation is as per @code{with-mutex} above.  A standard mutex
(@code{make-mutex}) is used, which means @var{body} must not
recursively re-enter the @code{monitor} form.

The term ``monitor'' comes from operating system theory, where it
means a particular bit of code managing access to some resource and
which only ever executes on behalf of one process at any one time.
@end deffn

@node Blocking
@subsection Blocking in Guile Mode

A thread must not block outside of a libguile function while it is in
guile mode.  The following functions can be used to temporily leave
guile mode or to perform some common blocking operations in a supported
way.

@deftypefn {C Function} {void *} scm_without_guile (void *(*func) (void *), void *data)
Leave guile mode, call @var{func} on @var{data}, enter guile mode and
return the result of calling @var{func}.

While a thread has left guile mode, it must not call any libguile
functions except @code{scm_with_guile} or @code{scm_without_guile} and
must not use any libguile macros.  Also, local variables of type
@code{SCM} that are allocated while not in guile mode are not
protected from the garbage collector.

When used from non-guile mode, calling @code{scm_without_guile} is
still allowed: it simply calls @var{func}.  In that way, you can leave
guile mode without having to know whether the current thread is in
guile mode or not.
@end deftypefn

@deftypefn {C Function} int scm_pthread_mutex_lock (pthread_mutex_t *mutex)
Like @code{pthread_mutex_lock}, but leaves guile mode while waiting for
the mutex.
@end deftypefn

@deftypefn  {C Function} int scm_pthread_cond_wait (pthread_cond_t *cond, pthread_mutex_t *mutex)
@deftypefnx {C Function} int scm_pthread_cond_timedwait (pthread_cond_t *cond, pthread_mutex_t *mutex, struct timespec *abstime)
Like @code{pthread_cond_wait} and @code{pthread_cond_timedwait}, but
leaves guile mode while waiting for the condition variable.
@end deftypefn

@deftypefn {C Function} int scm_std_select (int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout)
Like @code{select} but leaves guile mode while waiting.  Also, the
delivery of a system async causes this function to be interrupted with
error code @code{EINTR}.
@end deftypefn

@deftypefn {C Function} {unsigned int} scm_std_sleep ({unsigned int} seconds)
Like @code{sleep}, but leaves guile mode while sleeping.  Also, the
delivery of a system async causes this function to be interrupted.
@end deftypefn

@deftypefn {C Function} {unsigned long} scm_std_usleep ({unsigned long} usecs)
Like @code{usleep}, but leaves guile mode while sleeping.  Also, the
delivery of a system async causes this function to be interrupted.
@end deftypefn

@node Critical Sections
@subsection Critical Sections

@deffn  {C Macro} SCM_CRITICAL_SECTION_START
@deffnx {C Macro} SCM_CRITICAL_SECTION_END
These two macros can be used to delimit a critical section.
Syntactically, they are both statements and need to be followed
immediately by a semicolon.

Executing @code{SCM_CRITICAL_SECTION_START} will lock a recursive
mutex and block the executing of system asyncs.  Executing
@code{SCM_CRITICAL_SECTION_END} will unblock the execution of system
asyncs and unlock the mutex.  Thus, the code that executes between
these two macros can only be executed in one thread at any one time
and no system asyncs will run.  However, because the mutex is a
recursive one, the code might still be reentered by the same thread.
You must either allow for this or avoid it, both by careful coding.

On the other hand, critical sections delimited with these macros can
be nested since the mutex is recursive.

You must make sure that for each @code{SCM_CRITICAL_SECTION_START},
the corresponding @code{SCM_CRITICAL_SECTION_END} is always executed.
This means that no non-local exit (such as a signalled error) might
happen, for example.
@end deffn

@deftypefn {C Function} void scm_dynwind_critical_section (SCM mutex)
Call @code{scm_dynwind_lock_mutex} on @var{mutex} and call
@code{scm_dynwind_block_asyncs}.  When @var{mutex} is false, a recursive
mutex provided by Guile is used instead.

The effect of a call to @code{scm_dynwind_critical_section} is that
the current dynwind context (@pxref{Dynamic Wind}) turns into a
critical section.  Because of the locked mutex, no second thread can
enter it concurrently and because of the blocked asyncs, no system
async can reenter it from the current thread.

When the current thread reenters the critical section anyway, the kind
of @var{mutex} determines what happens: When @var{mutex} is recursive,
the reentry is allowed.  When it is a normal mutex, an error is
signalled.
@end deftypefn

@node Fluids and Dynamic States
@subsection Fluids and Dynamic States

@cindex fluids

A @emph{fluid} is an object that can store one value per @emph{dynamic
state}.  Each thread has a current dynamic state, and when accessing a
fluid, this current dynamic state is used to provide the actual value.
In this way, fluids can be used for thread local storage, but they are
in fact more flexible: dynamic states are objects of their own and can
be made current for more than one thread at the same time, or only be
made current temporarily, for example.

Fluids can also be used to simulate the desirable effects of
dynamically scoped variables.  Dynamically scoped variables are useful
when you want to set a variable to a value during some dynamic extent
in the execution of your program and have them revert to their
original value when the control flow is outside of this dynamic
extent.  See the description of @code{with-fluids} below for details.

New fluids are created with @code{make-fluid} and @code{fluid?} is
used for testing whether an object is actually a fluid.  The values
stored in a fluid can be accessed with @code{fluid-ref} and
@code{fluid-set!}.

@deffn {Scheme Procedure} make-fluid
@deffnx {C Function} scm_make_fluid ()
Return a newly created fluid.
Fluids are objects that can hold one
value per dynamic state.  That is, modifications to this value are
only visible to code that executes with the same dynamic state as
the modifying code.  When a new dynamic state is constructed, it
inherits the values from its parent.  Because each thread normally executes
with its own dynamic state, you can use fluids for thread local storage.
@end deffn

@deffn {Scheme Procedure} fluid? obj
@deffnx {C Function} scm_fluid_p (obj)
Return @code{#t} iff @var{obj} is a fluid; otherwise, return
@code{#f}.
@end deffn

@deffn {Scheme Procedure} fluid-ref fluid
@deffnx {C Function} scm_fluid_ref (fluid)
Return the value associated with @var{fluid} in the current
dynamic root.  If @var{fluid} has not been set, then return
@code{#f}.
@end deffn

@deffn {Scheme Procedure} fluid-set! fluid value
@deffnx {C Function} scm_fluid_set_x (fluid, value)
Set the value associated with @var{fluid} in the current dynamic root.
@end deffn

@code{with-fluids*} temporarily changes the values of one or more fluids,
so that the given procedure and each procedure called by it access the
given values.  After the procedure returns, the old values are restored.

@deffn {Scheme Procedure} with-fluid* fluid value thunk
@deffnx {C Function} scm_with_fluid (fluid, value, thunk)
Set @var{fluid} to @var{value} temporarily, and call @var{thunk}.
@var{thunk} must be a procedure with no argument.
@end deffn

@deffn {Scheme Procedure} with-fluids* fluids values thunk
@deffnx {C Function} scm_with_fluids (fluids, values, thunk)
Set @var{fluids} to @var{values} temporary, and call @var{thunk}.
@var{fluids} must be a list of fluids and @var{values} must be the
same number of their values to be applied.  Each substitution is done
in the order given.  @var{thunk} must be a procedure with no argument.
it is called inside a @code{dynamic-wind} and the fluids are
set/restored when control enter or leaves the established dynamic
extent.
@end deffn

@deffn {Scheme Macro} with-fluids ((fluid value) ...) body...
Execute @var{body...} while each @var{fluid} is set to the
corresponding @var{value}.  Both @var{fluid} and @var{value} are
evaluated and @var{fluid} must yield a fluid.  @var{body...} is
executed inside a @code{dynamic-wind} and the fluids are set/restored
when control enter or leaves the established dynamic extent.
@end deffn

@deftypefn {C Function} SCM scm_c_with_fluids (SCM fluids, SCM vals, SCM (*cproc)(void *), void *data)
@deftypefnx {C Function} SCM scm_c_with_fluid (SCM fluid, SCM val, SCM (*cproc)(void *), void *data)
The function @code{scm_c_with_fluids} is like @code{scm_with_fluids}
except that it takes a C function to call instead of a Scheme thunk.

The function @code{scm_c_with_fluid} is similar but only allows one
fluid to be set instead of a list.
@end deftypefn

@deftypefn {C Function} void scm_dynwind_fluid (SCM fluid, SCM val)
This function must be used inside a pair of calls to
@code{scm_dynwind_begin} and @code{scm_dynwind_end} (@pxref{Dynamic
Wind}).  During the dynwind context, the fluid @var{fluid} is set to
@var{val}.

More precisely, the value of the fluid is swapped with a `backup'
value whenever the dynwind context is entered or left.  The backup
value is initialized with the @var{val} argument.
@end deftypefn

@deffn {Scheme Procedure} make-dynamic-state [parent]
@deffnx {C Function} scm_make_dynamic_state (parent)
Return a copy of the dynamic state object @var{parent}
or of the current dynamic state when @var{parent} is omitted.
@end deffn

@deffn {Scheme Procedure} dynamic-state? obj
@deffnx {C Function} scm_dynamic_state_p (obj)
Return @code{#t} if @var{obj} is a dynamic state object;
return @code{#f} otherwise.
@end deffn

@deftypefn {C Procedure} int scm_is_dynamic_state (SCM obj)
Return non-zero if @var{obj} is a dynamic state object;
return zero otherwise.
@end deftypefn

@deffn {Scheme Procedure} current-dynamic-state
@deffnx {C Function} scm_current_dynamic_state ()
Return the current dynamic state object.
@end deffn

@deffn {Scheme Procedure} set-current-dynamic-state state
@deffnx {C Function} scm_set_current_dynamic_state (state)
Set the current dynamic state object to @var{state}
and return the previous current dynamic state object.
@end deffn

@deffn {Scheme Procedure} with-dynamic-state state proc
@deffnx {C Function} scm_with_dynamic_state (state, proc)
Call @var{proc} while @var{state} is the current dynamic
state object.
@end deffn

@deftypefn {C Procedure} void scm_dynwind_current_dynamic_state (SCM state)
Set the current dynamic state to @var{state} for the current dynwind
context.
@end deftypefn

@deftypefn {C Procedure} {void *} scm_c_with_dynamic_state (SCM state, void *(*func)(void *), void *data)
Like @code{scm_with_dynamic_state}, but call @var{func} with
@var{data}.
@end deftypefn

@c @node Futures
@c @subsection Futures
@c @cindex futures

@c -- Futures are disabled for the time being, see futures.h for an
@c -- explanation.

@c Futures are a convenient way to run a calculation in a new thread, and
@c only wait for the result when it's actually needed.

@c Futures are similar to promises (@pxref{Delayed Evaluation}), in that
@c they allow mainline code to continue immediately.  But @code{delay}
@c doesn't evaluate at all until forced, whereas @code{future} starts
@c immediately in a new thread.

@c @deffn {syntax} future expr
@c Begin evaluating @var{expr} in a new thread, and return a ``future''
@c object representing the calculation.
@c @end deffn

@c @deffn {Scheme Procedure} make-future thunk
@c @deffnx {C Function} scm_make_future (thunk)
@c Begin evaluating the call @code{(@var{thunk})} in a new thread, and
@c return a ``future'' object representing the calculation.
@c @end deffn

@c @deffn {Scheme Procedure} future-ref f
@c @deffnx {C Function} scm_future_ref (f)
@c Return the value computed by the future @var{f}.  If @var{f} has not
@c yet finished executing then wait for it to do so.
@c @end deffn

@node Parallel Forms
@subsection Parallel forms
@cindex parallel forms

The functions described in this section are available from

@example
(use-modules (ice-9 threads))
@end example

@deffn syntax parallel expr1 @dots{} exprN
Evaluate each @var{expr} expression in parallel, each in its own thread.
Return the results as a set of @var{N} multiple values
(@pxref{Multiple Values}).
@end deffn

@deffn syntax letpar ((var1 expr1) @dots{} (varN exprN)) body@dots{}
Evaluate each @var{expr} in parallel, each in its own thread, then bind
the results to the corresponding @var{var} variables and evaluate
@var{body}.

@code{letpar} is like @code{let} (@pxref{Local Bindings}), but all the
expressions for the bindings are evaluated in parallel.
@end deffn

@deffn {Scheme Procedure} par-map proc lst1 @dots{} lstN
@deffnx {Scheme Procedure} par-for-each proc lst1 @dots{} lstN
Call @var{proc} on the elements of the given lists.  @code{par-map}
returns a list comprising the return values from @var{proc}.
@code{par-for-each} returns an unspecified value, but waits for all
calls to complete.

The @var{proc} calls are @code{(@var{proc} @var{elem1} @dots{}
@var{elemN})}, where each @var{elem} is from the corresponding
@var{lst}.  Each @var{lst} must be the same length.  The calls are
made in parallel, each in its own thread.

These functions are like @code{map} and @code{for-each} (@pxref{List
Mapping}), but make their @var{proc} calls in parallel.
@end deffn

@deffn {Scheme Procedure} n-par-map n proc lst1 @dots{} lstN
@deffnx {Scheme Procedure} n-par-for-each n proc lst1 @dots{} lstN
Call @var{proc} on the elements of the given lists, in the same way as
@code{par-map} and @code{par-for-each} above, but use no more than
@var{n} threads at any one time.  The order in which calls are
initiated within that threads limit is unspecified.

These functions are good for controlling resource consumption if
@var{proc} calls might be costly, or if there are many to be made.  On
a dual-CPU system for instance @math{@var{n}=4} might be enough to
keep the CPUs utilized, and not consume too much memory.
@end deffn

@deffn {Scheme Procedure} n-for-each-par-map n sproc pproc lst1 @dots{} lstN
Apply @var{pproc} to the elements of the given lists, and apply
@var{sproc} to each result returned by @var{pproc}.  The final return
value is unspecified, but all calls will have been completed before
returning.

The calls made are @code{(@var{sproc} (@var{pproc} @var{elem1} @dots{}
@var{elemN}))}, where each @var{elem} is from the corresponding
@var{lst}.  Each @var{lst} must have the same number of elements.

The @var{pproc} calls are made in parallel, in separate threads.  No more
than @var{n} threads are used at any one time.  The order in which
@var{pproc} calls are initiated within that limit is unspecified.

The @var{sproc} calls are made serially, in list element order, one at
a time.  @var{pproc} calls on later elements may execute in parallel
with the @var{sproc} calls.  Exactly which thread makes each
@var{sproc} call is unspecified.

This function is designed for individual calculations that can be done
in parallel, but with results needing to be handled serially, for
instance to write them to a file.  The @var{n} limit on threads
controls system resource usage when there are many calculations or
when they might be costly.

It will be seen that @code{n-for-each-par-map} is like a combination
of @code{n-par-map} and @code{for-each},

@example
(for-each sproc (n-par-map n pproc lst1 ... lstN))
@end example

@noindent
But the actual implementation is more efficient since each @var{sproc}
call, in turn, can be initiated once the relevant @var{pproc} call has
completed, it doesn't need to wait for all to finish.
@end deffn

@c Local Variables:
@c TeX-master: "guile.texi"
@c End:

license: unknown


code:
@c -*-texinfo-*-
@c This is part of the GNU Guile Reference Manual.
@c Copyright (C)  1996, 1997, 2000, 2001, 2002, 2003, 2004
@c   Free Software Foundation, Inc.
@c See the file guile.texi for copying conditions.

@node The SCM Type
@section The SCM Type

Guile represents all Scheme values with the single C type @code{SCM}.
For an introduction to this topic, @xref{Dynamic Types}.

@deftp {C Type} SCM
@code{SCM} is the user level abstract C type that is used to represent
all of Guile's Scheme objects, no matter what the Scheme object type is.
No C operation except assignment is guaranteed to work with variables of
type @code{SCM}, so you should only use macros and functions to work
with @code{SCM} values.  Values are converted between C data types and
the @code{SCM} type with utility functions and macros.
@end deftp
@cindex SCM data type

@deftp {C Type} scm_t_bits
@code{scm_t_bits} is an unsigned integral data type that is guaranteed
to be large enough to hold all information that is required to
represent any Scheme object.  While this data type is mostly used to
implement Guile's internals, the use of this type is also necessary to
write certain kinds of extensions to Guile.
@end deftp

@deftp {C Type} scm_t_signed_bits
This is a signed integral type of the same size as @code{scm_t_bits}.
@end deftp

@deftypefn {C Macro} scm_t_bits SCM_UNPACK (SCM @var{x})
Transforms the @code{SCM} value @var{x} into its representation as an
integral type.  Only after applying @code{SCM_UNPACK} it is possible to
access the bits and contents of the @code{SCM} value.
@end deftypefn

@deftypefn {C Macro} SCM SCM_PACK (scm_t_bits @var{x})
Takes a valid integral representation of a Scheme object and transforms
it into its representation as a @code{SCM} value.
@end deftypefn


code:
@c -*-texinfo-*-
@c This is part of the GNU Guile Reference Manual.
@c Copyright (C)  1996, 1997, 2000, 2001, 2002, 2003, 2004
@c   Free Software Foundation, Inc.
@c See the file guile.texi for copying conditions.

@page
@node Smobs
@section Smobs

This chapter contains reference information related to defining and
working with smobs.  See @ref{Defining New Types (Smobs)} for a
tutorial-like introduction to smobs.

@deftypefun scm_t_bits scm_make_smob_type (const char *name, size_t size)
This function adds a new smob type, named @var{name}, with instance size
@var{size}, to the system.  The return value is a tag that is used in
creating instances of the type.

If @var{size} is 0, the default @emph{free} function will do nothing.

If @var{size} is not 0, the default @emph{free} function will
deallocate the memory block pointed to by @code{SCM_SMOB_DATA} with
@code{scm_gc_free}.  The @var{WHAT} parameter in the call to
@code{scm_gc_free} will be @var{NAME}.

Default values are provided for the @emph{mark}, @emph{free},
@emph{print}, and @emph{equalp} functions, as described in
@ref{Defining New Types (Smobs)}.  If you want to customize any of
these functions, the call to @code{scm_make_smob_type} should be
immediately followed by calls to one or several of
@code{scm_set_smob_mark}, @code{scm_set_smob_free},
@code{scm_set_smob_print}, and/or @code{scm_set_smob_equalp}.
@end deftypefun

@deftypefn {C Function} void scm_set_smob_mark (scm_t_bits tc, SCM (*mark) (SCM obj))
This function sets the smob marking procedure for the smob type specified by
the tag @var{tc}. @var{tc} is the tag returned by @code{scm_make_smob_type}.

The @var{mark} procedure must cause @code{scm_gc_mark} to be called
for every @code{SCM} value that is directly referenced by the smob
instance @var{obj}.  One of these @code{SCM} values can be returned
from the procedure and Guile will call @code{scm_gc_mark} for it.
This can be used to avoid deep recursions for smob instances that form
a list.

It must not call any libguile function or macro except
@code{scm_gc_mark}, @code{SCM_SMOB_FLAGS}, @code{SCM_SMOB_DATA},
@code{SCM_SMOB_DATA_2}, and @code{SCM_SMOB_DATA_3}.
@end deftypefn

@deftypefn {C Function} void scm_set_smob_free (scm_t_bits tc, size_t (*free) (SCM obj))
This function sets the smob freeing procedure for the smob type
specified by the tag @var{tc}. @var{tc} is the tag returned by
@code{scm_make_smob_type}.

The @var{free} procedure must deallocate all resources that are
directly associated with the smob instance @var{OBJ}.  It must assume
that all @code{SCM} values that it references have already been freed
and are thus invalid.

It must also not call any libguile function or macro except
@code{scm_gc_free}, @code{SCM_SMOB_FLAGS}, @code{SCM_SMOB_DATA},
@code{SCM_SMOB_DATA_2}, and @code{SCM_SMOB_DATA_3}.

The @var{free} procedure must return 0.
@end deftypefn

@deftypefn {C Function} void scm_set_smob_print (scm_t_bits tc, int (*print) (SCM obj, SCM port, scm_print_state* pstate))
This function sets the smob printing procedure for the smob type
specified by the tag @var{tc}. @var{tc} is the tag returned by
@code{scm_make_smob_type}.

The @var{print} procedure should output a textual representation of
the smob instance @var{obj} to @var{port}, using information in
@var{pstate}.

The textual representation should be of the form @code{#<name ...>}.
This ensures that @code{read} will not interpret it as some other
Scheme value.

It is often best to ignore @var{pstate} and just print to @var{port}
with @code{scm_display}, @code{scm_write}, @code{scm_simple_format},
and @code{scm_puts}.
@end deftypefn

@deftypefn {C Function} void scm_set_smob_equalp (scm_t_bits tc, SCM (*equalp) (SCM obj1, SCM obj1))
This function sets the smob equality-testing predicate for the smob
type specified by the tag @var{tc}. @var{tc} is the tag returned by
@code{scm_make_smob_type}.

The @var{equalp} procedure should return @code{SCM_BOOL_T} when
@var{obj1} is @code{equal?} to @var{obj2}.  Else it should return
@var{SCM_BOOL_F}.  Both @var{obj1} and @var{obj2} are instances of the
smob type @var{tc}.
@end deftypefn

@deftypefn {C Function} void scm_assert_smob_type (scm_t_bits tag, SCM val)
When @var{val} is a smob of the type indicated by @var{tag}, do nothing.
Else, signal an error.
@end deftypefn

@deftypefn {C Macro} int SCM_SMOB_PREDICATE (scm_t_bits tag, SCM exp)
Return true iff @var{exp} is a smob instance of the type indicated by
@var{tag}.  The expression @var{exp} can be evaluated more than once,
so it shouldn't contain any side effects.
@end deftypefn

@deftypefn {C Macro} void SCM_NEWSMOB (SCM value, scm_t_bits tag, void *data)
@deftypefnx {C Macro} void SCM_NEWSMOB2 (SCM value, scm_t_bits tag, void *data, void *data2)
@deftypefnx {C Macro} void SCM_NEWSMOB3 (SCM value, scm_t_bits tag, void *data, void *data2, void *data3)
Make @var{value} contain a smob instance of the type with tag
@var{tag} and smob data @var{data}, @var{data2}, and @var{data3}, as
appropriate.

The @var{tag} is what has been returned by @code{scm_make_smob_type}.
The initial values @var{data}, @var{data2}, and @var{data3} are of
type @code{scm_t_bits}; when you want to use them for @code{SCM}
values, these values need to be converted to a @code{scm_t_bits} first
by using @code{SCM_UNPACK}.

The flags of the smob instance start out as zero.
@end deftypefn

Since it is often the case (e.g., in smob constructors) that you will
create a smob instance and return it, there is also a slightly specialized
macro for this situation:

@deftypefn {C Macro} {} SCM_RETURN_NEWSMOB (scm_t_bits tag, void *data)
@deftypefnx {C Macro} {} SCM_RETURN_NEWSMOB2 (scm_t_bits tag, void *data1, void *data2)
@deftypefnx {C Macro} {} SCM_RETURN_NEWSMOB3 (scm_t_bits tag, void *data1, void *data2, void *data3)
This macro expands to a block of code that creates a smob instance of
the type with tag @var{tag} and smob data @var{data}, @var{data2}, and
@var{data3}, as with @code{SCM_NEWSMOB}, etc., and causes the
surrounding function to return that @code{SCM} value.  It should be
the last piece of code in a block.
@end deftypefn

@deftypefn {C Macro} scm_t_bits SCM_SMOB_FLAGS (SCM obj)
Return the 16 extra bits of the smob @var{obj}.  No meaning is
predefined for these bits, you can use them freely.
@end deftypefn

@deftypefn {C Macro} scm_t_bits SCM_SET_SMOB_FLAGS (SCM obj, scm_t_bits flags)
Set the 16 extra bits of the smob @var{obj} to @var{flags}.  No
meaning is predefined for these bits, you can use them freely.
@end deftypefn

@deftypefn {C Macro} scm_t_bits SCM_SMOB_DATA (SCM obj)
@deftypefnx {C Macro} scm_t_bits SCM_SMOB_DATA_2 (SCM obj)
@deftypefnx {C Macro} scm_t_bits SCM_SMOB_DATA_3 (SCM obj)
Return the first (second, third) immediate word of the smob @var{obj}
as a @code{scm_t_bits} value.  When the word contains a @code{SCM}
value, use @code{SCM_SMOB_OBJECT} (etc.) instead.
@end deftypefn

@deftypefn {C Macro} void SCM_SET_SMOB_DATA (SCM obj, scm_t_bits val)
@deftypefnx {C Macro} void SCM_SET_SMOB_DATA_2 (SCM obj, scm_t_bits val)
@deftypefnx {C Macro} void SCM_SET_SMOB_DATA_3 (SCM obj, scm_t_bits val)
Set the first (second, third) immediate word of the smob @var{obj} to
@var{val}.  When the word should be set to a @code{SCM} value, use
@code{SCM_SMOB_SET_OBJECT} (etc.) instead.
@end deftypefn

@deftypefn {C Macro} SCM SCM_SMOB_OBJECT (SCM obj)
@deftypefnx {C Macro} SCM SCM_SMOB_OBJECT_2 (SCM obj)
@deftypefnx {C Macro} SCM SCM_SMOB_OBJECT_3 (SCM obj)
Return the first (second, third) immediate word of the smob @var{obj}
as a @code{SCM} value.  When the word contains a @code{scm_t_bits}
value, use @code{SCM_SMOB_DATA} (etc.) instead.
@end deftypefn

@deftypefn {C Macro} void SCM_SET_SMOB_OBJECT (SCM obj, SCM val)
@deftypefnx {C Macro} void SCM_SET_SMOB_OBJECT_2 (SCM obj, SCM val)
@deftypefnx {C Macro} void SCM_SET_SMOB_OBJECT_3 (SCM obj, SCM val)
Set the first (second, third) immediate word of the smob @var{obj} to
@var{val}.  When the word should be set to a @code{scm_t_bits} value, use
@code{SCM_SMOB_SET_DATA} (etc.) instead.
@end deftypefn

@deftypefn {C Macro} {SCM *} SCM_SMOB_OBJECT_LOC (SCM obj)
@deftypefnx {C Macro} {SCM *} SCM_SMOB_OBJECT_2_LOC (SCM obj)
@deftypefnx {C Macro} {SCM *} SCM_SMOB_OBJECT_3_LOC (SCM obj)
Return a pointer to the first (second, third) immediate word of the
smob @var{obj}.  Note that this is a pointer to @code{SCM}.  If you
need to work with @code{scm_t_bits} values, use @code{SCM_PACK} and
@code{SCM_UNPACK}, as appropriate.
@end deftypefn

@deftypefun SCM scm_markcdr (SCM @var{x})
Mark the references in the smob @var{x}, assuming that @var{x}'s first
data word contains an ordinary Scheme object, and @var{x} refers to no
other objects.  This function simply returns @var{x}'s first data word.
@end deftypefun

@c Local Variables:
@c TeX-master: "guile.texi"
@c End:


code:
@c -*-texinfo-*-
@c This is part of the GNU Guile Reference Manual.
@c Copyright (C)  1996, 1997, 2000, 2001, 2002, 2003, 2004
@c   Free Software Foundation, Inc.
@c See the file guile.texi for copying conditions.

@node Snarfing Macros
@section Snarfing Macros
@cindex guile-snarf recognized macros
@cindex guile-snarf deprecated macros

The following macros do two different things: when compiled normally,
they expand in one way; when processed during snarfing, they cause the
@code{guile-snarf} program to pick up some initialization code,
@xref{Function Snarfing}.

The descriptions below use the term `normally' to refer to the case
when the code is compiled normally, and `while snarfing' when the code
is processed by @code{guile-snarf}.

@deffn {C Macro} SCM_SNARF_INIT (code)

Normally, @code{SCM_SNARF_INIT} expands to nothing; while snarfing, it
causes @var{code} to be included in the initialization action file,
followed by a semicolon.

This is the fundamental macro for snarfing initialization actions.
The more specialized macros below use it internally.
@end deffn

@deffn {C Macro} SCM_DEFINE (c_name, scheme_name, req, opt, var, arglist, docstring)

Normally, this macro expands into

@smallexample
static const char s_@var{c_name}[] = @var{scheme_name};
SCM
@var{c_name} @var{arglist}
@end smallexample

While snarfing, it causes

@smallexample
scm_c_define_gsubr (s_@var{c_name}, @var{req}, @var{opt}, @var{var},
                    @var{c_name});
@end smallexample

to be added to the initialization actions.  Thus, you can use it to
declare a C function named @var{c_name} that will be made available to
Scheme with the name @var{scheme_name}.

Note that the @var{arglist} argument must have parentheses around it.
@end deffn

@deffn {C Macro} SCM_SYMBOL (c_name, scheme_name)
@deffnx {C Macro} SCM_GLOBAL_SYMBOL (c_name, scheme_name)
Normally, these macros expand into

@smallexample
static SCM @var{c_name}
@end smallexample

or

@smallexample
SCM @var{c_name}
@end smallexample

respectively.  While snarfing, they both expand into the
initialization code

@smallexample
@var{c_name} = scm_permanent_object (scm_from_locale_symbol (@var{scheme_name}));
@end smallexample

Thus, you can use them declare a static or global variable of type
@code{SCM} that will be initialized to the symbol named
@var{scheme_name}.
@end deffn

@deffn {C Macro} SCM_KEYWORD (c_name, scheme_name)
@deffnx {C Macro} SCM_GLOBAL_KEYWORD (c_name, scheme_name)
Normally, these macros expand into

@smallexample
static SCM @var{c_name}
@end smallexample

or

@smallexample
SCM @var{c_name}
@end smallexample

respectively.  While snarfing, they both expand into the
initialization code

@smallexample
@var{c_name} = scm_permanent_object (scm_c_make_keyword (@var{scheme_name}));
@end smallexample

Thus, you can use them declare a static or global variable of type
@code{SCM} that will be initialized to the keyword named
@var{scheme_name}.
@end deffn

@deffn {C Macro} SCM_VARIABLE (c_name, scheme_name)
@deffnx {C Macro} SCM_GLOBAL_VARIABLE (c_name, scheme_name)
These macros are equivalent to @code{SCM_VARIABLE_INIT} and
@code{SCM_GLOBAL_VARIABLE_INIT}, respectively, with a @var{value} of
@code{SCM_BOOL_F}.
@end deffn

@deffn {C Macro} SCM_VARIABLE_INIT (c_name, scheme_name, value)
@deffnx {C Macro} SCM_GLOBAL_VARIABLE_INIT (c_name, scheme_name, value)

Normally, these macros expand into

@smallexample
static SCM @var{c_name}
@end smallexample

or

@smallexample
SCM @var{c_name}
@end smallexample

respectively.  While snarfing, they both expand into the
initialization code

@smallexample
@var{c_name} = scm_permanent_object (scm_c_define (@var{scheme_name}, @var{value}));
@end smallexample

Thus, you can use them declare a static or global C variable of type
@code{SCM} that will be initialized to the object representing the
Scheme variable named @var{scheme_name} in the current module.  The
variable will be defined when it doesn't already exist.  It is always
set to @var{value}.
@end deffn


code:
@c -*-texinfo-*-
@c This is part of the GNU Guile Reference Manual.
@c Copyright (C)  1996, 1997, 2000, 2001, 2002, 2003, 2004
@c   Free Software Foundation, Inc.
@c See the file guile.texi for copying conditions.

@page
@node Translation
@section Support for Translating Other Languages

[Describe translation framework.]

@menu
* Emacs Lisp Support::          Helper primitives for Emacs Lisp.
@end menu

@node Emacs Lisp Support
@subsection Emacs Lisp Support

@deffn {Scheme Procedure} nil-car x
@deffnx {C Function} scm_nil_car (x)
Return the car of @var{x}, but convert it to LISP nil if it
is Scheme's end-of-list.
@end deffn

@deffn {Scheme Procedure} nil-cdr x
@deffnx {C Function} scm_nil_cdr (x)
Return the cdr of @var{x}, but convert it to LISP nil if it
is Scheme's end-of-list.
@end deffn

@deffn {Scheme Procedure} nil-cons x y
@deffnx {C Function} scm_nil_cons (x, y)
Create a new cons cell with @var{x} as the car and @var{y} as
the cdr, but convert @var{y} to Scheme's end-of-list if it is
a Lisp nil.
@end deffn

@deffn {Scheme Procedure} nil-eq x y
Compare @var{x} and @var{y} and return Lisp's t if they are
@code{eq?}, return Lisp's nil otherwise.
@end deffn

@deffn {Scheme Procedure} null x
@deffnx {C Function} scm_null (x)
Return Lisp's @code{t} if @var{x} is nil in the LISP sense,
return Lisp's nil otherwise.
@end deffn

@c Local Variables:
@c TeX-master: "guile.texi"
@c End: