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

@node Options and Config
@section Configuration, Features and Runtime Options

Why is my Guile different from your Guile?  There are three kinds of
possible variation:

@itemize @bullet
@item
build differences --- different versions of the Guile source code,
installation directories, configuration flags that control pieces of
functionality being included or left out, etc.

@item
differences in dynamically loaded code --- behaviour and features
provided by modules that can be dynamically loaded into a running Guile

@item
different runtime options --- some of the options that are provided for
controlling Guile's behaviour may be set differently.
@end itemize

Guile provides ``introspective'' variables and procedures to query all
of these possible variations at runtime.  For runtime options, it also
provides procedures to change the settings of options and to obtain
documentation on what the options mean.

@menu
* Build Config::                Build and installation configuration.
* Feature Tracking::            Available features in the Guile process.
* Runtime Options::             Controlling Guile's runtime behaviour.
@end menu

@node Build Config
@subsection Configuration, Build and Installation

The following procedures and variables provide information about how
Guile was configured, built and installed on your system.

@deffn {Scheme Procedure} version
@deffnx {Scheme Procedure} effective-version
@deffnx {Scheme Procedure} major-version
@deffnx {Scheme Procedure} minor-version
@deffnx {Scheme Procedure} micro-version
@deffnx {C Function} scm_version ()
@deffnx {C Function} scm_effective_version ()
@deffnx {C Function} scm_major_version ()
@deffnx {C Function} scm_minor_version ()
@deffnx {C Function} scm_micro_version ()
Return a string describing Guile's full version number, effective
version number, major, minor or micro version number, respectively.
The @code{effective-version} function returns the version name that
should remain unchanged during a stable series.  Currently that means
that it omits the micro version.  The effective version should be used
for items like the versioned share directory name
i.e. @file{/usr/share/guile/1.6/}

@lisp
(version) @result{} "1.6.0"
(effective-version) @result{} "1.6"
(major-version) @result{} "1"
(minor-version) @result{} "6"
(micro-version) @result{} "0"
@end lisp
@end deffn

@deffn {Scheme Procedure} %package-data-dir
@deffnx {C Function} scm_sys_package_data_dir ()
Return the name of the directory under which Guile Scheme files in
general are stored.  On Unix-like systems, this is usually
@file{/usr/local/share/guile} or @file{/usr/share/guile}.
@end deffn

@deffn {Scheme Procedure} %library-dir
@deffnx {C Function} scm_sys_library_dir ()
Return the name of the directory where the Guile Scheme files that
belong to the core Guile installation (as opposed to files from a 3rd
party package) are installed.  On Unix-like systems this is usually
@file{/usr/local/share/guile/<GUILE_EFFECTIVE_VERSION>} or
@file{/usr/share/guile/<GUILE_EFFECTIVE_VERSION>};

@noindent for example @file{/usr/local/share/guile/1.6}.
@end deffn

@deffn {Scheme Procedure} %site-dir
@deffnx {C Function} scm_sys_site_dir ()
Return the name of the directory where Guile Scheme files specific to
your site should be installed.  On Unix-like systems, this is usually
@file{/usr/local/share/guile/site} or @file{/usr/share/guile/site}.
@end deffn

@cindex GUILE_LOAD_PATH
@defvar %load-path
List of directories which should be searched for Scheme modules and
libraries.  @code{%load-path} is initialized when Guile starts up to
@code{(list (%site-dir) (%library-dir) (%package-data-dir))},
prepended with the contents of the GUILE_LOAD_PATH environment variable,
if it is set.
@end defvar

@deffn {Scheme Procedure} parse-path path [tail]
@deffnx {C Function} scm_parse_path (path, tail)
Parse @var{path}, which is expected to be a colon-separated
string, into a list and return the resulting list with
@var{tail} appended. If @var{path} is @code{#f}, @var{tail}
is returned.
@end deffn

@deffn {Scheme Procedure} search-path path filename [extensions [require-exts?]]
@deffnx {C Function} scm_search_path (path, filename, rest)
Search @var{path} for a directory containing a file named
@var{filename}. The file must be readable, and not a directory.
If we find one, return its full filename; otherwise, return
@code{#f}.  If @var{filename} is absolute, return it unchanged.
If given, @var{extensions} is a list of strings; for each
directory in @var{path}, we search for @var{filename}
concatenated with each @var{extension}.  If @var{require-exts?}
is true, require that the returned file name have one of the
given extensions; if @var{require-exts?} is not given, it
defaults to @code{#f}.

For compatibility with Guile 1.8 and earlier, the C function takes only
three arguments
@end deffn

@defvar %guile-build-info
Alist of information collected during the building of a particular
Guile.  Entries can be grouped into one of several categories:
directories, env vars, and versioning info.

Briefly, here are the keys in @code{%guile-build-info}, by group:

@cindex @code{srcdir}
@cindex @code{top_srcdir}
@cindex @code{prefix}
@cindex @code{exec_prefix}
@cindex @code{bindir}
@cindex @code{sbindir}
@cindex @code{libexecdir}
@cindex @code{datadir}
@cindex @code{sysconfdir}
@cindex @code{sharedstatedir}
@cindex @code{localstatedir}
@cindex @code{libdir}
@cindex @code{infodir}
@cindex @code{mandir}
@cindex @code{includedir}
@cindex @code{pkgdatadir}
@cindex @code{pkglibdir}
@cindex @code{pkgincludedir}
@table @asis
@item   directories
srcdir, top_srcdir, prefix, exec_prefix, bindir, sbindir, libexecdir,
datadir, sysconfdir, sharedstatedir, localstatedir, libdir, infodir,
mandir, includedir, pkgdatadir, pkglibdir, pkgincludedir
@cindex @code{LIBS}
@item   env vars
LIBS
@cindex @code{guileversion}
@cindex @code{libguileinterface}
@cindex @code{buildstamp}
@item   versioning info
guileversion, libguileinterface, buildstamp
@end table

Values are all strings.  The value for @code{LIBS} is typically found
also as a part of "guile-config link" output.  The value for
@code{guileversion} has form X.Y.Z, and should be the same as returned
by @code{(version)}.  The value for @code{libguileinterface} is
libtool compatible and has form CURRENT:REVISION:AGE
(@pxref{Versioning,, Library interface versions, libtool, GNU
Libtool}).  The value for @code{buildstamp} is the output of the
command @samp{date -u +'%Y-%m-%d %T'} (UTC).

In the source, @code{%guile-build-info} is initialized from
libguile/libpath.h, which is completely generated, so deleting this file
before a build guarantees up-to-date values for that build.
@end defvar

@cindex GNU triplet
@cindex canonical host type

@defvar %host-type
The canonical host type (GNU triplet) of the host Guile was configured
for, e.g., @code{"x86_64-unknown-linux-gnu"} (@pxref{Canonicalizing,,,
autoconf, The GNU Autoconf Manual}).
@end defvar

@node Feature Tracking
@subsection Feature Tracking

Guile has a Scheme level variable @code{*features*} that keeps track to
some extent of the features that are available in a running Guile.
@code{*features*} is a list of symbols, for example @code{threads}, each
of which describes a feature of the running Guile process.

@defvar *features*
A list of symbols describing available features of the Guile process.
@end defvar

You shouldn't modify the @code{*features*} variable directly using
@code{set!}.  Instead, see the procedures that are provided for this
purpose in the following subsection.

@menu
* Feature Manipulation::        Checking for and advertising features.
* Common Feature Symbols::      Commonly available features.
@end menu

@node Feature Manipulation
@subsubsection Feature Manipulation

To check whether a particular feature is available, use the
@code{provided?} procedure:

@deffn {Scheme Procedure} provided? feature
@deffnx {Deprecated Scheme Procedure} feature? feature
Return @code{#t} if the specified @var{feature} is available, otherwise
@code{#f}.
@end deffn

To advertise a feature from your own Scheme code, you can use the
@code{provide} procedure:

@deffn {Scheme Procedure} provide feature
Add @var{feature} to the list of available features in this Guile
process.
@end deffn

For C code, the equivalent function takes its feature name as a
@code{char *} argument for convenience:

@deftypefn {C Function} void scm_add_feature (const char *str)
Add a symbol with name @var{str} to the list of available features in
this Guile process.
@end deftypefn

@node Common Feature Symbols
@subsubsection Common Feature Symbols

In general, a particular feature may be available for one of two
reasons.  Either because the Guile library was configured and compiled
with that feature enabled --- i.e. the feature is built into the library
on your system.  Or because some C or Scheme code that was dynamically
loaded by Guile has added that feature to the list.

In the first category, here are the features that the current version of
Guile may define (depending on how it is built), and what they mean.

@table @code
@item array
Indicates support for arrays (@pxref{Arrays}).

@item array-for-each
Indicates availability of @code{array-for-each} and other array mapping
procedures (@pxref{Arrays}).

@item char-ready?
Indicates that the @code{char-ready?} function is available
(@pxref{Reading}).

@item complex
Indicates support for complex numbers.

@item current-time
Indicates availability of time-related functions: @code{times},
@code{get-internal-run-time} and so on (@pxref{Time}).

@item debug-extensions
Indicates that the debugging evaluator is available, together with the
options for controlling it.

@item delay
Indicates support for promises (@pxref{Delayed Evaluation}).

@item EIDs
Indicates that the @code{geteuid} and @code{getegid} really return
effective user and group IDs (@pxref{Processes}).

@item inexact
Indicates support for inexact numbers.

@item i/o-extensions
Indicates availability of the following extended I/O procedures:
@code{ftell}, @code{redirect-port}, @code{dup->fdes}, @code{dup2},
@code{fileno}, @code{isatty?}, @code{fdopen},
@code{primitive-move->fdes} and @code{fdes->ports} (@pxref{Ports and
File Descriptors}).

@item net-db
Indicates availability of network database functions:
@code{scm_gethost}, @code{scm_getnet}, @code{scm_getproto},
@code{scm_getserv}, @code{scm_sethost}, @code{scm_setnet}, @code{scm_setproto},
@code{scm_setserv}, and their `byXXX' variants (@pxref{Network
Databases}).

@item posix
Indicates support for POSIX functions: @code{pipe}, @code{getgroups},
@code{kill}, @code{execl} and so on (@pxref{POSIX}).

@item random
Indicates availability of random number generation functions:
@code{random}, @code{copy-random-state}, @code{random-uniform} and so on
(@pxref{Random}).

@item reckless
Indicates that Guile was built with important checks omitted --- you
should never see this!

@item regex
Indicates support for POSIX regular expressions using
@code{make-regexp}, @code{regexp-exec} and friends (@pxref{Regexp
Functions}).

@item socket
Indicates availability of socket-related functions: @code{socket},
@code{bind}, @code{connect} and so on (@pxref{Network Sockets and
Communication}).

@item sort
Indicates availability of sorting and merging functions
(@pxref{Sorting}).

@item system
Indicates that the @code{system} function is available
(@pxref{Processes}).

@item threads
Indicates support for multithreading (@pxref{Threads}).

@item values
Indicates support for multiple return values using @code{values} and
@code{call-with-values} (@pxref{Multiple Values}).
@end table

Available features in the second category depend, by definition, on what
additional code your Guile process has loaded in.  The following table
lists features that you might encounter for this reason.

@table @code
@item defmacro
Indicates that the @code{defmacro} macro is available (@pxref{Macros}).

@item describe
Indicates that the @code{(oop goops describe)} module has been loaded,
which provides a procedure for describing the contents of GOOPS
instances.

@item readline
Indicates that Guile has loaded in Readline support, for command line
editing (@pxref{Readline Support}).

@item record
Indicates support for record definition using @code{make-record-type}
and friends (@pxref{Records}).
@end table

Although these tables may seem exhaustive, it is probably unwise in
practice to rely on them, as the correspondences between feature symbols
and available procedures/behaviour are not strictly defined.  If you are
writing code that needs to check for the existence of some procedure, it
is probably safer to do so directly using the @code{defined?} procedure
than to test for the corresponding feature using @code{provided?}.

@node Runtime Options
@subsection Runtime Options

Guile's runtime behaviour can be modified by setting options.  For
example, is the language that Guile accepts case sensitive, or should
the debugger automatically show a backtrace on error?

Guile has two levels of interface for managing options: a low-level
control interface, and a user-level interface which allows the enabling
or disabling of options.

Moreover, the options are classified in groups according to whether they
configure @emph{reading}, @emph{printing}, @emph{debugging} or
@emph{evaluating}.

@menu
* Low level options interfaces::
* User level options interfaces::
* Reader options::
* Printing options::
* Debugger options::
* Evaluator options::
* Evaluator trap options::
* Examples of option use::
@end menu

@node Low level options interfaces
@subsubsection Low Level Options Interfaces

@deffn {Scheme Procedure} read-options-interface [setting]
@deffnx {Scheme Procedure} eval-options-interface [setting]
@deffnx {Scheme Procedure} print-options-interface [setting]
@deffnx {Scheme Procedure} debug-options-interface [setting]
@deffnx {Scheme Procedure} evaluator-traps-interface [setting]
@deffnx {C Function} scm_read_options (setting)
@deffnx {C Function} scm_eval_options_interface (setting)
@deffnx {C Function} scm_print_options (setting)
@deffnx {C Function} scm_debug_options (setting)
@deffnx {C Function} scm_evaluator_traps (setting)
If one of these procedures is called with no arguments (or with
@code{setting == SCM_UNDEFINED} in C code), it returns a list describing
the current setting of the read, eval, print, debug or evaluator traps
options respectively.  The setting of a boolean option is indicated
simply by the presence or absence of the option symbol in the list.  The
setting of a non-boolean option is indicated by the presence of the
option symbol immediately followed by the option's current value.

If called with a list argument, these procedures interpret the list as
an option setting and modify the relevant options accordingly.  [FIXME
--- this glosses over a lot of details!]

If called with any other argument, such as @code{'help}, these
procedures return a list of entries like @code{(@var{OPTION-SYMBOL}
@var{DEFAULT-VALUE} @var{DOC-STRING})}, with each entry giving the
default value and documentation for each option symbol in the relevant
set of options.
@end deffn

@node User level options interfaces
@subsubsection User Level Options Interfaces

@c @deftp {Data type} scm_option
@c @code{scm_option} is used to represent run time options.  It can be a
@c @emph{boolean} type, in which case the option will be set by the strings
@c @code{"yes"} and @code{"no"}.  It can be a
@c @end deftp

@c NJFIXME
@deffn {Scheme Procedure} <group>-options [arg]
@deffnx {Scheme Procedure} read-options [arg]
@deffnx {Scheme Procedure} print-options [arg]
@deffnx {Scheme Procedure} debug-options [arg]
@deffnx {Scheme Procedure} traps [arg]
These functions list the options in their group.  The optional argument
@var{arg} is a symbol which modifies the form in which the options are
presented.

With no arguments, @code{<group>-options} returns the values of the
options in that particular group.  If @var{arg} is @code{'help}, a
description of each option is given.  If @var{arg} is @code{'full},
programmers' options are also shown.

@var{arg} can also be a list representing the state of all options.  In
this case, the list contains single symbols (for enabled boolean
options) and symbols followed by values.
@end deffn
[FIXME: I don't think 'full is ever any different from 'help.  What's
up?]

@c NJFIXME
@deffn {Scheme Procedure} <group>-enable option-symbol
@deffnx {Scheme Procedure} read-enable option-symbol
@deffnx {Scheme Procedure} print-enable option-symbol
@deffnx {Scheme Procedure} debug-enable option-symbol
@deffnx {Scheme Procedure} trap-enable option-symbol
These functions set the specified @var{option-symbol} in their options
group.  They only work if the option is boolean, and throw an error
otherwise.
@end deffn

@c NJFIXME
@deffn {Scheme Procedure} <group>-disable option-symbol
@deffnx {Scheme Procedure} read-disable option-symbol
@deffnx {Scheme Procedure} print-disable option-symbol
@deffnx {Scheme Procedure} debug-disable option-symbol
@deffnx {Scheme Procedure} trap-disable option-symbol
These functions turn off the specified @var{option-symbol} in their
options group.  They only work if the option is boolean, and throw an
error otherwise.
@end deffn

@c NJFIXME
@deffn syntax <group>-set! option-symbol value
@deffnx syntax read-set! option-symbol value
@deffnx syntax print-set! option-symbol value
@deffnx syntax debug-set! option-symbol value
@deffnx syntax trap-set! option-symbol value
These functions set a non-boolean @var{option-symbol} to the specified
@var{value}.
@end deffn

@node Reader options
@subsubsection Reader options
@cindex options - read
@cindex read options

Here is the list of reader options generated by typing
@code{(read-options 'full)} in Guile.  You can also see the default
values.

@smalllisp
keywords         #f      Style of keyword recognition: #f, 'prefix or 'postfix
case-insensitive no      Convert symbols to lower case.
positions        yes     Record positions of source code expressions.
copy             no      Copy source code expressions.
r6rs-hex-escapes no      Use R6RS-style string hex escapes
@end smalllisp

Notice that while Standard Scheme is case insensitive, to ease
translation of other Lisp dialects, notably Emacs Lisp, into Guile,
Guile is case-sensitive by default.

To make Guile case insensitive, you can type

@lisp
(read-enable 'case-insensitive)
@end lisp

For more information on the effect of the @code{r6rs-hex-escapes} option, see
(@pxref{String Syntax}).

@node Printing options
@subsubsection Printing options

Here is the list of print options generated by typing
@code{(print-options 'full)} in Guile.  You can also see the default
values.

@smallexample
quote-keywordish-symbols reader How to print symbols that have a colon
                                as their first or last character. The
                                value '#f' does not quote the colons;
                                '#t' quotes them; 'reader' quotes
                                them when the reader option
                                'keywords' is not '#f'.

highlight-prefix         @{      The string to print before highlighted values.
highlight-suffix         @}      The string to print after highlighted values.

source                   no     Print closures with source.
closure-hook             #f     Hook for printing closures.
@end smallexample

@node Evaluator options
@subsubsection Evaluator options

These are the evaluator options with their default values, as they are
printed by typing @code{(eval-options 'full)} in Guile.

@smallexample
stack           22000   Size of thread stacks (in machine words).
@end smallexample

@node Evaluator trap options
@subsubsection Evaluator trap options
[FIXME: These flags, together with their corresponding handlers, are not
user level options.  Probably this entire section should be moved to the
documentation about the low-level programmer debugging interface.]

Here is the list of evaluator trap options generated by typing
@code{(traps 'full)} in Guile.  You can also see the default values.

@smallexample
exit-frame      no      Trap when exiting eval or apply.
apply-frame     no      Trap when entering apply.
enter-frame     no      Trap when eval enters new frame.
memoize-symbol  no      Trap when eval memoizes a symbol's value
traps		yes	Enable evaluator traps.
@end smallexample

@deffn apply-frame-handler key cont tailp
Called when a procedure is being applied.

Called if:

@itemize @bullet
@item
evaluator traps are enabled [traps interface], and
@item
either
@itemize @minus
@item
@code{apply-frame} is enabled [traps interface], or
@item
trace mode is on [debug-options interface], and the procedure being
called has the trace property enabled.
@end itemize
@end itemize

@var{cont} is a ``debug object'', which means that it can be passed to
@code{make-stack} to discover the stack at the point of the trap.  The
apply frame handler's code can capture a restartable continuation if it
wants to by using @code{call-with-current-continuation} in the usual way.

@var{tailp} is true if this is a tail call
@end deffn

@deffn exit-frame-handler key cont retval
Called when a value is returned from a procedure.

Called if:

@itemize @bullet
@item
evaluator traps are enabled [traps interface], and
@item
either
@itemize @minus
@item
 @code{exit-frame} is enabled [traps interface], or
@item
trace mode is on [debug-options interface], and the procedure being
called has the trace property enabled.
@end itemize
@end itemize

@var{cont} is a ``debug object'', which means that it can be passed to
@code{make-stack} to discover the stack at the point of the trap.  The
exit frame handler's code can capture a restartable continuation if it
wants to by using @code{call-with-current-continuation} in the usual
way.

@var{retval} is the return value.
@end deffn

@deffn memoize-symbol-handler key cont expression env
Called when the evaluator memoizes the value of a procedure symbol

@var{cont} is a ``debug object'', which means that it can be passed to
@code{make-stack} to discover the stack at the point of the trap.  The
exit frame handler's code can capture a restartable continuation if it
wants to by using @code{call-with-current-continuation} in the usual
way.

@var{retval} is the return value.
@end deffn

@deffn {Scheme Procedure} with-traps thunk
@deffnx {C Function} scm_with_traps (thunk)
Call @var{thunk} with traps enabled.
@end deffn

@deffn {Scheme Procedure} debug-object? obj
@deffnx {C Function} scm_debug_object_p (obj)
Return @code{#t} if @var{obj} is a debug object.
@end deffn

@node Debugger options
@subsubsection Debugger options

Here is the list of print options generated by typing
@code{(debug-options 'full)} in Guile.  You can also see the default
values.

@smallexample
stack           20000   Stack size limit (0 = no check).
debug           yes     Use the debugging evaluator.
backtrace       no      Show backtrace on error.
depth           20      Maximal length of printed backtrace.
maxdepth        1000    Maximal number of stored backtrace frames.
frames          3       Maximum number of tail-recursive frames in backtrace.
indent          10      Maximal indentation in backtrace.
backwards       no      Display backtrace in anti-chronological order.
procnames       yes     Record procedure names at definition.
trace           no      *Trace mode.
breakpoints     no      *Check for breakpoints.
cheap           yes     *This option is now obsolete.  Setting it has no effect.
@end smallexample

@subsubheading Stack overflow

@cindex overflow, stack
@cindex stack overflow
Stack overflow errors are caused by a computation trying to use more
stack space than has been enabled by the @code{stack} option.  They are
reported like this:

@lisp
(non-tail-recursive-factorial 500)
@print{}
ERROR: Stack overflow
ABORT: (stack-overflow)
@end lisp

If you get an error like this, you can either try rewriting your code to
use less stack space, or increase the maximum stack size.  To increase
the maximum stack size, use @code{debug-set!}, for example:

@lisp
(debug-set! stack 200000)
@result{}
(show-file-name #t stack 200000 debug backtrace depth 20
   maxdepth 1000 frames 3 indent 10 width 79 procnames cheap)

(non-tail-recursive-factorial 500)
@result{}
122013682599111006870123878542304692625357434@dots{}
@end lisp

If you prefer to try rewriting your code, you may be able to save stack
space by making some of your procedures @dfn{tail recursive}
(@pxref{Tail Calls}).

@node Examples of option use
@subsubsection Examples of option use

Here is an example of a session in which some read and debug option
handling procedures are used.  In this example, the user

@enumerate
@item
Notices that the symbols @code{abc} and @code{aBc} are not the same
@item
Examines the @code{read-options}, and sees that @code{case-insensitive}
is set to ``no''.
@item
Enables @code{case-insensitive}
@item
Verifies that now @code{aBc} and @code{abc} are the same
@item
Disables @code{case-insensitive} and enables debugging @code{backtrace}
@item
Reproduces the error of displaying @code{aBc} with backtracing enabled
[FIXME: this last example is lame because there is no depth in the
backtrace.  Need to give a better example, possibly putting debugging
option examples in a separate session.]
@end enumerate

@smalllisp
guile> (define abc "hello")
guile> abc
"hello"
guile> aBc
ERROR: In expression aBc:
ERROR: Unbound variable: aBc
ABORT: (misc-error)

Type "(backtrace)" to get more information.
guile> (read-options 'help)
keywords	#f	Style of keyword recognition: #f, 'prefix or 'postfix
case-insensitive	no	Convert symbols to lower case.
positions	yes	Record positions of source code expressions.
copy		no	Copy source code expressions.
guile> (debug-options 'help)
stack		20000	Stack size limit (0 = no check).
debug		yes	Use the debugging evaluator.
backtrace	no	Show backtrace on error.
depth		20	Maximal length of printed backtrace.
maxdepth	1000	Maximal number of stored backtrace frames.
frames		3	Maximum number of tail-recursive frames in backtrace.
indent		10	Maximal indentation in backtrace.
backwards	no	Display backtrace in anti-chronological order.
procnames	yes	Record procedure names at definition.
trace		no	*Trace mode.
breakpoints	no	*Check for breakpoints.
cheap		yes	*This option is now obsolete.  Setting it has no effect.
guile> (read-enable 'case-insensitive)
(keywords #f case-insensitive positions)
guile> aBc
"hello"
guile> (read-disable 'case-insensitive)
(keywords #f positions)
guile> (debug-enable 'backtrace)
(stack 20000 debug backtrace depth 20 maxdepth 1000 frames 3 indent 10 procnames cheap)
guile> aBc

Backtrace:
0* aBc

ERROR: In expression aBc:
ERROR: Unbound variable: aBc
ABORT: (misc-error)
guile>
@end smalllisp

@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 API Overview
@section Overview of the Guile API

Guile's application programming interface (@dfn{API}) makes
functionality available that an application developer can use in either
C or Scheme programming.  The interface consists of @dfn{elements} that
may be macros, functions or variables in C, and procedures, variables,
syntax or other types of object in Scheme.

Many elements are available to both Scheme and C, in a form that is
appropriate.  For example, the @code{assq} Scheme procedure is also
available as @code{scm_assq} to C code.  These elements are documented
only once, addressing both the Scheme and C aspects of them.

The Scheme name of an element is related to its C name in a regular
way.  Also, a C function takes its parameters in a systematic way.

Normally, the name of a C function can be derived given its Scheme name,
using some simple textual transformations:

@itemize @bullet

@item
Replace @code{-} (hyphen) with @code{_} (underscore).

@item
Replace @code{?} (question mark) with @code{_p}.

@item
Replace @code{!} (exclamation point) with @code{_x}.

@item
Replace internal @code{->} with @code{_to_}.

@item
Replace @code{<=} (less than or equal) with @code{_leq}.

@item
Replace @code{>=} (greater than or equal) with @code{_geq}.

@item
Replace @code{<} (less than) with @code{_less}.

@item
Replace @code{>} (greater than) with @code{_gr}.

@item
Prefix with @code{scm_}.

@end itemize

@c Here is an Emacs Lisp command that prompts for a Scheme function name and
@c inserts the corresponding C function name into the buffer.

@c @example
@c (defun insert-scheme-to-C (name &optional use-gh)
@c   "Transforms Scheme NAME, a string, to its C counterpart, and inserts it.
@c Prefix arg non-nil means use \"gh_\" prefix, otherwise use \"scm_\" prefix."
@c   (interactive "sScheme name: \nP")
@c   (let ((transforms '(("-"  . "_")
@c                       ("?"  . "_p")
@c                       ("!"  . "_x")
@c                       ("->" . "_to_")
@c                       ("<=" . "_leq")
@c                       (">=" . "_geq")
@c                       ("<"  . "_less")
@c                       (">"  . "_gr")
@c                       ("@@"  . "at"))))
@c     (while transforms
@c       (let ((trigger (concat "\\(.*\\)"
@c                              (regexp-quote (caar transforms))
@c                              "\\(.*\\)"))
@c             (sub (cdar transforms))
@c             (m nil))
@c         (while (setq m (string-match trigger name))
@c           (setq name (concat (match-string 1 name)
@c                              sub
@c                              (match-string 2 name)))))
@c       (setq transforms (cdr transforms))))
@c   (insert (if use-gh "gh_" "scm_") name))
@c @end example

A C function always takes a fixed number of arguments of type
@code{SCM}, even when the corresponding Scheme function takes a
variable number.

For some Scheme functions, some last arguments are optional; the
corresponding C function must always be invoked with all optional
arguments specified.  To get the effect as if an argument has not been
specified, pass @code{SCM_UNDEFINED} as its value.  You can not do
this for an argument in the middle; when one argument is
@code{SCM_UNDEFINED} all the ones following it must be
@code{SCM_UNDEFINED} as well.

Some Scheme functions take an arbitrary number of @emph{rest}
arguments; the corresponding C function must be invoked with a list of
all these arguments.  This list is always the last argument of the C
function.

These two variants can also be combined.

The type of the return value of a C function that corresponds to a
Scheme function is always @code{SCM}.  In the descriptions below,
types are therefore often omitted bot for the return value and for the
arguments.

license: mit


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

@node Procedures
@section Procedures

@menu
* Lambda::                      Basic procedure creation using lambda.
* Primitive Procedures::        Procedures defined in C.
* Compiled Procedures::         Scheme procedures can be compiled.
* Optional Arguments::          Handling keyword, optional and rest arguments.
* Case-lambda::                 One function, multiple arities.
* Procedure Properties::        Procedure properties and meta-information.
* Procedures with Setters::     Procedures with setters.
@end menu

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

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 evaluated 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}, but may not exceed 10.  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 Compiled Procedures
@subsection Compiled Procedures

In Guile, procedures can be executed by directly interpreting their
source code. Scheme source code is a set of nested lists, after all,
with each list representing a procedure call.

Most procedures are compiled, however. This means that Guile has done
some pre-computation on the procedure, to determine what it will need
to do each time the procedure runs. Compiled procedures run faster
than interpreted procedures.

Loading files is the normal way that compiled procedures come to
being. If Guile sees that a file is uncompiled, or that its compiled
file is out of date, it will attempt to compile the file when it is
loaded, and save the result to disk. Procedures can be compiled at
runtime as well. @xref{Read/Load/Eval/Compile}, for more information
on runtime compilation.

Compiled procedures, also known as @dfn{programs}, respond all
procedures that operate on procedures. In addition, there are a few
more accessors for low-level details on programs.

Most people won't need to use the routines described in this section,
but it's good to have them documented. You'll have to include the
appropriate module first, though:

@example
(use-modules (system vm program))
@end example

@deffn {Scheme Procedure} program? obj
@deffnx {C Function} scm_program_p (obj)
Returns @code{#t} iff @var{obj} is a compiled procedure.
@end deffn

@deffn {Scheme Procedure} program-objcode program
@deffnx {C Function} scm_program_objcode (program)
Returns the object code associated with this program. @xref{Bytecode
and Objcode}, for more information.
@end deffn

@deffn {Scheme Procedure} program-objects program
@deffnx {C Function} scm_program_objects (program)
Returns the ``object table'' associated with this program, as a
vector. @xref{VM Programs}, for more information.
@end deffn

@deffn {Scheme Procedure} program-module program
@deffnx {C Function} scm_program_module (program)
Returns the module that was current when this program was created. Can
return @code{#f} if the compiler could determine that this information
was unnecessary.
@end deffn

@deffn {Scheme Procedure} program-free-variables program
@deffnx {C Function} scm_program_free_variables (program)
Returns the set of free variables that this program captures in its
closure, as a vector. If a closure is code with data, you can get the
code from @code{program-objcode}, and the data via
@code{program-free-variables}.

Some of the values captured are actually in variable ``boxes''.
@xref{Variables and the VM}, for more information.

Users must not modify the returned value unless they think they're
really clever.
@end deffn

@deffn {Scheme Procedure} program-meta program
@deffnx {C Function} scm_program_meta (program)
Return the metadata thunk of @var{program}, or @code{#f} if it has no
metadata.

When called, a metadata thunk returns a list of the following form:
@code{(@var{bindings} @var{sources} @var{arities} . @var{properties})}. The format
of each of these elements is discussed below.
@end deffn

@deffn {Scheme Procedure} program-bindings program
@deffnx {Scheme Procedure} make-binding name boxed? index start end
@deffnx {Scheme Procedure} binding:name binding
@deffnx {Scheme Procedure} binding:boxed? binding
@deffnx {Scheme Procedure} binding:index binding
@deffnx {Scheme Procedure} binding:start binding
@deffnx {Scheme Procedure} binding:end binding
Bindings annotations for programs, along with their accessors.

Bindings declare names and liveness extents for block-local variables.
The best way to see what these are is to play around with them at a
REPL. @xref{VM Concepts}, for more information.

Note that bindings information is stored in a program as part of its
metadata thunk, so including it in the generated object code does not
impose a runtime performance penalty.
@end deffn

@deffn {Scheme Procedure} program-sources program
@deffnx {Scheme Procedure} source:addr source
@deffnx {Scheme Procedure} source:line source
@deffnx {Scheme Procedure} source:column source
@deffnx {Scheme Procedure} source:file source
Source location annotations for programs, along with their accessors.

Source location information propagates through the compiler and ends
up being serialized to the program's metadata. This information is
keyed by the offset of the instruction pointer within the object code
of the program. Specifically, it is keyed on the @code{ip} @emph{just
following} an instruction, so that backtraces can find the source
location of a call that is in progress.
@end deffn

@deffn {Scheme Procedure} program-arities program
@deffnx {C Function} scm_program_arities (program)
@deffnx {Scheme Procedure} program-arity program ip
@deffnx {Scheme Procedure} arity:start arity
@deffnx {Scheme Procedure} arity:end arity
@deffnx {Scheme Procedure} arity:nreq arity
@deffnx {Scheme Procedure} arity:nopt arity
@deffnx {Scheme Procedure} arity:rest? arity
@deffnx {Scheme Procedure} arity:kw arity
@deffnx {Scheme Procedure} arity:allow-other-keys? arity
Accessors for a representation of the ``arity'' of a program.

The normal case is that a procedure has one arity. For example,
@code{(lambda (x) x)}, takes one required argument, and that's it. One
could access that number of required arguments via @code{(arity:nreq
(program-arities (lambda (x) x)))}. Similarly, @code{arity:nopt} gets
the number of optional arguments, and @code{arity:rest?} returns a true
value if the procedure has a rest arg.

@code{arity:kw} returns a list of @code{(@var{kw} . @var{idx})} pairs,
if the procedure has keyword arguments. The @var{idx} refers to the
@var{idx}th local variable; @xref{Variables and the VM}, for more
information. Finally @code{arity:allow-other-keys?} returns a true
value if other keys are allowed. @xref{Optional Arguments}, for more
information.

So what about @code{arity:start} and @code{arity:end}, then? They
return the range of bytes in the program's bytecode for which a given
arity is valid. You see, a procedure can actually have more than one
arity. The question, ``what is a procedure's arity'' only really makes
sense at certain points in the program, delimited by these
@code{arity:start} and @code{arity:end} values.
@end deffn

@node Optional Arguments
@subsection Optional Arguments

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 arguments, but the remaining
(optional) arguments can be only referenced as a list of values
(@pxref{Lambda}).

For this reason, Guile provides an extension to @code{lambda},
@code{lambda*}, which allows the user to define procedures with
optional and keyword arguments. In addition, Guile's virtual machine
has low-level support for optional and keyword argument dispatch.
Calls to procedures with optional and keyword arguments can be made
cheaply, without allocating a rest list.

@menu
* lambda* and define*::         Creating advanced argument handling procedures.
* ice-9 optargs::               (ice-9 optargs) provides some utilities.
@end menu

@node lambda* and define*
@subsubsection lambda* and define*.

@code{lambda*} is like @code{lambda}, except with some extensions to
allow optional and keyword arguments.

@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}.

@fnindex define*
Likewise, @code{define*} is syntactic sugar for defining procedures
using @code{lambda*}.

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

@lisp
(define* (sir-yes-sir #:key action how-high)
  (list action how-high))
@end lisp

can be called as @code{(sir-yes-sir #:action 'jump)},
@code{(sir-yes-sir #:how-high 13)}, @code{(sir-yes-sir #:action
'lay-down #:how-high 0)}, or just @code{(sir-yes-sir)}. 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
(define* (frob 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
(define* (flips #:key (heads 0) (tails 0))
  (display (list heads tails)))

(flips #: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. 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

The exception to this left-to-right scoping rule is the rest argument.
If there is a rest argument, it is bound after the optional arguments,
but before the keyword arguments.
@end deffn

@node ice-9 optargs
@subsubsection (ice-9 optargs)

Before Guile 2.0, @code{lambda*} and @code{define*} were implemented
using macros that processed rest list arguments. This was not optimal,
as calling procedures with optional arguments had to allocate rest
lists at every procedure invocation. Guile 2.0 improved this
situation by bringing optional and keyword arguments into Guile's
core.

However there are occasions in which you have a list and want to parse
it for optional or keyword arguments. Guile's @code{(ice-9 optargs)}
provides some macros to help with that task.

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

Similarly, @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.
@end deffn

@code{(ice-9 optargs)} also provides some more @code{define*} sugar,
which is not so useful with modern Guile coding, but still supported:
@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*-public formals body
Like a mix of @code{define*} and @code{define-public}.
@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 Case-lambda
@subsection Case-lambda
@cindex SRFI-16
@cindex variable arity
@cindex arity, variable

R5RS's rest arguments are indeed useful and very general, but they
often aren't the most appropriate or efficient means to get the job
done. For example, @code{lambda*} is a much better solution to the
optional argument problem than @code{lambda} with rest arguments.

@fnindex case-lambda
Likewise, @code{case-lambda} works well for when you want one
procedure to do double duty (or triple, or ...), without the penalty
of consing a rest list.

For example:

@lisp
(define (make-accum n)
  (case-lambda
    (() n)
    ((m) (set! n (+ n m)) n)))

(define a (make-accum 20))
(a) @result{} 20
(a 10) @result{} 30
(a) @result{} 30
@end lisp

The value returned by a @code{case-lambda} form is a procedure which
matches the number of actual arguments against the formals in the
various clauses, in order. The first matching clause is selected, the
corresponding values from the actual parameter list are bound to the
variable names in the clauses and the body of the clause is evaluated.
If no clause matches, an error is signalled.

The syntax of the @code{case-lambda} form is defined in the following
EBNF grammar. @dfn{Formals} means a formal argument list just like
with @code{lambda} (@pxref{Lambda}).

@example
@group
<case-lambda>
   --> (case-lambda <case-lambda-clause>)
<case-lambda-clause>
   --> (<formals> <definition-or-command>*)
<formals>
   --> (<identifier>*)
     | (<identifier>* . <identifier>)
     | <identifier>
@end group
@end example

Rest lists can be useful with @code{case-lambda}:

@lisp
(define plus
  (case-lambda
    (() 0)
    ((a) a)
    ((a b) (+ a b))
    ((a b . rest) (apply plus (+ a b) rest))))
(plus 1 2 3) @result{} 6
@end lisp

@fnindex case-lambda*
Also, for completeness. Guile defines @code{case-lambda*} as well,
which is like @code{case-lambda}, except with @code{lambda*} clauses.
A @code{case-lambda*} clause matches if the arguments fill the
required arguments, but are not too many for the optional and/or rest
arguments.

Keyword arguments are possible with @code{case-lambda*}, but they do
not contribute to the ``matching'' behavior. That is to say,
@code{case-lambda*} matches only on required, optional, and rest
arguments, and on the predicate; keyword arguments may be present but
do not contribute to the ``success'' of a match. In fact a bad keyword
argument list may cause an error to be raised.

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

In addition to the information that is strictly necessary to run,
procedures may have other associated information. For example, the
name of a procedure is information not for the procedure, but about
the procedure. This meta-information can be accessed via the procedure
properties interface.

The first group of procedures in this meta-interface 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. This category somewhat
misnamed, actually, as it applies only to interpreted procedures, not
compiled procedures. But since it has historically been used more to
select on implementation details than on essence (closure or not), we
keep it here for compatibility. Don't use it in new code, though.
@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

@cindex procedure properties
Procedure properties are general properties associated with
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}. Returns @code{#f} if
the source code is not available.
@end deffn

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

@deffn {Scheme Procedure} procedure-properties proc
@deffnx {C Function} scm_procedure_properties (proc)
Return the properties associated with @var{proc}, as an association
list.
@end deffn

@deffn {Scheme Procedure} procedure-property proc key
@deffnx {C Function} scm_procedure_property (proc, key)
Return the property of @var{proc} 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{proc}'s property list to @var{alist}.
@end deffn

@deffn {Scheme Procedure} set-procedure-property! proc key value
@deffnx {C Function} scm_set_procedure_property_x (proc, key, value)
In @var{proc}'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 an
applicable 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

@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, 2007, 2009
@c   Free Software Foundation, Inc.
@c See the file guile.texi for copying conditions.

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

@menu
* Arbiters::                    Synchronization primitives.
* Asyncs::                      Asynchronous procedure invocation.
* 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)
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 execution 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

@deffn {Scheme Procedure} call-with-blocked-asyncs proc
@deffnx {C Function} scm_call_with_blocked_asyncs (proc)
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

@deftypefn {C Function} {void *} scm_c_call_with_blocked_asyncs (void * (*proc) (void *data), void *data)
The same but with a C function @var{proc} instead of a Scheme thunk.
@end deftypefn

@deffn {Scheme Procedure} call-with-unblocked-asyncs proc
@deffnx {C Function} scm_call_with_unblocked_asyncs (proc)
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_c_call_with_unblocked_asyncs (void *(*proc) (void *data), void *data)
The same but with a C function @var{proc} instead of a Scheme thunk.
@end deftypefn

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

@deftypefn {C Function} void scm_dynwind_unblock_asyncs ()
During the current dynwind context, decrease the blocking of asyncs by
one level.  This function must be used inside a pair of calls to
@code{scm_dynwind_begin} and @code{scm_dynwind_end} (@pxref{Dynamic
Wind}).
@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 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

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

@c begin (texi-doc-string "guile" "join-thread")
@deffn {Scheme Procedure} join-thread thread [timeout [timeoutval]]
@deffnx {C Function} scm_join_thread (thread)
@deffnx {C Function} scm_join_thread_timed (thread, timeout, timeoutval)
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}.  When
@var{timeout} is given, it specifies a point in time where the waiting
should be aborted.  It can be either an integer as returned by
@code{current-time} or a pair as returned by @code{gettimeofday}.
When the waiting is aborted, @var{timeoutval} is returned (if it is
specified; @code{#f} is returned otherwise).
@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

@deffn {Scheme Procedure} cancel-thread thread
@deffnx {C Function} scm_cancel_thread (thread)
Asynchronously notify @var{thread} to exit.  Immediately after
receiving this notification, @var{thread} will call its cleanup handler
(if one has been set) and then terminate, aborting any evaluation that
is in progress.

Because Guile threads are isomorphic with POSIX threads, @var{thread}
will not receive its cancellation signal until it reaches a cancellation
point.  See your operating system's POSIX threading documentation for
more information on cancellation points; note that in Guile, unlike
native POSIX threads, a thread can receive a cancellation notification
while attempting to lock a mutex.
@end deffn

@deffn {Scheme Procedure} set-thread-cleanup! thread proc
@deffnx {C Function} scm_set_thread_cleanup_x (thread, proc)
Set @var{proc} as the cleanup handler for the thread @var{thread}.
@var{proc}, which must be a thunk, will be called when @var{thread}
exits, either normally or by being canceled.  Thread cleanup handlers
can be used to perform useful tasks like releasing resources, such as
locked mutexes, when thread exit cannot be predicted.

The return value of @var{proc} will be set as the @emph{exit value} of
@var{thread}.

To remove a cleanup handler, pass @code{#f} for @var{proc}.
@end deffn

@deffn {Scheme Procedure} thread-cleanup thread
@deffnx {C Function} scm_thread_cleanup (thread)
Return the cleanup handler currently installed for the thread
@var{thread}.  If no cleanup handler is currently installed,
thread-cleanup returns @code{#f}.
@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 . flags
@deffnx {C Function} scm_make_mutex ()
@deffnx {C Function} scm_make_mutex_with_flags (SCM flags)
Return a new mutex.  It is initially unlocked.  If @var{flags} is
specified, it must be a list of symbols specifying configuration flags
for the newly-created mutex.  The supported flags are:
@table @code
@item unchecked-unlock
Unless this flag is present, a call to `unlock-mutex' on the returned
mutex when it is already unlocked will cause an error to be signalled.

@item allow-external-unlock
Allow the returned mutex to be unlocked by the calling thread even if
it was originally locked by a different thread.

@item recursive
The returned mutex will be recursive.

@end table
@end deffn

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

@deffn {Scheme Procedure} make-recursive-mutex
@deffnx {C Function} scm_make_recursive_mutex ()
Create a new recursive mutex.  It is initially unlocked.  Calling this
function is equivalent to calling `make-mutex' and specifying the
@code{recursive} flag.
@end deffn

@deffn {Scheme Procedure} lock-mutex mutex [timeout [owner]]
@deffnx {C Function} scm_lock_mutex (mutex)
@deffnx {C Function} scm_lock_mutex_timed (mutex, timeout, owner)
Lock @var{mutex}.  If the mutex is already locked, then block and
return only when @var{mutex} has been acquired.

When @var{timeout} is given, it specifies a point in time where the
waiting should be aborted.  It can be either an 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 @var{owner} is given, it specifies an owner for @var{mutex} other
than the calling thread.  @var{owner} may also be @code{#f},
indicating that the mutex should be locked but left unowned.

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.

If @var{mutex} was locked by a thread that exited before unlocking it,
the next attempt to lock @var{mutex} will succeed, but
@code{abandoned-mutex-error} will be signalled.

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 [condvar [timeout]]
@deffnx {C Function} scm_unlock_mutex (mutex)
@deffnx {C Function} scm_unlock_mutex_timed (mutex, condvar, timeout)
Unlock @var{mutex}.  An error is signalled if @var{mutex} is not locked
and was not created with the @code{unchecked-unlock} flag set, or if
@var{mutex} is locked by a thread other than the calling thread and was
not created with the @code{allow-external-unlock} flag set.

If @var{condvar} is given, it specifies a condition variable upon
which the calling thread will wait to be signalled before returning.
(This behavior is very similar to that of
@code{wait-condition-variable}, except that the mutex is left in an
unlocked state when the function returns.)

When @var{timeout} is also given, it specifies a point in time where
the waiting should be aborted.  It can be either an integer as
returned by @code{current-time} or a pair as returned by
@code{gettimeofday}.  When the waiting is aborted, @code{#f} is
returned.  Otherwise the function returns @code{#t}.
@end deffn

@deffn {Scheme Procedure} mutex-owner mutex
@deffnx {C Function} scm_mutex_owner (mutex)
Return the current owner of @var{mutex}, in the form of a thread or
@code{#f} (indicating no owner).  Note that a mutex may be unowned but
still locked.
@end deffn

@deffn {Scheme Procedure} mutex-level mutex
@deffnx {C Function} scm_mutex_level (mutex)
Return the current lock level of @var{mutex}.  If @var{mutex} is
currently unlocked, this value will be 0; otherwise, it will be the
number of times @var{mutex} has been recursively locked by its current
owner.
@end deffn

@deffn {Scheme Procedure} mutex-locked? mutex
@deffnx {C Function} scm_mutex_locked_p (mutex)
Return @code{#t} if @var{mutex} is locked, regardless of ownership;
otherwise, return @code{#f}.
@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} condition-variable? obj
@deffnx {C Function} scm_condition_variable_p (obj)
Return @code{#t} iff @var{obj} is a condition variable; otherwise,
return @code{#f}.
@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

Up to Guile version 1.8, a thread blocked in guile mode would prevent
the garbage collector from running.  Thus threads had to explicitly
leave guile mode with @code{scm_without_guile ()} before making a
potentially blocking call such as a mutex lock, a @code{select ()}
system call, etc.  The following functions could be used to temporarily
leave guile mode or to perform some common blocking operations in a
supported way.

Starting from Guile 2.0, blocked threads no longer hinder garbage
collection.  Thus, the functions below are not needed anymore.  They can
still be used to inform the GC that a thread is about to block, giving
it a (small) optimization opportunity for ``stop the world'' garbage
collections, should they occur while the thread is blocked.

@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

@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:


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