1
Fork 0
mirror of https://git.savannah.gnu.org/git/guile.git synced 2025-06-04 11:10:27 +02:00

* scheme-binding.texi: Renamed to api-binding.texi.

* scheme-compound.texi: Renamed to api-compound.texi.
* scheme-control.texi: Renamed to api-control.texi.
* scheme-data.texi: Renamed to api-data.texi.
* scheme-debug.texi: Renamed to api-debug.texi.
* deprecated.texi: Renamed to api-deprecated.texi.
* scheme-evaluation.texi: Renamed to api-evaluation.texi.
* ref-init.texi: Renamed to api-init.texi.
* scheme-io.texi: Renamed to api-io.texi.
* scheme-memory.texi: Renamed to api-memory.texi.
* scheme-modules.texi: Renamed to api-modules.texi.
* scheme-options.texi: Renamed to api-options.texi.
* scm.texi: Renamed to api-overview.texi.
* scheme-procedures.texi: Renamed to api-procedures.texi.
* scheme-scheduling.texi: Renamed to api-scheduling.texi.
* scheme-scm.texi: Renamed to api-scm.texi.
* scheme-smobs.texi: Renamed to api-smobs.texi.
* scheme-snarf.texi: Renamed to api-snarf.texi.
* scheme-translation.texi: Renamed to api-translation.texi.
* scheme-utility.texi: Renamed to api-utility.texi.
* debugging.texi: Renamed to scheme-debugging.texi.
* scripts.texi: Renamed to scheme-scripts.texi.
* program.texi: Renamed to libguile-program.texi.
This commit is contained in:
Marius Vollmer 2004-08-02 12:29:00 +00:00
parent 237be23842
commit 07d83abe7b
45 changed files with 16805 additions and 45 deletions

View file

@ -27,24 +27,24 @@ guile_TEXINFOS = preface.texi \
intro.texi \
libguile-program.texi \
scheme-intro.texi \
scheme-scm.texi \
scheme-snarf.texi \
scheme-smobs.texi \
api-scm.texi \
api-snarf.texi \
api-smobs.texi \
scheme-ideas.texi \
scheme-data.texi \
scheme-procedures.texi \
scheme-utility.texi \
scheme-binding.texi \
scheme-control.texi \
scheme-io.texi \
scheme-evaluation.texi \
scheme-memory.texi \
scheme-modules.texi \
scheme-scheduling.texi \
scheme-options.texi \
scheme-translation.texi \
scheme-debug.texi \
deprecated.texi \
api-data.texi \
api-procedures.texi \
api-utility.texi \
api-binding.texi \
api-control.texi \
api-io.texi \
api-evaluation.texi \
api-memory.texi \
api-modules.texi \
api-scheduling.texi \
api-options.texi \
api-translation.texi \
api-debug.texi \
api-deprecated.texi \
scheme-reading.texi \
scheme-indices.texi \
slib.texi \
@ -52,17 +52,17 @@ guile_TEXINFOS = preface.texi \
expect.texi \
scsh.texi \
tcltk.texi \
scripts.texi \
scheme-scripts.texi \
gh.texi \
scm.texi \
debugging.texi \
api-overview.texi \
scheme-debugging.texi \
indices.texi \
script-getopt.texi \
data-rep.texi \
repl-modules.texi \
srfi-modules.texi \
misc-modules.texi \
scheme-compound.texi \
api-compound.texi \
autoconf.texi \
autoconf-macros.texi \
tools.texi \
@ -72,7 +72,7 @@ guile_TEXINFOS = preface.texi \
libguile-snarf.texi \
libguile-linking.texi \
libguile-extensions.texi \
ref-init.texi \
api-init.texi \
mod-getopt-long.texi
ETAGS_ARGS = $(info_TEXINFOS) $(guile_TEXINFOS)

283
doc/ref/api-binding.texi Normal file
View file

@ -0,0 +1,283 @@
@c -*-texinfo-*-
@c This is part of the GNU Guile Reference Manual.
@c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004
@c Free Software Foundation, Inc.
@c See the file guile.texi for copying conditions.
@page
@node Binding Constructs
@section Definitions and Variable Bindings
@c FIXME::martin: Review me!
Scheme supports the definition of variables in different contexts.
Variables can be defined at the top level, so that they are visible in
the entire program, and variables can be defined locally to procedures
and expressions. This is important for modularity and data abstraction.
@menu
* Top Level:: Top level variable definitions.
* Local Bindings:: Local variable bindings.
* Internal Definitions:: Internal definitions.
* Binding Reflection:: Querying variable bindings.
@end menu
@node Top Level
@subsection Top Level Variable Definitions
@cindex variable definition
On the top level of a program (i.e. when not inside the body of a
procedure definition or a @code{let}, @code{let*} or @code{letrec}
expression), a definition of the form
@lisp
(define a @var{value})
@end lisp
@noindent
defines a variable called @code{a} and sets it to the value @var{value}.
If the variable already exists, because it has already been created by a
previous @code{define} expression with the same name, its value is
simply changed to the new @var{value}. In this case, then, the above
form is completely equivalent to
@lisp
(set! a @var{value})
@end lisp
@noindent
This equivalence means that @code{define} can be used interchangeably
with @code{set!} to change the value of variables at the top level of
the REPL or a Scheme source file. It is useful during interactive
development when reloading a Scheme file that you have modified, because
it allows the @code{define} expressions in that file to work as expected
both the first time that the file is loaded and on subsequent occasions.
Note, though, that @code{define} and @code{set!} are not always
equivalent. For example, a @code{set!} is not allowed if the named
variable does not already exist, and the two expressions can behave
differently in the case where there are imported variables visible from
another module.
@deffn {Scheme Syntax} define name value
Create a top level variable named @var{name} with value @var{value}.
If the named variable already exists, just change its value. The return
value of a @code{define} expression is unspecified.
@end deffn
The C API equivalents of @code{define} are @code{scm_define} and
@code{scm_c_define}, which differ from each other in whether the
variable name is specified as a @code{SCM} symbol or as a
null-terminated C string.
@deffn {C Function} scm_define (sym, value)
@deffnx {C Function} scm_c_define (const char *name, value)
C equivalents of @code{define}, with variable name specified either by
@var{sym}, a symbol, or by @var{name}, a null-terminated C string. Both
variants return the new or preexisting variable object.
@end deffn
@code{define} (when it occurs at top level), @code{scm_define} and
@code{scm_c_define} all create or set the value of a variable in the top
level environment of the current module. If there was not already a
variable with the specified name belonging to the current module, but a
similarly named variable from another module was visible through having
been imported, the newly created variable in the current module will
shadow the imported variable, such that the imported variable is no
longer visible.
Attention: Scheme definitions inside local binding constructs
(@pxref{Local Bindings}) act differently (@pxref{Internal Definitions}).
@node Local Bindings
@subsection Local Variable Bindings
@c FIXME::martin: Review me!
@cindex local bindings
@cindex local variables
As opposed to definitions at the top level, which are visible in the
whole program (or current module, when Guile modules are used), it is
also possible to define variables which are only visible in a
well-defined part of the program. Normally, this part of a program
will be a procedure or a subexpression of a procedure.
With the constructs for local binding (@code{let}, @code{let*} and
@code{letrec}), the Scheme language has a block structure like most
other programming languages since the days of @sc{Algol 60}. Readers
familiar to languages like C or Java should already be used to this
concept, but the family of @code{let} expressions has a few properties
which are well worth knowing.
The first local binding construct is @code{let}. The other constructs
@code{let*} and @code{letrec} are specialized versions for usage where
using plain @code{let} is a bit inconvenient.
@deffn syntax let bindings body
@var{bindings} has the form
@lisp
((@var{variable1} @var{init1}) @dots{})
@end lisp
that is zero or more two-element lists of a variable and an arbitrary
expression each. All @var{variable} names must be distinct.
A @code{let} expression is evaluated as follows.
@itemize @bullet
@item
All @var{init} expressions are evaluated.
@item
New storage is allocated for the @var{variables}.
@item
The values of the @var{init} expressions are stored into the variables.
@item
The expressions in @var{body} are evaluated in order, and the value of
the last expression is returned as the value of the @code{let}
expression.
@item
The storage for the @var{variables} is freed.
@end itemize
The @var{init} expressions are not allowed to refer to any of the
@var{variables}.
@end deffn
@deffn syntax let* bindings body
Similar to @code{let}, but the variable bindings are performed
sequentially, that means that all @var{init} expression are allowed to
use the variables defined on their left in the binding list.
A @code{let*} expression can always be expressed with nested @code{let}
expressions.
@lisp
(let* ((a 1) (b a))
b)
@equiv{}
(let ((a 1))
(let ((b a))
b))
@end lisp
@end deffn
@deffn syntax letrec bindings body
Similar to @code{let}, but it is possible to refer to the @var{variable}
from lambda expression created in any of the @var{inits}. That is,
procedures created in the @var{init} expression can recursively refer to
the defined variables.
@lisp
(letrec ((even?
(lambda (n)
(if (zero? n)
#t
(odd? (- n 1)))))
(odd?
(lambda (n)
(if (zero? n)
#f
(even? (- n 1))))))
(even? 88))
@result{}
#t
@end lisp
@end deffn
There is also an alternative form of the @code{let} form, which is used
for expressing iteration. Because of the use as a looping construct,
this form (the @dfn{named let}) is documented in the section about
iteration (@pxref{while do, Iteration})
@node Internal Definitions
@subsection Internal definitions
@c FIXME::martin: Review me!
A @code{define} form which appears inside the body of a @code{lambda},
@code{let}, @code{let*}, @code{letrec} or equivalent expression is
called an @dfn{internal definition}. An internal definition differs
from a top level definition (@pxref{Top Level}), because the definition
is only visible inside the complete body of the enclosing form. Let us
examine the following example.
@lisp
(let ((frumble "froz"))
(define banana (lambda () (apple 'peach)))
(define apple (lambda (x) x))
(banana))
@result{}
peach
@end lisp
Here the enclosing form is a @code{let}, so the @code{define}s in the
@code{let}-body are internal definitions. Because the scope of the
internal definitions is the @strong{complete} body of the
@code{let}-expression, the @code{lambda}-expression which gets bound
to the variable @code{banana} may refer to the variable @code{apple},
even though it's definition appears lexically @emph{after} the definition
of @code{banana}. This is because a sequence of internal definition
acts as if it were a @code{letrec} expression.
@lisp
(let ()
(define a 1)
(define b 2)
(+ a b))
@end lisp
@noindent
is equivalent to
@lisp
(let ()
(letrec ((a 1) (b 2))
(+ a b)))
@end lisp
Another noteworthy difference to top level definitions is that within
one group of internal definitions all variable names must be distinct.
That means where on the top level a second define for a given variable
acts like a @code{set!}, an exception is thrown for internal definitions
with duplicate bindings.
@c FIXME::martin: The following is required by R5RS, but Guile does not
@c signal an error. Document it anyway, saying that Guile is sloppy?
@c Internal definitions are only allowed at the beginning of the body of an
@c enclosing expression. They may not be mixed with other expressions.
@c @lisp
@c (let ()
@c (define a 1)
@c a
@c (define b 2)
@c b)
@c @end lisp
@node Binding Reflection
@subsection Querying variable bindings
Guile provides a procedure for checking whether a symbol is bound in the
top level environment.
@c NJFIXME explain [env]
@deffn {Scheme Procedure} defined? sym [env]
@deffnx {C Function} scm_defined_p (sym, env)
Return @code{#t} if @var{sym} is defined in the lexical environment @var{env}. When @var{env} is not specified, look in the top-level environment as defined by the current module.
@end deffn
@c Local Variables:
@c TeX-master: "guile.texi"
@c End:

2530
doc/ref/api-compound.texi Normal file

File diff suppressed because it is too large Load diff

1337
doc/ref/api-control.texi Normal file

File diff suppressed because it is too large Load diff

3591
doc/ref/api-data.texi Executable file

File diff suppressed because it is too large Load diff

361
doc/ref/api-debug.texi Normal file
View file

@ -0,0 +1,361 @@
@c -*-texinfo-*-
@c This is part of the GNU Guile Reference Manual.
@c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004
@c Free Software Foundation, Inc.
@c See the file guile.texi for copying conditions.
@page
@node Debugging
@section Debugging Infrastructure
@menu
* Interactive Debugging:: Functions intended for interactive use.
* Breakpoints::
* Source Properties:: Remembering the source of an expression.
* Using Traps::
* Capturing the Stack or Innermost Stack Frame::
* Examining the Stack::
* Examining Stack Frames::
* Decoding Memoized Source Expressions::
* Starting a New Stack::
@end menu
@node Interactive Debugging
@subsection Interactive Debugging
@deffn {Scheme Procedure} backtrace
@deffnx {C Function} scm_backtrace ()
Display a backtrace of the stack saved by the last error
to the current output port.
@end deffn
@deffn {Scheme Procedure} debug
Invoke the Guile debugger to explore the context of the last error.
@end deffn
@node Breakpoints
@subsection Breakpoints
@deffn {Generic Function} set-breakpoint! behaviour . location-args
Set a breakpoint with behaviour @var{behaviour} at the location
specified by @var{location-args}.
The form of the @var{location-args} depends upon what methods for
@code{set-breakpoint!} have been provided by the implementations of
subclasses of the @code{<breakpoint>} base class.
@end deffn
@deffn {Generic Function} get-breakpoint . location-args
Find and return the breakpoint instance at the location specified by
@var{location-args}.
The form of the @var{location-args} depends upon what methods for
@code{get-breakpoint} have been provided by the implementations of
subclasses of the @code{<breakpoint>} base class.
@end deffn
@deffn {Method} set-breakpoint! behaviour (proc <procedure>)
Set a breakpoint with behaviour @var{behaviour} before applications of
the procedure @var{proc}.
@end deffn
@deffn {Method} set-breakpoint! behaviour x-as-read (x-pairified <pair>)
Set a breakpoint with behaviour @var{behaviour} on the source expression
@var{x-pairified}, storing @var{x-as-read} for use in messages
describing the breakpoint.
@end deffn
@deffn {Method} set-breakpoint! behaviour (number <integer>)
Change the behaviour of existing breakpoint number @var{number} to
@var{behaviour}.
@end deffn
@deffn {Accessor} bp-behaviour breakpoint
Get or set the behaviour of the breakpoint instance @var{breakpoint}.
@end deffn
@deffn {Accessor} bp-enabled? breakpoint
Get or set the enabled state of the specified @var{breakpoint}.
@end deffn
@deffn {Procedure} enable-breakpoint! . location-args
@deffnx {Procedure} disable-breakpoint! . location-args
Enable or disable the breakpoint at the location specified by
@var{location-args}.
@end deffn
@deffn {Generic Function} bp-delete! breakpoint
Delete breakpoint @var{breakpoint}. This means (1) doing whatever is
needed to prevent the breakpoint from triggering again, and (2) removing
it from the global list of current breakpoints.
@end deffn
@deffn {Procedure} delete-breakpoint! . location-args
Delete the breakpoint at the location specified by @var{location-args}.
@end deffn
@deffn {Generic Function} bp-describe breakpoint port
Print a description of @var{breakpoint} to the specified @var{port}.
@var{port} can be @code{#t} for standard output, or else any output
port.
@end deffn
@deffn {Procedure} describe-breakpoint . location-args
Print (to standard output) a description of the breakpoint at location
specified by @var{location-args}.
@end deffn
@deffn {Procedure} all-breakpoints
Return a list of all current breakpoints, ordered by breakpoint number.
@end deffn
@deffn {Procedure} describe-all-breakpoints
Print a description of all current breakpoints to standard output.
@end deffn
@node Source Properties
@subsection Source Properties
@cindex source properties
As Guile reads in Scheme code from file or from standard input, it
remembers the file name, line number and column number where each
expression begins. These pieces of information are known as the
@dfn{source properties} of the expression. If an expression undergoes
transformation --- for example, if there is a syntax transformer in
effect, or the expression is a macro call --- the source properties are
copied from the untransformed to the transformed expression so that, if
an error occurs when evaluating the transformed expression, Guile's
debugger can point back to the file and location where the expression
originated.
The way that source properties are stored means that Guile can only
associate source properties with parenthesized expressions, and not, for
example, with individual symbols, numbers or strings. The difference
can be seen by typing @code{(xxx)} and @code{xxx} at the Guile prompt
(where the variable @code{xxx} has not been defined):
@example
guile> (xxx)
standard input:2:1: In expression (xxx):
standard input:2:1: Unbound variable: xxx
ABORT: (unbound-variable)
guile> xxx
<unnamed port>: In expression xxx:
<unnamed port>: Unbound variable: xxx
ABORT: (unbound-variable)
@end example
@noindent
In the latter case, no source properties were stored, so the best that
Guile could say regarding the location of the problem was ``<unnamed
port>''.
The recording of source properties is controlled by the read option
named ``positions'' (@pxref{Reader options}). This option is switched
@emph{on} by default, together with the debug options ``debug'' and
``backtrace'' (@pxref{Debugger options}), when Guile is run
interactively; all these options are @emph{off} by default when Guile
runs a script non-interactively.
@node Using Traps
@subsection Using Traps
@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 Capturing the Stack or Innermost Stack Frame
@subsection Capturing the Stack or Innermost Stack Frame
When an error occurs in a running program, or the program hits a
breakpoint, its state at that point can be represented by a @dfn{stack}
of all the evaluations and procedure applications that are logically in
progress at that time, each of which is known as a @dfn{frame}. The
programmer can learn more about the program's state at the point of
interruption or error by inspecting the stack and its frames.
@deffn {Scheme Procedure} make-stack obj . args
@deffnx {C Function} scm_make_stack (obj, args)
Create a new stack. If @var{obj} is @code{#t}, the current
evaluation stack is used for creating the stack frames,
otherwise the frames are taken from @var{obj} (which must be
either a debug object or a continuation).
@var{args} should be a list containing any combination of
integer, procedure and @code{#t} values.
These values specify various ways of cutting away uninteresting
stack frames from the top and bottom of the stack that
@code{make-stack} returns. They come in pairs like this:
@code{(@var{inner_cut_1} @var{outer_cut_1} @var{inner_cut_2}
@var{outer_cut_2} @dots{})}.
Each @var{inner_cut_N} can be @code{#t}, an integer, or a
procedure. @code{#t} means to cut away all frames up to but
excluding the first user module frame. An integer means to cut
away exactly that number of frames. A procedure means to cut
away all frames up to but excluding the application frame whose
procedure matches the specified one.
Each @var{outer_cut_N} can be an integer or a procedure. An
integer means to cut away that number of frames. A procedure
means to cut away frames down to but excluding the application
frame whose procedure matches the specified one.
If the @var{outer_cut_N} of the last pair is missing, it is
taken as 0.
@end deffn
@deffn {Scheme Procedure} last-stack-frame obj
@deffnx {C Function} scm_last_stack_frame (obj)
Return a stack which consists of a single frame, which is the
last stack frame for @var{obj}. @var{obj} must be either a
debug object or a continuation.
@end deffn
@node Examining the Stack
@subsection Examining the Stack
@deffn {Scheme Procedure} stack? obj
@deffnx {C Function} scm_stack_p (obj)
Return @code{#t} if @var{obj} is a calling stack.
@end deffn
@deffn {Scheme Procedure} stack-id stack
@deffnx {C Function} scm_stack_id (stack)
Return the identifier given to @var{stack} by @code{start-stack}.
@end deffn
@deffn {Scheme Procedure} stack-length stack
@deffnx {C Function} scm_stack_length (stack)
Return the length of @var{stack}.
@end deffn
@deffn {Scheme Procedure} stack-ref stack index
@deffnx {C Function} scm_stack_ref (stack, index)
Return the @var{index}'th frame from @var{stack}.
@end deffn
@deffn {Scheme Procedure} display-backtrace stack port [first [depth]]
@deffnx {C Function} scm_display_backtrace (stack, port, first, depth)
Display a backtrace to the output port @var{port}. @var{stack}
is the stack to take the backtrace from, @var{first} specifies
where in the stack to start and @var{depth} how much frames
to display. Both @var{first} and @var{depth} can be @code{#f},
which means that default values will be used.
@end deffn
@node Examining Stack Frames
@subsection Examining Stack Frames
@deffn {Scheme Procedure} frame? obj
@deffnx {C Function} scm_frame_p (obj)
Return @code{#t} if @var{obj} is a stack frame.
@end deffn
@deffn {Scheme Procedure} frame-number frame
@deffnx {C Function} scm_frame_number (frame)
Return the frame number of @var{frame}.
@end deffn
@deffn {Scheme Procedure} frame-previous frame
@deffnx {C Function} scm_frame_previous (frame)
Return the previous frame of @var{frame}, or @code{#f} if
@var{frame} is the first frame in its stack.
@end deffn
@deffn {Scheme Procedure} frame-next frame
@deffnx {C Function} scm_frame_next (frame)
Return the next frame of @var{frame}, or @code{#f} if
@var{frame} is the last frame in its stack.
@end deffn
@deffn {Scheme Procedure} frame-source frame
@deffnx {C Function} scm_frame_source (frame)
Return the source of @var{frame}.
@end deffn
@deffn {Scheme Procedure} frame-procedure? frame
@deffnx {C Function} scm_frame_procedure_p (frame)
Return @code{#t} if a procedure is associated with @var{frame}.
@end deffn
@deffn {Scheme Procedure} frame-procedure frame
@deffnx {C Function} scm_frame_procedure (frame)
Return the procedure for @var{frame}, or @code{#f} if no
procedure is associated with @var{frame}.
@end deffn
@deffn {Scheme Procedure} frame-arguments frame
@deffnx {C Function} scm_frame_arguments (frame)
Return the arguments of @var{frame}.
@end deffn
@deffn {Scheme Procedure} frame-evaluating-args? frame
@deffnx {C Function} scm_frame_evaluating_args_p (frame)
Return @code{#t} if @var{frame} contains evaluated arguments.
@end deffn
@deffn {Scheme Procedure} frame-overflow? frame
@deffnx {C Function} scm_frame_overflow_p (frame)
Return @code{#t} if @var{frame} is an overflow frame.
@end deffn
@deffn {Scheme Procedure} frame-real? frame
@deffnx {C Function} scm_frame_real_p (frame)
Return @code{#t} if @var{frame} is a real frame.
@end deffn
@deffn {Scheme Procedure} display-application frame [port [indent]]
@deffnx {C Function} scm_display_application (frame, port, indent)
Display a procedure application @var{frame} to the output port
@var{port}. @var{indent} specifies the indentation of the
output.
@end deffn
@node Decoding Memoized Source Expressions
@subsection Decoding Memoized Source Expressions
@deffn {Scheme Procedure} memoized? obj
@deffnx {C Function} scm_memoized_p (obj)
Return @code{#t} if @var{obj} is memoized.
@end deffn
@deffn {Scheme Procedure} unmemoize m
@deffnx {C Function} scm_unmemoize (m)
Unmemoize the memoized expression @var{m},
@end deffn
@deffn {Scheme Procedure} memoized-environment m
@deffnx {C Function} scm_memoized_environment (m)
Return the environment of the memoized expression @var{m}.
@end deffn
@node Starting a New Stack
@subsection Starting a New Stack
@deffn {Scheme Syntax} start-stack id exp
Evaluate @var{exp} on a new calling stack with identity @var{id}. If
@var{exp} is interrupted during evaluation, backtraces will not display
frames farther back than @var{exp}'s top-level form. This macro is a
way of artificially limiting backtraces and stack procedures, largely as
a convenience to the user.
@end deffn
@c Local Variables:
@c TeX-master: "guile.texi"
@c End:

604
doc/ref/api-evaluation.texi Normal file
View file

@ -0,0 +1,604 @@
@c -*-texinfo-*-
@c This is part of the GNU Guile Reference Manual.
@c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004
@c Free Software Foundation, Inc.
@c See the file guile.texi for copying conditions.
@page
@node Read/Load/Eval
@section Reading and Evaluating Scheme Code
This chapter describes Guile functions that are concerned with reading,
loading and evaluating Scheme code at run time.
@menu
* Scheme Syntax:: Standard and extended Scheme syntax.
* Scheme Read:: Reading Scheme code.
* Fly Evaluation:: Procedures for on the fly evaluation.
* Loading:: Loading Scheme code from file.
* Delayed Evaluation:: Postponing evaluation until it is needed.
* Local Evaluation:: Evaluation in a local environment.
* Evaluator Behaviour:: Modifying Guile's evaluator.
@end menu
@node Scheme Syntax
@subsection Scheme Syntax: Standard and Guile Extensions
@menu
* Expression Syntax::
* Comments::
* Block Comments::
* Case Sensitivity::
* Keyword Syntax::
* Reader Extensions::
@end menu
@node Expression Syntax
@subsubsection Expression Syntax
An expression to be evaluated takes one of the following forms.
@table @nicode
@item @var{symbol}
A symbol is evaluated by dereferencing. A binding of that symbol is
sought and the value there used. For example,
@example
(define x 123)
x @result{} 123
@end example
@item (@var{proc} @var{args}@dots{})
A parenthesised expression is a function call. @var{proc} and each
argument are evaluated, then the function (which @var{proc} evaluated
to) is called with those arguments.
The order in which @var{proc} and the arguments are evaluated is
unspecified, so be careful when using expressions with side effects.
@example
(max 1 2 3) @result{} 3
(define (get-some-proc) min)
((get-some-proc) 1 2 3) @result{} 1
@end example
The same sort of parenthesised form is used for a macro invocation,
but in that case the arguments are not evaluated. See the
descriptions of macros for more on this (@pxref{Macros}, and
@pxref{Syntax Rules}).
@item @var{constant}
Number, string, character and boolean constants evaluate ``to
themselves'', so can appear as literals.
@example
123 @result{} 123
99.9 @result{} 99.9
"hello" @result{} "hello"
#\z @result{} #\z
#t @result{} #t
@end example
Note that an application must not attempt to modify literal strings,
since they may be in read-only memory.
@item (quote @var{data})
@itemx '@var{data}
@findex quote
@findex '
Quoting is used to obtain a literal symbol (instead of a variable
reference), a literal list (instead of a function call), or a literal
vector. @nicode{'} is simply a shorthand for a @code{quote} form.
For example,
@example
'x @result{} x
'(1 2 3) @result{} (1 2 3)
'#(1 (2 3) 4) @result{} #(1 (2 3) 4)
(quote x) @result{} x
(quote (1 2 3)) @result{} (1 2 3)
(quote #(1 (2 3) 4)) @result{} #(1 (2 3) 4)
@end example
Note that an application must not attempt to modify literal lists or
vectors obtained from a @code{quote} form, since they may be in
read-only memory.
@item (quasiquote @var{data})
@itemx `@var{data}
@findex quasiquote
@findex `
Backquote quasi-quotation is like @code{quote}, but selected
sub-expressions are evaluated. This is a convenient way to construct
a list or vector structure most of which is constant, but at certain
points should have expressions substituted.
The same effect can always be had with suitable @code{list},
@code{cons} or @code{vector} calls, but quasi-quoting is often easier.
@table @nicode
@item (unquote @var{expr})
@itemx ,@var{expr}
@findex unquote
@findex ,
Within the quasiquote @var{data}, @code{unquote} or @code{,} indicates
an expression to be evaluated and inserted. The comma syntax @code{,}
is simply a shorthand for an @code{unquote} form. For example,
@example
`(1 2 ,(* 9 9) 3 4) @result{} (1 2 81 3 4)
`(1 (unquote (+ 1 1)) 3) @result{} (1 2 3)
`#(1 ,(/ 12 2)) @result{} #(1 6)
@end example
@item (unquote-splicing @var{expr})
@itemx ,@@@var{expr}
@findex unquote-splicing
@findex ,@@
Within the quasiquote @var{data}, @code{unquote-splicing} or
@code{,@@} indicates an expression to be evaluated and the elements of
the returned list inserted. @var{expr} must evaluate to a list. The
``comma-at'' syntax @code{,@@} is simply a shorthand for an
@code{unquote-splicing} form.
@example
(define x '(2 3))
`(1 ,@@x 4) @result{} (1 2 3 4)
`(1 (unquote-splicing (map 1+ x))) @result{} (1 3 4)
`#(9 ,@@x 9) @result{} #(9 2 3 9)
@end example
Notice @code{,@@} differs from plain @code{,} in the way one level of
nesting is stripped. For @code{,@@} the elements of a returned list
are inserted, whereas with @code{,} it would be the list itself
inserted.
@end table
@c
@c FIXME: What can we say about the mutability of a quasiquote
@c result? R5RS doesn't seem to specify anything, though where it
@c says backquote without commas is the same as plain quote then
@c presumably the "fixed" portions of a quasiquote expression must be
@c treated as immutable.
@c
@end table
@node Comments
@subsubsection Comments
@c FIXME::martin: Review me!
Comments in Scheme source files are written by starting them with a
semicolon character (@code{;}). The comment then reaches up to the end
of the line. Comments can begin at any column, and the may be inserted
on the same line as Scheme code.
@lisp
; Comment
;; Comment too
(define x 1) ; Comment after expression
(let ((y 1))
;; Display something.
(display y)
;;; Comment at left margin.
(display (+ y 1)))
@end lisp
It is common to use a single semicolon for comments following
expressions on a line, to use two semicolons for comments which are
indented like code, and three semicolons for comments which start at
column 0, even if they are inside an indented code block. This
convention is used when indenting code in Emacs' Scheme mode.
@node Block Comments
@subsubsection Block Comments
@c FIXME::martin: Review me!
@cindex multiline comments
In addition to the standard line comments defined by R5RS, Guile has
another comment type for multiline comments, called @dfn{block
comments}. This type of comment begins with the character sequence
@code{#!} and ends with the characters @code{!#}, which must appear on a
line of their own. These comments are compatible with the block
comments in the Scheme Shell @file{scsh} (@pxref{The Scheme shell
(scsh)}). The characters @code{#!} were chosen because they are the
magic characters used in shell scripts for indicating that the name of
the program for executing the script follows on the same line.
Thus a Guile script often starts like this.
@lisp
#! /usr/local/bin/guile -s
!#
@end lisp
More details on Guile scripting can be found in the scripting section
(@pxref{Guile Scripting}).
@node Case Sensitivity
@subsubsection Case Sensitivity
@c FIXME::martin: Review me!
Scheme as defined in R5RS is not case sensitive when reading symbols.
Guile, on the contrary is case sensitive by default, so the identifiers
@lisp
guile-whuzzy
Guile-Whuzzy
@end lisp
are the same in R5RS Scheme, but are different in Guile.
It is possible to turn off case sensitivity in Guile by setting the
reader option @code{case-insensitive}. More on reader options can be
found at (@pxref{Reader options}).
@lisp
(read-enable 'case-insensitive)
@end lisp
Note that this is seldom a problem, because Scheme programmers tend not
to use uppercase letters in their identifiers anyway.
@node Keyword Syntax
@subsubsection Keyword Syntax
@node Reader Extensions
@subsubsection Reader Extensions
@deffn {Scheme Procedure} read-hash-extend chr proc
@deffnx {C Function} scm_read_hash_extend (chr, proc)
Install the procedure @var{proc} for reading expressions
starting with the character sequence @code{#} and @var{chr}.
@var{proc} will be called with two arguments: the character
@var{chr} and the port to read further data from. The object
returned will be the return value of @code{read}.
@end deffn
@node Scheme Read
@subsection Reading Scheme Code
@rnindex read
@deffn {Scheme Procedure} read [port]
@deffnx {C Function} scm_read (port)
Read an s-expression from the input port @var{port}, or from
the current input port if @var{port} is not specified.
Any whitespace before the next token is discarded.
@end deffn
The behaviour of Guile's Scheme reader can be modified by manipulating
its read options. For more information about options, @xref{User level
options interfaces}. If you want to know which reader options are
available, @xref{Reader options}.
@c FIXME::martin: This is taken from libguile/options.c. Is there
@c actually a difference between 'help and 'full?
@deffn {Scheme Procedure} read-options [setting]
Display the current settings of the read options. If @var{setting} is
omitted, only a short form of the current read options is printed.
Otherwise, @var{setting} should be one of the following symbols:
@table @code
@item help
Display the complete option settings.
@item full
Like @code{help}, but also print programmer options.
@end table
@end deffn
@deffn {Scheme Procedure} read-enable option-name
@deffnx {Scheme Procedure} read-disable option-name
@deffnx {Scheme Procedure} read-set! option-name value
Modify the read options. @code{read-enable} should be used with boolean
options and switches them on, @code{read-disable} switches them off.
@code{read-set!} can be used to set an option to a specific value.
@end deffn
@deffn {Scheme Procedure} read-options-interface [setting]
@deffnx {C Function} scm_read_options (setting)
Option interface for the read options. Instead of using
this procedure directly, use the procedures @code{read-enable},
@code{read-disable}, @code{read-set!} and @code{read-options}.
@end deffn
@node Fly Evaluation
@subsection Procedures for On the Fly Evaluation
@xref{Environments}.
@rnindex eval
@c ARGFIXME environment/environment specifier
@deffn {Scheme Procedure} eval exp module
@deffnx {C Function} scm_eval (exp, module)
Evaluate @var{exp}, a list representing a Scheme expression,
in the top-level environment specified by @var{module}.
While @var{exp} is evaluated (using @code{primitive-eval}),
@var{module} is made the current module. The current module
is reset to its previous value when @var{eval} returns.
@end deffn
@rnindex interaction-environment
@deffn {Scheme Procedure} interaction-environment
@deffnx {C Function} scm_interaction_environment ()
Return a specifier for the environment that contains
implementation--defined bindings, typically a superset of those
listed in the report. The intent is that this procedure will
return the environment in which the implementation would
evaluate expressions dynamically typed by the user.
@end deffn
@deffn {Scheme Procedure} eval-string string [module]
@deffnx {C Function} scm_eval_string (string)
@deffnx {C Function} scm_eval_string_in_module (string, module)
Evaluate @var{string} as the text representation of a Scheme form or
forms, and return whatever value they produce. Evaluation takes place
in the given module, or in the current module when no module is given.
While the code is evaluated, the given module is made the current one.
The current module is restored when this procedure returns.
@end deffn
@deffn {Scheme Procedure} apply proc arg1 @dots{} argN arglst
@deffnx {C Function} scm_apply_0 (proc, arglst)
@deffnx {C Function} scm_apply_1 (proc, arg1, arglst)
@deffnx {C Function} scm_apply_2 (proc, arg1, arg2, arglst)
@deffnx {C Function} scm_apply_3 (proc, arg1, arg2, arg3, arglst)
@deffnx {C Function} scm_apply (proc, arg, rest)
@rnindex apply
Call @var{proc} with arguments @var{arg1} @dots{} @var{argN} plus the
elements of the @var{arglst} list.
@code{scm_apply} takes parameters corresponding to a Scheme level
@code{(lambda (proc arg . rest) ...)}. So @var{arg} and all but the
last element of the @var{rest} list make up
@var{arg1}@dots{}@var{argN} and the last element of @var{rest} is the
@var{arglst} list. Or if @var{rest} is the empty list @code{SCM_EOL}
then there's no @var{arg1}@dots{}@var{argN} and @var{arg} is the
@var{arglst}.
@var{arglst} is not modified, but the @var{rest} list passed to
@code{scm_apply} is modified.
@end deffn
@deffn {C Function} scm_call_0 (proc)
@deffnx {C Function} scm_call_1 (proc, arg1)
@deffnx {C Function} scm_call_2 (proc, arg1, arg2)
@deffnx {C Function} scm_call_3 (proc, arg1, arg2, arg3)
Call @var{proc} with the given arguments.
@end deffn
@deffn {Scheme Procedure} apply:nconc2last lst
@deffnx {C Function} scm_nconc2last (lst)
@var{lst} should be a list (@var{arg1} @dots{} @var{argN}
@var{arglst}), with @var{arglst} being a list. This function returns
a list comprising @var{arg1} to @var{argN} plus the elements of
@var{arglst}. @var{lst} is modified to form the return. @var{arglst}
is not modified, though the return does share structure with it.
This operation collects up the arguments from a list which is
@code{apply} style parameters.
@end deffn
@deffn {Scheme Procedure} primitive-eval exp
@deffnx {C Function} scm_primitive_eval (exp)
Evaluate @var{exp} in the top-level environment specified by
the current module.
@end deffn
@node Loading
@subsection Loading Scheme Code from File
@rnindex load
@deffn {Scheme Procedure} load filename
Load @var{filename} and evaluate its contents in the top-level
environment. The load paths are not searched. If the variable
@code{%load-hook} is defined, it should be bound to a procedure that
will be called before any code is loaded. See documentation for
@code{%load-hook} later in this section.
@end deffn
@deffn {Scheme Procedure} load-from-path filename
Similar to @code{load}, but searches for @var{filename} in the load
paths.
@end deffn
@deffn {Scheme Procedure} primitive-load filename
@deffnx {C Function} scm_primitive_load (filename)
Load the file named @var{filename} and evaluate its contents in
the top-level environment. The load paths are not searched;
@var{filename} must either be a full pathname or be a pathname
relative to the current directory. If the variable
@code{%load-hook} is defined, it should be bound to a procedure
that will be called before any code is loaded. See the
documentation for @code{%load-hook} later in this section.
@end deffn
@deffn {Scheme Procedure} primitive-load-path filename
@deffnx {C Function} scm_primitive_load_path (filename)
Search @var{%load-path} for the file named @var{filename} and
load it into the top-level environment. If @var{filename} is a
relative pathname and is not found in the list of search paths,
an error is signalled.
@end deffn
@deffn {Scheme Procedure} %search-load-path filename
@deffnx {C Function} scm_sys_search_load_path (filename)
Search @var{%load-path} for the file named @var{filename},
which must be readable by the current user. If @var{filename}
is found in the list of paths to search or is an absolute
pathname, return its full pathname. Otherwise, return
@code{#f}. Filenames may have any of the optional extensions
in the @code{%load-extensions} list; @code{%search-load-path}
will try each extension automatically.
@end deffn
@defvar %load-hook
A procedure to be run whenever @code{primitive-load} is called. If this
procedure is defined, it will be called with the filename argument that
was passed to @code{primitive-load}.
@example
(define %load-hook (lambda (file)
(display "Loading ")
(display file)
(write-line "...."))) @result{} undefined
(load-from-path "foo.scm")
@print{} Loading /usr/local/share/guile/site/foo.scm....
@end example
@end defvar
@deffn {Scheme Procedure} current-load-port
@deffnx {C Function} scm_current_load_port ()
Return the current-load-port.
The load port is used internally by @code{primitive-load}.
@end deffn
@defvar %load-extensions
A list of default file extensions for files containing Scheme code.
@code{%search-load-path} tries each of these extensions when looking for
a file to load. By default, @code{%load-extensions} is bound to the
list @code{("" ".scm")}.
@end defvar
@node Delayed Evaluation
@subsection Delayed Evaluation
@cindex delayed evaluation
@cindex promises
Promises are a convenient way to defer a calculation until its result
is actually needed, and to run such a calculation only once.
@deffn syntax delay expr
@rnindex delay
Return a promise object which holds the given @var{expr} expression,
ready to be evaluated by a later @code{force}.
@end deffn
@deffn {Scheme Procedure} promise? obj
@deffnx {C Function} scm_promise_p (obj)
Return true if @var{obj} is a promise.
@end deffn
@rnindex force
@deffn {Scheme Procedure} force p
@deffnx {C Function} scm_force (p)
Return the value obtained from evaluating the @var{expr} in the given
promise @var{p}. If @var{p} has previously been forced then its
@var{expr} is not evaluated again, instead the value obtained at that
time is simply returned.
During a @code{force}, an @var{expr} can call @code{force} again on
its own promise, resulting in a recursive evaluation of that
@var{expr}. The first evaluation to return gives the value for the
promise. Higher evaluations run to completion in the normal way, but
their results are ignored, @code{force} always returns the first
value.
@end deffn
@node Local Evaluation
@subsection Local Evaluation
[the-environment]
@deffn {Scheme Procedure} local-eval exp [env]
@deffnx {C Function} scm_local_eval (exp, env)
Evaluate @var{exp} in its environment. If @var{env} is supplied,
it is the environment in which to evaluate @var{exp}. Otherwise,
@var{exp} must be a memoized code object (in which case, its environment
is implicit).
@end deffn
@node Evaluator Behaviour
@subsection Evaluator Behaviour
@c FIXME::martin: Maybe this node name is bad, but the old name clashed with
@c `Evaluator options' under `Options and Config'.
The behaviour of Guile's evaluator can be modified by manipulating the
evaluator options. For more information about options, @xref{User level
options interfaces}. If you want to know which evaluator options are
available, @xref{Evaluator options}.
@c FIXME::martin: This is taken from libguile/options.c. Is there
@c actually a difference between 'help and 'full?
@deffn {Scheme Procedure} eval-options [setting]
Display the current settings of the evaluator options. If @var{setting}
is omitted, only a short form of the current evaluator options is
printed. Otherwise, @var{setting} should be one of the following
symbols:
@table @code
@item help
Display the complete option settings.
@item full
Like @code{help}, but also print programmer options.
@end table
@end deffn
@deffn {Scheme Procedure} eval-enable option-name
@deffnx {Scheme Procedure} eval-disable option-name
@deffnx {Scheme Procedure} eval-set! option-name value
Modify the evaluator options. @code{eval-enable} should be used with boolean
options and switches them on, @code{eval-disable} switches them off.
@code{eval-set!} can be used to set an option to a specific value.
@end deffn
@deffn {Scheme Procedure} eval-options-interface [setting]
@deffnx {C Function} scm_eval_options_interface (setting)
Option interface for the evaluation options. Instead of using
this procedure directly, use the procedures @code{eval-enable},
@code{eval-disable}, @code{eval-set!} and @code{eval-options}.
@end deffn
@c FIXME::martin: Why aren't these procedure named like the other options
@c procedures?
@deffn {Scheme Procedure} traps [setting]
Display the current settings of the evaluator traps options. If
@var{setting} is omitted, only a short form of the current evaluator
traps options is printed. Otherwise, @var{setting} should be one of the
following symbols:
@table @code
@item help
Display the complete option settings.
@item full
Like @code{help}, but also print programmer options.
@end table
@end deffn
@deffn {Scheme Procedure} trap-enable option-name
@deffnx {Scheme Procedure} trap-disable option-name
@deffnx {Scheme Procedure} trap-set! option-name value
Modify the evaluator options. @code{trap-enable} should be used with boolean
options and switches them on, @code{trap-disable} switches them off.
@code{trap-set!} can be used to set an option to a specific value.
@end deffn
@deffn {Scheme Procedure} evaluator-traps-interface [setting]
@deffnx {C Function} scm_evaluator_traps (setting)
Option interface for the evaluator trap options.
@end deffn
@c Local Variables:
@c TeX-master: "guile.texi"
@c End:

66
doc/ref/api-init.texi Normal file
View file

@ -0,0 +1,66 @@
@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 Initialization
@section Initializing Guile
@deftypefn {C Function} void scm_boot_guile (int @var{argc}, char **@var{argv}, void (*@var{main_func}) (void *@var{data}, int @var{argc}, char **@var{argv}), void *@var{data})
Initialize the Guile Scheme interpreter. Then call @var{main_func},
passing it @var{data}, @var{argc}, and @var{argv} as indicated. The
function @var{main_func} should do all the work of the program
(initializing other packages, defining application-specific functions,
reading user input, and so on) before returning. When @var{main_func}
returns, @code{scm_boot_guile} calls @code{exit (0)};
@code{scm_boot_guile} never returns. If you want some other exit
value, have @var{main_func} call @code{exit} itself.
@code{scm_boot_guile} arranges for the Scheme @code{command-line}
function to return the strings given by @var{argc} and @var{argv}. If
@var{main_func} modifies @var{argc} or @var{argv}, it should call
@code{scm_set_program_arguments} with the final list, so Scheme code
will know which arguments have been processed.
Why must the caller do all the real work from @var{main_func}? Guile's
garbage collector scans the stack to find all local variables that
reference Scheme objects. To do this, it needs to know the bounds of
the stack that might contain such references. Because there is no
portable way in C to find the base of the stack, @code{scm_boot_guile}
assumes that all references are above its own stack frame. If you try
to manipulate Scheme objects after this function returns, it's the luck
of the draw whether Guile's storage manager will be able to find the
objects you allocate. So, @code{scm_boot_guile} function exits, rather
than returning, to discourage you from making that mistake.
See @code{scm_init_guile}, below, for a function that can find the real
base of the stack, but not in a portable way.
@end deftypefn
@deftypefn {C Function} void scm_init_guile ()
Initialize the Guile Scheme interpreter.
In contrast to @code{scm_boot_guile}, this function knows how to find
the true base of the stack and thus does not need to usurp the control
flow of your program. However, since finding the stack base can not be
done portably, this function might not be available in all installations
of Guile. If you can, you should use @code{scm_boot_guile} instead.
Note that @code{scm_init_guile} does not inform Guile about the command
line arguments that should be returned by the Scheme function
@code{command-line}. You can use @code{scm_set_program_arguments} to do
this.
@end deftypefn
@deftypefn {C Function} void scm_shell (int @var{argc}, char **@var{argv})
Process command-line arguments in the manner of the @code{guile}
executable. This includes loading the normal Guile initialization
files, interacting with the user or running any scripts or expressions
specified by @code{-s} or @code{-e} options, and then exiting.
@xref{Invoking Guile}, for more details.
Since this function does not return, you must do all
application-specific initialization before calling this function.
@end deftypefn

1161
doc/ref/api-io.texi Normal file

File diff suppressed because it is too large Load diff

478
doc/ref/api-memory.texi Normal file
View file

@ -0,0 +1,478 @@
@c -*-texinfo-*-
@c This is part of the GNU Guile Reference Manual.
@c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004
@c Free Software Foundation, Inc.
@c See the file guile.texi for copying conditions.
@page
@node Memory Management
@section Memory Management and Garbage Collection
Guile uses a @emph{garbage collector} to manage most of its objects.
While the garbage collector is designed to be mostly invisible, you
sometimes need to interact with it explicitely.
See @ref{Garbage Collection} for a general discussion of how garbage
collection relates to using Guile from C.
@menu
* Garbage Collection Functions::
* Memory Blocks::
* Weak References::
* Guardians::
@end menu
@node Garbage Collection Functions
@subsection Function related to Garbage Collection
@deffn {Scheme Procedure} gc
@deffnx {C Function} scm_gc ()
Scans all of SCM objects and reclaims for further use those that are
no longer accessible. You normally don't need to call this function
explicitly. It is called automatically when appropriate.
@end deffn
@deftypefn {C Function} SCM scm_gc_protect_object (SCM @var{obj})
Protects @var{obj} from being freed by the garbage collector, when it
otherwise might be. When you are done with the object, call
@code{scm_gc_unprotect_object} on the object. Calls to
@code{scm_gc_protect}/@code{scm_gc_unprotect_object} can be nested, and
the object remains protected until it has been unprotected as many times
as it was protected. It is an error to unprotect an object more times
than it has been protected. Returns the SCM object it was passed.
@end deftypefn
@deftypefn {C Function} SCM scm_gc_unprotect_object (SCM @var{obj})
Unprotects an object from the garbage collector which was protected by
@code{scm_gc_unprotect_object}. Returns the SCM object it was passed.
@end deftypefn
@deftypefn {C Function} SCM scm_permanent_object (SCM @var{obj})
Similar to @code{scm_gc_protect_object} in that it causes the
collector to always mark the object, except that it should not be
nested (only call @code{scm_permanent_object} on an object once), and
it has no corresponding unpermanent function. Once an object is
declared permanent, it will never be freed. Returns the SCM object it
was passed.
@end deftypefn
@c NOTE: The varargs scm_remember_upto_here is deliberately not
@c documented, because we don't think it can be implemented as a nice
@c inline compiler directive or asm block. New _3, _4 or whatever
@c forms could certainly be added though, if needed.
@deftypefn {C Macro} void scm_remember_upto_here_1 (SCM obj)
@deftypefnx {C Macro} void scm_remember_upto_here_2 (SCM obj1, SCM obj2)
Create a reference to the given object or objects, so they're certain
to be present on the stack or in a register and hence will not be
freed by the garbage collector before this point.
Note that these functions can only be applied to ordinary C local
variables (ie.@: ``automatics''). Objects held in global or static
variables or some malloced block or the like cannot be protected with
this mechanism.
@end deftypefn
@deffn {Scheme Procedure} gc-stats
@deffnx {C Function} scm_gc_stats ()
Return an association list of statistics about Guile's current
use of storage.
@deftypefun void scm_gc_mark (SCM @var{x})
Mark the object @var{x}, and recurse on any objects @var{x} refers to.
If @var{x}'s mark bit is already set, return immediately. This function
must only be called during the mark-phase of garbage collection,
typically from a smob @emph{mark} function.
@end deftypefun
@end deffn
@node Memory Blocks
@subsection Memory Blocks
In C programs, dynamic management of memory blocks is normally done
with the functions malloc, realloc, and free. Guile has additional
functions for dynamic memory allocation that are integrated into the
garbage collector and the error reporting system.
Memory blocks that are associated with Scheme objects (for example a
smob) should be allocated and freed with @code{scm_gc_malloc} and
@code{scm_gc_free}. The function @code{scm_gc_malloc} will either
return a valid pointer or signal an error. It will also assume that
the new memory can be freed by a garbage collection. The garbage
collector uses this information to decide when to try to actually
collect some garbage. Memory blocks allocated with
@code{scm_gc_malloc} must be freed with @code{scm_gc_free}.
For memory that is not associated with a Scheme object, you can use
@code{scm_malloc} instead of @code{malloc}. Like
@code{scm_gc_malloc}, it will either return a valid pointer or signal
an error. However, it will not assume that the new memory block can
be freed by a garbage collection. The memory can be freed with
@code{free}.
There is also @code{scm_gc_realloc} and @code{scm_realloc}, to be used
in place of @code{realloc} when appropriate, @code{scm_gc_calloc} and
@code{scm_calloc}, to be used in place of @code{calloc} when
appropriate.
For really specialized needs, take at look at
@code{scm_gc_register_collectable_memory} and
@code{scm_gc_unregister_collectable_memory}.
@deftypefn {C Function} {void *} scm_malloc (size_t @var{size})
@deftypefnx {C Function} {void *} scm_calloc (size_t @var{size})
Allocate @var{size} bytes of memory and return a pointer to it. When
@var{size} is 0, return @code{NULL}. When not enough memory is
available, signal an error. This function runs the GC to free up some
memory when it deems it appropriate.
The memory is allocated by the libc @code{malloc} function and can be
freed with @code{free}. There is no @code{scm_free} function to go
with @code{scm_malloc} to make it easier to pass memory back and forth
between different modules.
The function @code{scm_calloc} is similar to @code{scm_malloc}, but
initializes the block of memory to zero as well.
@end deftypefn
@deftypefn {C Function} {void *} scm_realloc (void *@var{mem}, size_t @var{new_size})
Change the size of the memory block at @var{mem} to @var{new_size} and
return its new location. When @var{new_size} is 0, this is the same
as calling @code{free} on @var{mem} and @code{NULL} is returned. When
@var{mem} is @code{NULL}, this function behaves like @code{scm_malloc}
and allocates a new block of size @var{new_size}.
When not enough memory is available, signal an error. This function
runs the GC to free up some memory when it deems it appropriate.
@end deftypefn
@deftypefn {C Function} void scm_gc_register_collectable_memory (void *@var{mem}, size_t @var{size}, const char *@var{what})
Informs the GC that the memory at @var{mem} of size @var{size} can
potentially be freed during a GC. That is, announce that @var{mem} is
part of a GC controlled object and when the GC happens to free that
object, @var{size} bytes will be freed along with it. The GC will
@strong{not} free the memory itself, it will just know that so-and-so
much bytes of memory are associated with GC controlled objects and the
memory system figures this into its decisions when to run a GC.
@var{mem} does not need to come from @code{scm_malloc}. You can only
call this function once for every memory block.
The @var{what} argument is used for statistical purposes. It should
describe the type of object that the memory will be used for so that
users can identify just what strange objects are eating up their
memory.
@end deftypefn
@deftypefn {C Function} void scm_gc_unregister_collectable_memory (void *@var{mem}, size_t @var{size})
Informs the GC that the memory at @var{mem} of size @var{size} is no
longer associated with a GC controlled object. You must take care to
match up every call to @code{scm_gc_register_collectable_memory} with
a call to @code{scm_gc_unregister_collectable_memory}. If you don't do
this, the GC might have a wrong impression of what is going on and run
much less efficiently than it could.
@end deftypefn
@deftypefn {C Function} {void *} scm_gc_malloc (size_t @var{size}, const char *@var{what})
@deftypefnx {C Function} {void *} scm_gc_realloc (void *@var{mem}, size_t @var{old_size}, size_t @var{new_size}, const char *@var{what});
@deftypefnx {C Function} {void *} scm_gc_calloc (size_t @var{size}, const char *@var{what})
Like @code{scm_malloc}, @code{scm_realloc} or @code{scm_calloc}, but
also call @code{scm_gc_register_collectable_memory}. Note that you
need to pass the old size of a reallocated memory block as well. See
below for a motivation.
@end deftypefn
@deftypefn {C Function} void scm_gc_free (void *@var{mem}, size_t @var{size}, const char *@var{what})
Like @code{free}, but also call @code{scm_gc_unregister_collectable_memory}.
Note that you need to explicitely pass the @var{size} parameter. This
is done since it should normally be easy to provide this parameter
(for memory that is associated with GC controlled objects) and this
frees us from tracking this value in the GC itself, which will keep
the memory management overhead very low.
@end deftypefn
@deffn {Scheme Procedure} malloc-stats
Return an alist ((@var{what} . @var{n}) ...) describing number
of malloced objects.
@var{what} is the second argument to @code{scm_gc_malloc},
@var{n} is the number of objects of that type currently
allocated.
@end deffn
@subsubsection Upgrading from scm_must_malloc et al.
Version 1.6 of Guile and earlier did not have the functions from the
previous section. In their place, it had the functions
@code{scm_must_malloc}, @code{scm_must_realloc} and
@code{scm_must_free}. This section explains why we want you to stop
using them, and how to do this.
@findex scm_must_malloc
@findex scm_must_realloc
@findex scm_must_calloc
@findex scm_must_free
The functions @code{scm_must_malloc} and @code{scm_must_realloc}
behaved like @code{scm_gc_malloc} and @code{scm_gc_realloc} do now,
respectively. They would inform the GC about the newly allocated
memory via the internal equivalent of
@code{scm_gc_register_collectable_memory}. However,
@code{scm_must_free} did not unregister the memory it was about to
free. The usual way to unregister memory was to return its size from
a smob free function.
This disconnectedness of the actual freeing of memory and reporting
this to the GC proved to be bad in practice. It was easy to make
mistakes and report the wrong size because allocating and freeing was
not done with symmetric code, and because it is cumbersome to compute
the total size of nested data structures that were freed with multiple
calls to @code{scm_must_free}. Additionally, there was no equivalent
to @code{scm_malloc}, and it was tempting to just use
@code{scm_must_malloc} and never to tell the GC that the memory has
been freed.
The effect was that the internal statistics kept by the GC drifted out
of sync with reality and could even overflow in long running programs.
When this happened, the result was a dramatic increase in (senseless)
GC activity which would effectively stop the program dead.
@findex scm_done_malloc
@findex scm_done_free
The functions @code{scm_done_malloc} and @code{scm_done_free} were
introduced to help restore balance to the force, but existing bugs did
not magically disappear, of course.
Therefore we decided to force everybody to review their code by
deprecating the existing functions and introducing new ones in their
place that are hopefully easier to use correctly.
For every use of @code{scm_must_malloc} you need to decide whether to
use @code{scm_malloc} or @code{scm_gc_malloc} in its place. When the
memory block is not part of a smob or some other Scheme object whose
lifetime is ultimately managed by the garbage collector, use
@code{scm_malloc} and @code{free}. When it is part of a smob, use
@code{scm_gc_malloc} and change the smob free function to use
@code{scm_gc_free} instead of @code{scm_must_free} or @code{free} and
make it return zero.
The important thing is to always pair @code{scm_malloc} with
@code{free}; and to always pair @code{scm_gc_malloc} with
@code{scm_gc_free}.
The same reasoning applies to @code{scm_must_realloc} and
@code{scm_realloc} versus @code{scm_gc_realloc}.
@node Weak References
@subsection Weak References
[FIXME: This chapter is based on Mikael Djurfeldt's answer to a
question by Michael Livshin. Any mistakes are not theirs, of course. ]
Weak references let you attach bookkeeping information to data so that
the additional information automatically disappears when the original
data is no longer in use and gets garbage collected. In a weak key hash,
the hash entry for that key disappears as soon as the key is no longer
referenced from anywhere else. For weak value hashes, the same happens
as soon as the value is no longer in use. Entries in a doubly weak hash
disappear when either the key or the value are not used anywhere else
anymore.
Object properties offer the same kind of functionality as weak key
hashes in many situations. (@pxref{Object Properties})
Here's an example (a little bit strained perhaps, but one of the
examples is actually used in Guile):
Assume that you're implementing a debugging system where you want to
associate information about filename and position of source code
expressions with the expressions themselves.
Hashtables can be used for that, but if you use ordinary hash tables
it will be impossible for the scheme interpreter to "forget" old
source when, for example, a file is reloaded.
To implement the mapping from source code expressions to positional
information it is necessary to use weak-key tables since we don't want
the expressions to be remembered just because they are in our table.
To implement a mapping from source file line numbers to source code
expressions you would use a weak-value table.
To implement a mapping from source code expressions to the procedures
they constitute a doubly-weak table has to be used.
@menu
* Weak key hashes::
* Weak vectors::
@end menu
@node Weak key hashes
@subsubsection Weak key hashes
@deffn {Scheme Procedure} make-weak-key-hash-table size
@deffnx {Scheme Procedure} make-weak-value-hash-table size
@deffnx {Scheme Procedure} make-doubly-weak-hash-table size
@deffnx {C Function} scm_make_weak_key_hash_table (size)
@deffnx {C Function} scm_make_weak_value_hash_table (size)
@deffnx {C Function} scm_make_doubly_weak_hash_table (size)
Return a weak hash table with @var{size} buckets. As with any
hash table, choosing a good size for the table requires some
caution.
You can modify weak hash tables in exactly the same way you
would modify regular hash tables. (@pxref{Hash Tables})
@end deffn
@deffn {Scheme Procedure} weak-key-hash-table? obj
@deffnx {Scheme Procedure} weak-value-hash-table? obj
@deffnx {Scheme Procedure} doubly-weak-hash-table? obj
@deffnx {C Function} scm_weak_key_hash_table_p (obj)
@deffnx {C Function} scm_weak_value_hash_table_p (obj)
@deffnx {C Function} scm_doubly_weak_hash_table_p (obj)
Return @code{#t} if @var{obj} is the specified weak hash
table. Note that a doubly weak hash table is neither a weak key
nor a weak value hash table.
@end deffn
@deffn {Scheme Procedure} make-weak-value-hash-table k
@end deffn
@deffn {Scheme Procedure} weak-value-hash-table? x
@end deffn
@deffn {Scheme Procedure} make-doubly-weak-hash-table k
@end deffn
@deffn {Scheme Procedure} doubly-weak-hash-table? x
@end deffn
@node Weak vectors
@subsubsection Weak vectors
Weak vectors are mainly useful in Guile's implementation of weak hash
tables.
@deffn {Scheme Procedure} make-weak-vector size [fill]
@deffnx {C Function} scm_make_weak_vector (size, fill)
Return a weak vector with @var{size} elements. If the optional
argument @var{fill} is given, all entries in the vector will be
set to @var{fill}. The default value for @var{fill} is the
empty list.
@end deffn
@deffn {Scheme Procedure} weak-vector . l
@deffnx {Scheme Procedure} list->weak-vector l
@deffnx {C Function} scm_weak_vector (l)
Construct a weak vector from a list: @code{weak-vector} uses
the list of its arguments while @code{list->weak-vector} uses
its only argument @var{l} (a list) to construct a weak vector
the same way @code{list->vector} would.
@end deffn
@deffn {Scheme Procedure} weak-vector? obj
@deffnx {C Function} scm_weak_vector_p (obj)
Return @code{#t} if @var{obj} is a weak vector. Note that all
weak hashes are also weak vectors.
@end deffn
@node Guardians
@subsection Guardians
@deffn {Scheme Procedure} make-guardian [greedy?]
@deffnx {C Function} scm_make_guardian (greedy_p)
Create a new guardian.
A guardian protects a set of objects from garbage collection,
allowing a program to apply cleanup or other actions.
@code{make-guardian} returns a procedure representing the guardian.
Calling the guardian procedure with an argument adds the
argument to the guardian's set of protected objects.
Calling the guardian procedure without an argument returns
one of the protected objects which are ready for garbage
collection, or @code{#f} if no such object is available.
Objects which are returned in this way are removed from
the guardian.
@code{make-guardian} takes one optional argument that says whether the
new guardian should be greedy or sharing. If there is any chance
that any object protected by the guardian may be resurrected,
then you should make the guardian greedy (this is the default).
See R. Kent Dybvig, Carl Bruggeman, and David Eby (1993)
"Guardians in a Generation-Based Garbage Collector".
ACM SIGPLAN Conference on Programming Language Design
and Implementation, June 1993.
(the semantics are slightly different at this point, but the
paper still (mostly) accurately describes the interface).
@end deffn
@deffn {Scheme Procedure} destroy-guardian! guardian
@deffnx {C Function} scm_destroy_guardian_x (guardian)
Destroys @var{guardian}, by making it impossible to put any more
objects in it or get any objects from it. It also unguards any
objects guarded by @var{guardian}.
@end deffn
@deffn {Scheme Procedure} guardian-greedy? guardian
@deffnx {C Function} scm_guardian_greedy_p (guardian)
Return @code{#t} if @var{guardian} is a greedy guardian, otherwise @code{#f}.
@end deffn
@deffn {Scheme Procedure} guardian-destroyed? guardian
@deffnx {C Function} scm_guardian_destroyed_p (guardian)
Return @code{#t} if @var{guardian} has been destroyed, otherwise @code{#f}.
@end deffn
@page
@node Objects
@section Objects
@deffn {Scheme Procedure} entity? obj
@deffnx {C Function} scm_entity_p (obj)
Return @code{#t} if @var{obj} is an entity.
@end deffn
@deffn {Scheme Procedure} operator? obj
@deffnx {C Function} scm_operator_p (obj)
Return @code{#t} if @var{obj} is an operator.
@end deffn
@deffn {Scheme Procedure} set-object-procedure! obj proc
@deffnx {C Function} scm_set_object_procedure_x (obj, proc)
Set the object procedure of @var{obj} to @var{proc}.
@var{obj} must be either an entity or an operator.
@end deffn
@deffn {Scheme Procedure} make-class-object metaclass layout
@deffnx {C Function} scm_make_class_object (metaclass, layout)
Create a new class object of class @var{metaclass}, with the
slot layout specified by @var{layout}.
@end deffn
@deffn {Scheme Procedure} make-subclass-object class layout
@deffnx {C Function} scm_make_subclass_object (class, layout)
Create a subclass object of @var{class}, with the slot layout
specified by @var{layout}.
@end deffn
@c Local Variables:
@c TeX-master: "guile.texi"
@c End:

1042
doc/ref/api-modules.texi Normal file

File diff suppressed because it is too large Load diff

731
doc/ref/api-options.texi Normal file
View file

@ -0,0 +1,731 @@
@c -*-texinfo-*-
@c This is part of the GNU Guile Reference Manual.
@c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004
@c Free Software Foundation, Inc.
@c See the file guile.texi for copying conditions.
@page
@node 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>}, 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]
@deffnx {C Function} scm_search_path (path, filename, extensions)
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}.
@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. The value for
@code{buildstamp} is the output of the date(1) command.
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
@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{Array Mapping}).
@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 or 'prefix
case-insensitive no Convert symbols to lower case.
positions yes Record positions of source code expressions.
copy no Copy source code expressions.
@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
@smalllisp
(read-enable 'case-insensitive)
@end smalllisp
@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
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.
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
If cheap traps are enabled [debug-options interface], @var{cont} is a
debug object, otherwise it is a restartable continuation.
@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
If cheap traps are enabled [debug-options interface], @var{cont} is a
debug object, otherwise it is a restartable continuation.
@var{retval} is the return value.
@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 *Flyweight representation of the stack at traps.
@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}. For a
description of what this means, see @ref{Proper tail
recursion,,,r5rs,The Revised^5 Report on Scheme}.
@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 or 'prefix
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 *Flyweight representation of the stack at traps.
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:

112
doc/ref/api-overview.texi Normal file
View file

@ -0,0 +1,112 @@
@c -*-texinfo-*-
@c This is part of the GNU Guile Reference Manual.
@c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004
@c Free Software Foundation, Inc.
@c See the file guile.texi for copying conditions.
@page
@node 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.

859
doc/ref/api-procedures.texi Normal file
View file

@ -0,0 +1,859 @@
@c -*-texinfo-*-
@c This is part of the GNU Guile Reference Manual.
@c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004
@c Free Software Foundation, Inc.
@c See the file guile.texi for copying conditions.
@page
@node Procedures and Macros
@section Procedures and Macros
@menu
* Lambda:: Basic procedure creation using lambda.
* Primitive Procedures:: Procedures defined in C.
* Optional Arguments:: Handling keyword, optional and rest arguments.
* Procedure Properties:: Procedure properties and meta-information.
* Procedures with Setters:: Procedures with setters.
* Macros:: Lisp style macro definitions.
* Syntax Rules:: Support for R5RS @code{syntax-rules}.
* Syntax Case:: Support for the @code{syntax-case} system.
* Internal Macros:: Guile's internal representation.
@end menu
@node Lambda
@subsection Lambda: Basic Procedure Creation
@cindex lambda
@c FIXME::martin: Review me!
A @code{lambda} expression evaluates to a procedure. The environment
which is in effect when a @code{lambda} expression is evaluated is
enclosed in the newly created procedure, this is referred to as a
@dfn{closure} (@pxref{About Closure}).
When a procedure created by @code{lambda} is called with some actual
arguments, the environment enclosed in the procedure is extended by
binding the variables named in the formal argument list to new locations
and storing the actual arguments into these locations. Then the body of
the @code{lambda} expression is evaluation sequentially. The result of
the last expression in the procedure body is then the result of the
procedure invocation.
The following examples will show how procedures can be created using
@code{lambda}, and what you can do with these procedures.
@lisp
(lambda (x) (+ x x)) @result{} @r{a procedure}
((lambda (x) (+ x x)) 4) @result{} 8
@end lisp
The fact that the environment in effect when creating a procedure is
enclosed in the procedure is shown with this example:
@lisp
(define add4
(let ((x 4))
(lambda (y) (+ x y))))
(add4 6) @result{} 10
@end lisp
@deffn syntax lambda formals body
@var{formals} should be a formal argument list as described in the
following table.
@table @code
@item (@var{variable1} @dots{})
The procedure takes a fixed number of arguments; when the procedure is
called, the arguments will be stored into the newly created location for
the formal variables.
@item @var{variable}
The procedure takes any number of arguments; when the procedure is
called, the sequence of actual arguments will converted into a list and
stored into the newly created location for the formal variable.
@item (@var{variable1} @dots{} @var{variablen} . @var{variablen+1})
If a space-delimited period precedes the last variable, then the
procedure takes @var{n} or more variables where @var{n} is the number
of formal arguments before the period. There must be at least one
argument before the period. The first @var{n} actual arguments will be
stored into the newly allocated locations for the first @var{n} formal
arguments and the sequence of the remaining actual arguments is
converted into a list and the stored into the location for the last
formal argument. If there are exactly @var{n} actual arguments, the
empty list is stored into the location of the last formal argument.
@end table
The list in @var{variable} or @var{variablen+1} is always newly
created and the procedure can modify it if desired. This is the case
even when the procedure is invoked via @code{apply}, the required part
of the list argument there will be copied (@pxref{Fly Evaluation,,
Procedures for On the Fly Evaluation}).
@var{body} is a sequence of Scheme expressions which are evaluated in
order when the procedure is invoked.
@end deffn
@node Primitive Procedures
@subsection Primitive Procedures
@cindex primitives
@cindex primitive procedures
Procedures written in C can be registered for use from Scheme,
provided they take only arguments of type @code{SCM} and return
@code{SCM} values. @code{scm_c_define_gsubr} is likely to be the most
useful mechanism, combining the process of registration
(@code{scm_c_make_gsubr}) and definition (@code{scm_define}).
@deftypefun SCM scm_c_make_gsubr (const char *name, int req, int opt, int rst, fcn)
Register a C procedure @var{FCN} as a ``subr'' --- a primitive
subroutine that can be called from Scheme. It will be associated with
the given @var{name} but no environment binding will be created. The
arguments @var{req}, @var{opt} and @var{rst} specify the number of
required, optional and ``rest'' arguments respectively. The total
number of these arguments should match the actual number of arguments
to @var{fcn}. The number of rest arguments should be 0 or 1.
@code{scm_c_make_gsubr} returns a value of type @code{SCM} which is a
``handle'' for the procedure.
@end deftypefun
@deftypefun SCM scm_c_define_gsubr (const char *name, int req, int opt, int rst, fcn)
Register a C procedure @var{FCN}, as for @code{scm_c_make_gsubr}
above, and additionally create a top-level Scheme binding for the
procedure in the ``current environment'' using @code{scm_define}.
@code{scm_c_define_gsubr} returns a handle for the procedure in the
same way as @code{scm_c_make_gsubr}, which is usually not further
required.
@end deftypefun
@code{scm_c_make_gsubr} and @code{scm_c_define_gsubr} automatically
use @code{scm_c_make_subr} and also @code{scm_makcclo} if necessary.
It is advisable to use the gsubr variants since they provide a
slightly higher-level abstraction of the Guile implementation.
@node Optional Arguments
@subsection Optional Arguments
@c FIXME::martin: Review me!
Scheme procedures, as defined in R5RS, can either handle a fixed number
of actual arguments, or a fixed number of actual arguments followed by
arbitrarily many additional arguments. Writing procedures of variable
arity can be useful, but unfortunately, the syntactic means for handling
argument lists of varying length is a bit inconvenient. It is possible
to give names to the fixed number of argument, but the remaining
(optional) arguments can be only referenced as a list of values
(@pxref{Lambda}).
Guile comes with the module @code{(ice-9 optargs)}, which makes using
optional arguments much more convenient. In addition, this module
provides syntax for handling keywords in argument lists
(@pxref{Keywords}).
Before using any of the procedures or macros defined in this section,
you have to load the module @code{(ice-9 optargs)} with the statement:
@cindex @code{optargs}
@lisp
(use-modules (ice-9 optargs))
@end lisp
@menu
* let-optional Reference:: Locally binding optional arguments.
* let-keywords Reference:: Locally binding keywords arguments.
* lambda* Reference:: Creating advanced argument handling procedures.
* define* Reference:: Defining procedures and macros.
@end menu
@node let-optional Reference
@subsubsection let-optional Reference
@c FIXME::martin: Review me!
The syntax @code{let-optional} and @code{let-optional*} are for
destructuring rest argument lists and giving names to the various list
elements. @code{let-optional} binds all variables simultaneously, while
@code{let-optional*} binds them sequentially, consistent with @code{let}
and @code{let*} (@pxref{Local Bindings}).
@deffn {library syntax} let-optional rest-arg (binding @dots{}) expr @dots{}
@deffnx {library syntax} let-optional* rest-arg (binding @dots{}) expr @dots{}
These two macros give you an optional argument interface that is very
@dfn{Schemey} and introduces no fancy syntax. They are compatible with
the scsh macros of the same name, but are slightly extended. Each of
@var{binding} may be of one of the forms @var{var} or @code{(@var{var}
@var{default-value})}. @var{rest-arg} should be the rest-argument of the
procedures these are used from. The items in @var{rest-arg} are
sequentially bound to the variable names are given. When @var{rest-arg}
runs out, the remaining vars are bound either to the default values or
@code{#f} if no default value was specified. @var{rest-arg} remains
bound to whatever may have been left of @var{rest-arg}.
After binding the variables, the expressions @var{expr} @dots{} are
evaluated in order.
@end deffn
@node let-keywords Reference
@subsubsection let-keywords Reference
@c FIXME::martin: Review me!
@code{let-keywords} and @code{let-keywords*} are used for extracting
values from argument lists which use keywords instead of argument
position for binding local variables to argument values.
@code{let-keywords} binds all variables simultaneously, while
@code{let-keywords*} binds them sequentially, consistent with @code{let}
and @code{let*} (@pxref{Local Bindings}).
@deffn {library syntax} let-keywords rest-arg allow-other-keys? (binding @dots{}) expr @dots{}
@deffnx {library syntax} let-keywords rest-arg allow-other-keys? (binding @dots{}) expr @dots{}
These macros pick out keyword arguments from @var{rest-arg}, but do not
modify it. This is consistent at least with Common Lisp, which
duplicates keyword arguments in the rest argument. More explanation of what
keyword arguments in a lambda list look like can be found below in
the documentation for @code{lambda*}
(@pxref{lambda* Reference}). @var{binding}s can have the same form as
for @code{let-optional}. If @var{allow-other-keys?} is false, an error
will be thrown if anything that looks like a keyword argument but does
not match a known keyword parameter will result in an error.
After binding the variables, the expressions @var{expr} @dots{} are
evaluated in order.
@end deffn
@node lambda* Reference
@subsubsection lambda* Reference
@c FIXME::martin: Review me!
When using optional and keyword argument lists, using @code{lambda} for
creating procedures and using @code{let-optional} or @code{let-keywords}
is a bit lengthy. Therefore, @code{lambda*} is provided, which combines
the features of those macros into a single convenient syntax.
For quick reference, here is the syntax of the formal argument list for
@code{lambda*} (brackets are used to indicate grouping only):
@example
ext-param-list ::= [identifier]* [#:optional [ext-var-decl]+]?
[#:key [ext-var-decl]+ [#:allow-other-keys]?]?
[[#:rest identifier]|[. identifier]]?
ext-var-decl ::= identifier | ( identifier expression )
@end example
The characters `*', `+' and `?' are not to be taken literally; they mean
respectively, zero or more occurrences, one or more occurrences, and one
or zero occurrences.
@deffn {library syntax} lambda* formals body
@code{lambda*} creates a procedure that takes optional arguments. These
are specified by putting them inside brackets at the end of the
parameter list, but before any dotted rest argument. For example,
@lisp
(lambda* (a b #:optional c d . e) '())
@end lisp
creates a procedure with fixed arguments @var{a} and @var{b}, optional
arguments @var{c} and @var{d}, and rest argument @var{e}. If the
optional arguments are omitted in a call, the variables for them are
bound to @code{#f}.
@code{lambda*} can also take keyword arguments. For example, a procedure
defined like this:
@lisp
(lambda* (#:key xyzzy larch) '())
@end lisp
can be called with any of the argument lists @code{(#:xyzzy 11)}
@code{(#:larch 13)} @code{(#:larch 42 #:xyzzy 19)} @code{()}. Whichever
arguments are given as keywords are bound to values.
Optional and keyword arguments can also be given default values
which they take on when they are not present in a call, by giving a
two-item list in place of an optional argument, for example in:
@lisp
(lambda* (foo #:optional (bar 42) #:key (baz 73))
(list foo bar baz))
@end lisp
@var{foo} is a fixed argument, @var{bar} is an optional argument with
default value 42, and baz is a keyword argument with default value 73.
Default value expressions are not evaluated unless they are needed and
until the procedure is called.
@code{lambda*} also supports two more special parameter list keywords.
@code{lambda*}-defined procedures now throw an error by default if a
keyword other than one of those specified is found in the actual
passed arguments. However, specifying @code{#:allow-other-keys}
immediately after the keyword argument declarations restores the
previous behavior of ignoring unknown keywords. @code{lambda*} also now
guarantees that if the same keyword is passed more than once, the
last one passed is the one that takes effect. For example,
@lisp
((lambda* (#:key (heads 0) (tails 0)) (display (list heads tails)))
#:heads 37 #:tails 42 #:heads 99)
@end lisp
would result in (99 47) being displayed.
@code{#:rest} is also now provided as a synonym for the dotted syntax
rest argument. The argument lists @code{(a . b)} and @code{(a #:rest b)}
are equivalent in all respects to @code{lambda*}. This is provided for
more similarity to DSSSL, MIT-Scheme and Kawa among others, as well as
for refugees from other Lisp dialects.
@end deffn
@node define* Reference
@subsubsection define* Reference
@c FIXME::martin: Review me!
Just like @code{define} has a shorthand notation for defining procedures
(@pxref{Lambda Alternatives}), @code{define*} is provided as an
abbreviation of the combination of @code{define} and @code{lambda*}.
@code{define*-public} is the @code{lambda*} version of
@code{define-public}; @code{defmacro*} and @code{defmacro*-public} exist
for defining macros with the improved argument list handling
possibilities. The @code{-public} versions not only define the
procedures/macros, but also export them from the current module.
@deffn {library syntax} define* formals body
@deffnx {library syntax} define*-public formals body
@code{define*} and @code{define*-public} support optional arguments with
a similar syntax to @code{lambda*}. They also support arbitrary-depth
currying, just like Guile's define. Some examples:
@lisp
(define* (x y #:optional a (z 3) #:key w . u)
(display (list y z u)))
@end lisp
defines a procedure @code{x} with a fixed argument @var{y}, an optional
argument @var{a}, another optional argument @var{z} with default value 3,
a keyword argument @var{w}, and a rest argument @var{u}.
@lisp
(define-public* ((foo #:optional bar) #:optional baz) '())
@end lisp
This illustrates currying. A procedure @code{foo} is defined, which,
when called with an optional argument @var{bar}, returns a procedure
that takes an optional argument @var{baz}.
Of course, @code{define*[-public]} also supports @code{#:rest} and
@code{#:allow-other-keys} in the same way as @code{lambda*}.
@end deffn
@deffn {library syntax} defmacro* name formals body
@deffnx {library syntax} defmacro*-public name formals body
These are just like @code{defmacro} and @code{defmacro-public} except that they
take @code{lambda*}-style extended parameter lists, where @code{#:optional},
@code{#:key}, @code{#:allow-other-keys} and @code{#:rest} are allowed with the usual
semantics. Here is an example of a macro with an optional argument:
@lisp
(defmacro* transmorgify (a #:optional b)
(a 1))
@end lisp
@end deffn
@node Procedure Properties
@subsection Procedure Properties and Meta-information
@c FIXME::martin: Review me!
Procedures always have attached the environment in which they were
created and information about how to apply them to actual arguments. In
addition to that, properties and meta-information can be stored with
procedures. The procedures in this section can be used to test whether
a given procedure satisfies a condition; and to access and set a
procedure's property.
The first group of procedures are predicates to test whether a Scheme
object is a procedure, or a special procedure, respectively.
@code{procedure?} is the most general predicates, it returns @code{#t}
for any kind of procedure. @code{closure?} does not return @code{#t}
for primitive procedures, and @code{thunk?} only returns @code{#t} for
procedures which do not accept any arguments.
@rnindex procedure?
@deffn {Scheme Procedure} procedure? obj
@deffnx {C Function} scm_procedure_p (obj)
Return @code{#t} if @var{obj} is a procedure.
@end deffn
@deffn {Scheme Procedure} closure? obj
@deffnx {C Function} scm_closure_p (obj)
Return @code{#t} if @var{obj} is a closure.
@end deffn
@deffn {Scheme Procedure} thunk? obj
@deffnx {C Function} scm_thunk_p (obj)
Return @code{#t} if @var{obj} is a thunk.
@end deffn
@c FIXME::martin: Is that true?
@cindex procedure properties
Procedure properties are general properties to be attached to
procedures. These can be the name of a procedure or other relevant
information, such as debug hints.
@deffn {Scheme Procedure} procedure-name proc
@deffnx {C Function} scm_procedure_name (proc)
Return the name of the procedure @var{proc}
@end deffn
@deffn {Scheme Procedure} procedure-source proc
@deffnx {C Function} scm_procedure_source (proc)
Return the source of the procedure @var{proc}.
@end deffn
@deffn {Scheme Procedure} procedure-environment proc
@deffnx {C Function} scm_procedure_environment (proc)
Return the environment of the procedure @var{proc}.
@end deffn
@deffn {Scheme Procedure} procedure-properties proc
@deffnx {C Function} scm_procedure_properties (proc)
Return @var{obj}'s property list.
@end deffn
@deffn {Scheme Procedure} procedure-property obj key
@deffnx {C Function} scm_procedure_property (obj, key)
Return the property of @var{obj} with name @var{key}.
@end deffn
@deffn {Scheme Procedure} set-procedure-properties! proc alist
@deffnx {C Function} scm_set_procedure_properties_x (proc, alist)
Set @var{obj}'s property list to @var{alist}.
@end deffn
@deffn {Scheme Procedure} set-procedure-property! obj key value
@deffnx {C Function} scm_set_procedure_property_x (obj, key, value)
In @var{obj}'s property list, set the property named @var{key} to
@var{value}.
@end deffn
@cindex procedure documentation
Documentation for a procedure can be accessed with the procedure
@code{procedure-documentation}.
@deffn {Scheme Procedure} procedure-documentation proc
@deffnx {C Function} scm_procedure_documentation (proc)
Return the documentation string associated with @code{proc}. By
convention, if a procedure contains more than one expression and the
first expression is a string constant, that string is assumed to contain
documentation for that procedure.
@end deffn
@cindex source properties
@c FIXME::martin: Is the following true?
Source properties are properties which are related to the source code of
a procedure, such as the line and column numbers, the file name etc.
@deffn {Scheme Procedure} set-source-properties! obj plist
@deffnx {C Function} scm_set_source_properties_x (obj, plist)
Install the association list @var{plist} as the source property
list for @var{obj}.
@end deffn
@deffn {Scheme Procedure} set-source-property! obj key datum
@deffnx {C Function} scm_set_source_property_x (obj, key, datum)
Set the source property of object @var{obj}, which is specified by
@var{key} to @var{datum}. Normally, the key will be a symbol.
@end deffn
@deffn {Scheme Procedure} source-properties obj
@deffnx {C Function} scm_source_properties (obj)
Return the source property association list of @var{obj}.
@end deffn
@deffn {Scheme Procedure} source-property obj key
@deffnx {C Function} scm_source_property (obj, key)
Return the source property specified by @var{key} from
@var{obj}'s source property list.
@end deffn
@node Procedures with Setters
@subsection Procedures with Setters
@c FIXME::martin: Review me!
@c FIXME::martin: Document `operator struct'.
@cindex procedure with setter
@cindex setter
A @dfn{procedure with setter} is a special kind of procedure which
normally behaves like any accessor procedure, that is a procedure which
accesses a data structure. The difference is that this kind of
procedure has a so-called @dfn{setter} attached, which is a procedure
for storing something into a data structure.
Procedures with setters are treated specially when the procedure appears
in the special form @code{set!} (REFFIXME). How it works is best shown
by example.
Suppose we have a procedure called @code{foo-ref}, which accepts two
arguments, a value of type @code{foo} and an integer. The procedure
returns the value stored at the given index in the @code{foo} object.
Let @code{f} be a variable containing such a @code{foo} data
structure.@footnote{Working definitions would be:
@lisp
(define foo-ref vector-ref)
(define foo-set! vector-set!)
(define f (make-vector 2 #f))
@end lisp
}
@lisp
(foo-ref f 0) @result{} bar
(foo-ref f 1) @result{} braz
@end lisp
Also suppose that a corresponding setter procedure called
@code{foo-set!} does exist.
@lisp
(foo-set! f 0 'bla)
(foo-ref f 0) @result{} bla
@end lisp
Now we could create a new procedure called @code{foo}, which is a
procedure with setter, by calling @code{make-procedure-with-setter} with
the accessor and setter procedures @code{foo-ref} and @code{foo-set!}.
Let us call this new procedure @code{foo}.
@lisp
(define foo (make-procedure-with-setter foo-ref foo-set!))
@end lisp
@code{foo} can from now an be used to either read from the data
structure stored in @code{f}, or to write into the structure.
@lisp
(set! (foo f 0) 'dum)
(foo f 0) @result{} dum
@end lisp
@deffn {Scheme Procedure} make-procedure-with-setter procedure setter
@deffnx {C Function} scm_make_procedure_with_setter (procedure, setter)
Create a new procedure which behaves like @var{procedure}, but
with the associated setter @var{setter}.
@end deffn
@deffn {Scheme Procedure} procedure-with-setter? obj
@deffnx {C Function} scm_procedure_with_setter_p (obj)
Return @code{#t} if @var{obj} is a procedure with an
associated setter procedure.
@end deffn
@deffn {Scheme Procedure} procedure proc
@deffnx {C Function} scm_procedure (proc)
Return the procedure of @var{proc}, which must be either a
procedure with setter, or an operator struct.
@end deffn
@deffn {Scheme Procedure} setter proc
Return the setter of @var{proc}, which must be either a procedure with
setter or an operator struct.
@end deffn
@node Macros
@subsection Lisp Style Macro Definitions
@cindex macros
@cindex transformation
Macros are objects which cause the expression that they appear in to be
transformed in some way @emph{before} being evaluated. In expressions
that are intended for macro transformation, the identifier that names
the relevant macro must appear as the first element, like this:
@lisp
(@var{macro-name} @var{macro-args} @dots{})
@end lisp
In Lisp-like languages, the traditional way to define macros is very
similar to procedure definitions. The key differences are that the
macro definition body should return a list that describes the
transformed expression, and that the definition is marked as a macro
definition (rather than a procedure definition) by the use of a
different definition keyword: in Lisp, @code{defmacro} rather than
@code{defun}, and in Scheme, @code{define-macro} rather than
@code{define}.
@fnindex defmacro
@fnindex define-macro
Guile supports this style of macro definition using both @code{defmacro}
and @code{define-macro}. The only difference between them is how the
macro name and arguments are grouped together in the definition:
@lisp
(defmacro @var{name} (@var{args} @dots{}) @var{body} @dots{})
@end lisp
@noindent
is the same as
@lisp
(define-macro (@var{name} @var{args} @dots{}) @var{body} @dots{})
@end lisp
@noindent
The difference is analogous to the corresponding difference between
Lisp's @code{defun} and Scheme's @code{define}.
@code{false-if-exception}, from the @file{boot-9.scm} file in the Guile
distribution, is a good example of macro definition using
@code{defmacro}:
@lisp
(defmacro false-if-exception (expr)
`(catch #t
(lambda () ,expr)
(lambda args #f)))
@end lisp
@noindent
The effect of this definition is that expressions beginning with the
identifier @code{false-if-exception} are automatically transformed into
a @code{catch} expression following the macro definition specification.
For example:
@lisp
(false-if-exception (open-input-file "may-not-exist"))
@equiv{}
(catch #t
(lambda () (open-input-file "may-not-exist"))
(lambda args #f))
@end lisp
@node Syntax Rules
@subsection The R5RS @code{syntax-rules} System
@cindex R5RS syntax-rules system
R5RS defines an alternative system for macro and syntax transformations
using the keywords @code{define-syntax}, @code{let-syntax},
@code{letrec-syntax} and @code{syntax-rules}.
The main difference between the R5RS system and the traditional macros
of the previous section is how the transformation is specified. In
R5RS, rather than permitting a macro definition to return an arbitrary
expression, the transformation is specified in a pattern language that
@itemize @bullet
@item
does not require complicated quoting and extraction of components of the
source expression using @code{caddr} etc.
@item
is designed such that the bindings associated with identifiers in the
transformed expression are well defined, and such that it is impossible
for the transformed expression to construct new identifiers.
@end itemize
@noindent
The last point is commonly referred to as being @dfn{hygienic}: the R5RS
@code{syntax-case} system provides @dfn{hygienic macros}.
For example, the R5RS pattern language for the @code{false-if-exception}
example of the previous section looks like this:
@lisp
(syntax-rules ()
((_ expr)
(catch #t
(lambda () expr)
(lambda args #f))))
@end lisp
@cindex @code{syncase}
In Guile, the @code{syntax-rules} system is provided by the @code{(ice-9
syncase)} module. To make these facilities available in your code,
include the expression @code{(use-syntax (ice-9 syncase))} (@pxref{Using
Guile Modules}) before the first usage of @code{define-syntax} etc. If
you are writing a Scheme module, you can alternatively include the form
@code{#:use-syntax (ice-9 syncase)} in your @code{define-module}
declaration (@pxref{Creating Guile Modules}).
@menu
* Pattern Language:: The @code{syntax-rules} pattern language.
* Define-Syntax:: Top level syntax definitions.
* Let-Syntax:: Local syntax definitions.
@end menu
@node Pattern Language
@subsubsection The @code{syntax-rules} Pattern Language
@node Define-Syntax
@subsubsection Top Level Syntax Definitions
define-syntax: The gist is
(define-syntax <keyword> <transformer-spec>)
makes the <keyword> into a macro so that
(<keyword> ...)
expands at _compile_ or _read_ time (i.e. before any
evaluation begins) into some expression that is
given by the <transformer-spec>.
@node Let-Syntax
@subsubsection Local Syntax Definitions
@node Syntax Case
@subsection Support for the @code{syntax-case} System
@node Internal Macros
@subsection Internal Representation of Macros and Syntax
Internally, Guile uses three different flavors of macros. The three
flavors are called @dfn{acro} (or @dfn{syntax}), @dfn{macro} and
@dfn{mmacro}.
Given the expression
@lisp
(foo @dots{})
@end lisp
@noindent
with @code{foo} being some flavor of macro, one of the following things
will happen when the expression is evaluated.
@itemize @bullet
@item
When @code{foo} has been defined to be an @dfn{acro}, the procedure used
in the acro definition of @code{foo} is passed the whole expression and
the current lexical environment, and whatever that procedure returns is
the value of evaluating the expression. You can think of this a
procedure that receives its argument as an unevaluated expression.
@item
When @code{foo} has been defined to be a @dfn{macro}, the procedure used
in the macro definition of @code{foo} is passed the whole expression and
the current lexical environment, and whatever that procedure returns is
evaluated again. That is, the procedure should return a valid Scheme
expression.
@item
When @code{foo} has been defined to be a @dfn{mmacro}, the procedure
used in the mmacro definition of `foo' is passed the whole expression
and the current lexical environment, and whatever that procedure returns
replaces the original expression. Evaluation then starts over from the
new expression that has just been returned.
@end itemize
The key difference between a @dfn{macro} and a @dfn{mmacro} is that the
expression returned by a @dfn{mmacro} procedure is remembered (or
@dfn{memoized}) so that the expansion does not need to be done again
next time the containing code is evaluated.
The primitives @code{procedure->syntax}, @code{procedure->macro} and
@code{procedure->memoizing-macro} are used to construct acros, macros
and mmacros respectively. However, if you do not have a very special
reason to use one of these primitives, you should avoid them: they are
very specific to Guile's current implementation and therefore likely to
change. Use @code{defmacro}, @code{define-macro} (@pxref{Macros}) or
@code{define-syntax} (@pxref{Syntax Rules}) instead. (In low level
terms, @code{defmacro}, @code{define-macro} and @code{define-syntax} are
all implemented as mmacros.)
@deffn {Scheme Procedure} procedure->syntax code
@deffnx {C Function} scm_makacro (code)
Return a macro which, when a symbol defined to this value appears as the
first symbol in an expression, returns the result of applying @var{code}
to the expression and the environment.
@end deffn
@deffn {Scheme Procedure} procedure->macro code
@deffnx {C Function} scm_makmacro (code)
Return a macro which, when a symbol defined to this value appears as the
first symbol in an expression, evaluates the result of applying
@var{code} to the expression and the environment. For example:
@lisp
(define trace
(procedure->macro
(lambda (x env)
`(set! ,(cadr x) (tracef ,(cadr x) ',(cadr x))))))
(trace @i{foo})
@equiv{}
(set! @i{foo} (tracef @i{foo} '@i{foo})).
@end lisp
@end deffn
@deffn {Scheme Procedure} procedure->memoizing-macro code
@deffnx {C Function} scm_makmmacro (code)
Return a macro which, when a symbol defined to this value appears as the
first symbol in an expression, evaluates the result of applying
@var{code} to the expression and the environment.
@code{procedure->memoizing-macro} is the same as
@code{procedure->macro}, except that the expression returned by
@var{code} replaces the original macro expression in the memoized form
of the containing code.
@end deffn
In the following primitives, @dfn{acro} flavor macros are referred to
as @dfn{syntax transformers}.
@deffn {Scheme Procedure} macro? obj
@deffnx {C Function} scm_macro_p (obj)
Return @code{#t} if @var{obj} is a regular macro, a memoizing macro or a
syntax transformer.
@end deffn
@deffn {Scheme Procedure} macro-type m
@deffnx {C Function} scm_macro_type (m)
Return one of the symbols @code{syntax}, @code{macro} or
@code{macro!}, depending on whether @var{m} is a syntax
transformer, a regular macro, or a memoizing macro,
respectively. If @var{m} is not a macro, @code{#f} is
returned.
@end deffn
@deffn {Scheme Procedure} macro-name m
@deffnx {C Function} scm_macro_name (m)
Return the name of the macro @var{m}.
@end deffn
@deffn {Scheme Procedure} macro-transformer m
@deffnx {C Function} scm_macro_transformer (m)
Return the transformer of the macro @var{m}.
@end deffn
@deffn {Scheme Procedure} cons-source xorig x y
@deffnx {C Function} scm_cons_source (xorig, x, y)
Create and return a new pair whose car and cdr are @var{x} and @var{y}.
Any source properties associated with @var{xorig} are also associated
with the new pair.
@end deffn
@c Local Variables:
@c TeX-master: "guile.texi"
@c End:

863
doc/ref/api-scheduling.texi Normal file
View file

@ -0,0 +1,863 @@
@c -*-texinfo-*-
@c This is part of the GNU Guile Reference Manual.
@c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004
@c Free Software Foundation, Inc.
@c See the file guile.texi for copying conditions.
@page
@node Scheduling
@section Threads, Mutexes, Asyncs and Dynamic Roots
[FIXME: This is pasted in from Tom Lord's original guile.texi chapter
plus the Cygnus programmer's manual; it should be *very* carefully
reviewed and largely reorganized.]
@menu
* Arbiters:: Synchronization primitives.
* Asyncs:: Asynchronous procedure invocation.
* Dynamic Roots:: Root frames of execution.
* Threads:: Multiple threads of execution.
* Fluids:: Thread-local variables.
* Futures:: Delayed execution in new threads.
* Parallel Forms:: Parallel execution of forms.
@end menu
@node Arbiters
@subsection Arbiters
@cindex arbiters
@c FIXME::martin: Review me!
Arbiters are synchronization objects. They are created with
@code{make-arbiter}. Two or more threads can synchronize on an arbiter
by trying to lock it using @code{try-arbiter}. This call will succeed
if no other thread has called @code{try-arbiter} on the arbiter yet,
otherwise it will fail and return @code{#f}. Once an arbiter is
successfully locked, it cannot be locked by another thread until the
thread holding the arbiter calls @code{release-arbiter} to unlock it.
@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)
Return @code{#t} and lock the arbiter @var{arb} if the arbiter
was unlocked. Otherwise, return @code{#f}.
@end deffn
@deffn {Scheme Procedure} release-arbiter arb
@deffnx {C Function} scm_release_arbiter (arb)
Return @code{#t} and unlock the arbiter @var{arb} if the
arbiter was locked. Otherwise, return @code{#f}.
@end deffn
@node Asyncs
@subsection Asyncs
@cindex asyncs
@cindex user asyncs
@cindex system asyncs
Asyncs are a means of deferring the excution of Scheme code until it is
safe to do so.
Guile provides two kinds of asyncs that share the basic concept but are
otherwise quite different: system asyncs and user asyncs. System asyncs
are integrated into the core of Guile and are executed automatically
when the system is in a state to allow the execution of Scheme code.
For example, it is not possible to execute Scheme code in a POSIX signal
handler, but such a signal handler can queue a system async to be
executed in the near future, when it is safe to do so.
System asyncs can also be queued for threads other than the current one.
This way, you can cause threads to asynchronously execute arbitrary
code.
User asyncs offer a convenient means of queueing procedures for future
execution and triggering this execution. They will not be executed
automatically.
@menu
* System asyncs::
* User asyncs::
@end menu
@node System asyncs
@subsubsection System asyncs
To cause the future asynchronous execution of a procedure in a given
thread, use @code{system-async-mark}.
Automatic invocation of system asyncs can be temporarily disabled by
calling @code{call-with-blocked-asyncs}. This function works by
temporarily increasing the @emph{async blocking level} of the current
thread while a given procedure is running. The blocking level starts
out at zero, and whenever a safe point is reached, a blocking level
greater than zero will prevent the execution of queued asyncs.
Analogously, the procedure @code{call-with-unblocked-asyncs} will
temporarily decrease the blocking level of the current thread. You
can use it when you want to disable asyncs by default and only allow
them temporarily.
In addition to the C versions of @code{call-with-blocked-asyncs} and
@code{call-with-unblocked-asyncs}, C code can use
@code{scm_with_blocked_asyncs} and @code{scm_with_unblocked_asyncs}
inside a @dfn{frame} (@pxref{Frames}) to block or unblock system asyncs
temporarily.
@deffn {Scheme Procedure} system-async-mark proc [thread]
@deffnx {C Function} scm_system_async_mark (proc)
@deffnx {C Function} scm_system_async_mark_for_thread (proc, thread)
Mark @var{proc} (a procedure with zero arguments) for future execution
in @var{thread}. When @var{proc} has already been marked for
@var{thread} but has not been executed yet, this call has no effect.
When @var{thread} is omitted, the thread that called
@code{system-async-mark} is used.
This procedure is not safe to be called from signal handlers. Use
@code{scm_sigaction} or @code{scm_sigaction_for_thread} to install
signal handlers.
@end deffn
@c FIXME: The use of @deffnx for scm_c_call_with_blocked_asyncs and
@c scm_c_call_with_unblocked_asyncs puts "void" into the function
@c index. Would prefer to use @deftypefnx if makeinfo allowed that,
@c or a @deftypefn with an empty return type argument if it didn't
@c introduce an extra space.
@deffn {Scheme Procedure} call-with-blocked-asyncs proc
@deffnx {C Function} scm_call_with_blocked_asyncs (proc)
@deffnx {C Function} void *scm_c_call_with_blocked_asyncs (void * (*proc) (void *data), void *data)
@findex scm_c_call_with_blocked_asyncs
Call @var{proc} and block the execution of system asyncs by one level
for the current thread while it is running. Return the value returned
by @var{proc}. For the first two variants, call @var{proc} with no
arguments; for the third, call it with @var{data}.
@end deffn
@deffn {Scheme Procedure} call-with-unblocked-asyncs proc
@deffnx {C Function} scm_call_with_unblocked_asyncs (proc)
@deffnx {C Function} void *scm_c_call_with_unblocked_asyncs (void *(*p) (void *d), void *d)
@findex scm_c_call_with_unblocked_asyncs
Call @var{proc} and unblock the execution of system asyncs by one
level for the current thread while it is running. Return the value
returned by @var{proc}. For the first two variants, call @var{proc}
with no arguments; for the third, call it with @var{data}.
@end deffn
@deftypefn {C Function} void scm_frame_block_asyncs ()
This function must be used inside a pair of calls to
@code{scm_frame_begin} and @code{scm_frame_end} (@pxref{Frames}).
During the dynamic extent of the frame, asyncs are blocked by one level.
@end deftypefn
@deftypefn {C Function} void scm_frame_unblock_asyncs ()
This function must be used inside a pair of calls to
@code{scm_frame_begin} and @code{scm_frame_end} (@pxref{Frames}).
During the dynamic extent of the frame, asyncs are unblocked by one
level.
@end deftypefn
@node User asyncs
@subsubsection User asyncs
A user async is a pair of a thunk (a parameterless procedure) and a
mark. Setting the mark on a user async will cause the thunk to be
executed when the user async is passed to @code{run-asyncs}. Setting
the mark more than once is satisfied by one execution of the thunk.
User asyncs are created with @code{async}. They are marked with
@code{async-mark}.
@deffn {Scheme Procedure} async thunk
@deffnx {C Function} scm_async (thunk)
Create a new user async for the procedure @var{thunk}.
@end deffn
@deffn {Scheme Procedure} async-mark a
@deffnx {C Function} scm_async_mark (a)
Mark the user async @var{a} for future execution.
@end deffn
@deffn {Scheme Procedure} run-asyncs list_of_a
@deffnx {C Function} scm_run_asyncs (list_of_a)
Execute all thunks from the marked asyncs of the list @var{list_of_a}.
@end deffn
@node Dynamic Roots
@subsection Dynamic Roots
@cindex dynamic roots
A @dfn{dynamic root} is a root frame of Scheme evaluation.
The top-level repl, for example, is an instance of a dynamic root.
Each dynamic root has its own chain of dynamic-wind information. Each
has its own set of continuations, jump-buffers, and pending CATCH
statements which are inaccessible from the dynamic scope of any
other dynamic root.
In a thread-based system, each thread has its own dynamic root. Therefore,
continuations created by one thread may not be invoked by another.
Even in a single-threaded system, it is sometimes useful to create a new
dynamic root. For example, if you want to apply a procedure, but to
not allow that procedure to capture the current continuation, calling
the procedure under a new dynamic root will do the job.
@deffn {Scheme Procedure} call-with-dynamic-root thunk handler
@deffnx {C Function} scm_call_with_dynamic_root (thunk, handler)
Evaluate @code{(thunk)} in a new dynamic context, returning its value.
If an error occurs during evaluation, apply @var{handler} to the
arguments to the throw, just as @code{throw} would. If this happens,
@var{handler} is called outside the scope of the new root -- it is
called in the same dynamic context in which
@code{call-with-dynamic-root} was evaluated.
If @var{thunk} captures a continuation, the continuation is rooted at
the call to @var{thunk}. In particular, the call to
@code{call-with-dynamic-root} is not captured. Therefore,
@code{call-with-dynamic-root} always returns at most one time.
Before calling @var{thunk}, the dynamic-wind chain is un-wound back to
the root and a new chain started for @var{thunk}. Therefore, this call
may not do what you expect:
@lisp
;; Almost certainly a bug:
(with-output-to-port
some-port
(lambda ()
(call-with-dynamic-root
(lambda ()
(display 'fnord)
(newline))
(lambda (errcode) errcode))))
@end lisp
The problem is, on what port will @samp{fnord} be displayed? You
might expect that because of the @code{with-output-to-port} that
it will be displayed on the port bound to @code{some-port}. But it
probably won't -- before evaluating the thunk, dynamic winds are
unwound, including those created by @code{with-output-to-port}.
So, the standard output port will have been re-set to its default value
before @code{display} is evaluated.
(This function was added to Guile mostly to help calls to functions in C
libraries that can not tolerate non-local exits or calls that return
multiple times. If such functions call back to the interpreter, it should
be under a new dynamic root.)
@end deffn
@deffn {Scheme Procedure} dynamic-root
@deffnx {C Function} scm_dynamic_root ()
Return an object representing the current dynamic root.
These objects are only useful for comparison using @code{eq?}.
They are currently represented as numbers, but your code should
in no way depend on this.
@end deffn
@c begin (scm-doc-string "boot-9.scm" "quit")
@deffn {Scheme Procedure} quit [exit_val]
Throw back to the error handler of the current dynamic root.
If integer @var{exit_val} is specified and if Guile is being used
stand-alone and if quit is called from the initial dynamic-root,
@var{exit_val} becomes the exit status of the Guile process and the
process exits.
@end deffn
When Guile is run interactively, errors are caught from within the
read-eval-print loop. An error message will be printed and @code{abort}
called. A default set of signal handlers is installed, e.g., to allow
user interrupt of the interpreter.
It is possible to switch to a "batch mode", in which the interpreter
will terminate after an error and in which all signals cause their
default actions. Switching to batch mode causes any handlers installed
from Scheme code to be removed. An example of where this is useful is
after forking a new process intended to run non-interactively.
@c begin (scm-doc-string "boot-9.scm" "batch-mode?")
@deffn {Scheme Procedure} batch-mode?
Returns a boolean indicating whether the interpreter is in batch mode.
@end deffn
@c begin (scm-doc-string "boot-9.scm" "set-batch-mode?!")
@deffn {Scheme Procedure} set-batch-mode?! arg
If @var{arg} is true, switches the interpreter to batch mode.
The @code{#f} case has not been implemented.
@end deffn
@node Threads
@subsection Threads
@cindex threads
@cindex Guile threads
@cindex POSIX threads
Guile threads are implemented using POSIX threads, they run
pre-emptively and concurrently through both Scheme code and system
calls. The only exception is for garbage collection, where all
threads must rendezvous.
@menu
* Low level thread primitives::
* Higher level thread procedures::
* C level thread interface::
@end menu
@node Low level thread primitives
@subsubsection Low level thread primitives
@c NJFIXME no current mechanism for making sure that these docstrings
@c are in sync.
@c begin (texi-doc-string "guile" "call-with-new-thread")
@deffn {Scheme Procedure} call-with-new-thread thunk error-handler
Evaluate @code{(thunk)} in a new thread, and new dynamic context,
returning a new thread object representing the thread.
If an error occurs during evaluation, call error-handler, passing it
an error code. If this happens, the error-handler is called outside
the scope of the new root -- it is called in the same dynamic context
in which with-new-thread was evaluated, but not in the caller's
thread.
All the evaluation rules for dynamic roots apply to threads.
@end deffn
@c begin (texi-doc-string "guile" "join-thread")
@deffn {Scheme Procedure} join-thread thread
Suspend execution of the calling thread until the target @var{thread}
terminates, unless the target @var{thread} has already terminated.
@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
@c begin (texi-doc-string "guile" "make-mutex")
@deffn {Scheme Procedure} make-mutex
Create a new mutex object.
@end deffn
@c begin (texi-doc-string "guile" "lock-mutex")
@deffn {Scheme Procedure} lock-mutex mutex
Lock @var{mutex}. If the mutex is already locked, the calling thread
blocks until the mutex becomes available. The function returns when
the calling thread owns the lock on @var{mutex}. Locking a mutex that
a thread already owns will succeed right away and will not block the
thread. That is, Guile's mutexes are @emph{recursive}.
When a system async is activated for a thread that is blocked in a
call to @code{lock-mutex}, the waiting is interrupted and the async is
executed. When the async returns, the waiting is resumed.
@end deffn
@deffn {Scheme Procedure} try-mutex mutex
Try to lock @var{mutex}. If the mutex is already locked by someone
else, return @code{#f}. Else lock the mutex and return @code{#t}.
@end deffn
@c begin (texi-doc-string "guile" "unlock-mutex")
@deffn {Scheme Procedure} unlock-mutex mutex
Unlocks @var{mutex} if the calling thread owns the lock on
@var{mutex}. Calling unlock-mutex on a mutex not owned by the current
thread results in undefined behaviour. Once a mutex has been unlocked,
one thread blocked on @var{mutex} is awakened and grabs the mutex
lock. Every call to @code{lock-mutex} by this thread must be matched
with a call to @code{unlock-mutex}. Only the last call to
@code{unlock-mutex} will actually unlock the mutex.
@end deffn
@c begin (texi-doc-string "guile" "make-condition-variable")
@deffn {Scheme Procedure} make-condition-variable
Make a new condition variable.
@end deffn
@c begin (texi-doc-string "guile" "wait-condition-variable")
@deffn {Scheme Procedure} wait-condition-variable cond-var mutex [time]
Wait until @var{cond-var} 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.
@end deffn
@c begin (texi-doc-string "guile" "signal-condition-variable")
@deffn {Scheme Procedure} signal-condition-variable cond-var
Wake up one thread that is waiting for @var{cv}.
@end deffn
@c begin (texi-doc-string "guile" "broadcast-condition-variable")
@deffn {Scheme Procedure} broadcast-condition-variable cond-var
Wake up all threads that are waiting for @var{cv}.
@end deffn
@node Higher level thread procedures
@subsubsection Higher level thread procedures
@c new by ttn, needs review
Higher level thread procedures are available by loading the
@code{(ice-9 threads)} module. These provide standardized
thread creation and mutex interaction.
@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.
@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
@deffn macro with-mutex m [body@dots{}]
Lock mutex @var{m}, evaluate @var{body}, and then unlock @var{m}.
These sub-operations form the branches of a @code{dynamic-wind}.
@end deffn
@deffn macro monitor body@dots{}
Evaluate @var{body}, with a mutex locked so only one thread can
execute that code at any one time. Each @code{monitor} form has its
own private mutex and the locking is done as per @code{with-mutex}
above. The return value is the return from the last form in
@var{body}.
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 C level thread interface
@subsubsection C level thread interface
You can create and manage threads, mutexes, and condition variables
with the C versions of the primitives above. For example, you can
create a mutex with @code{scm_make_mutex} and lock it with
@code{scm_lock_mutex}. In addition to these primitives there is also
a second set of primitives for threading related things. These
functions and data types are only available from C and can not be
mixed with the first set from above. However, they might be more
efficient and can be used in situations where Scheme data types are
not allowed or are inconvenient to use.
Furthermore, they are the primitives that Guile relies on for its own
higher level threads. By reimplementing them, you can adapt Guile to
different low-level thread implementations.
C code in a thread must call a libguile function periodically. When
one thread finds garbage collection is required, it waits for all
threads to rendezvous before doing that GC. Such a rendezvous is
checked within libguile functions. If C code wants to sleep or block
in a thread it should use one of the libguile functions provided.
Only threads created by Guile can use the libguile functions. Threads
created directly with say @code{pthread_create} are unknown to Guile
and they cannot call libguile. The stack in such foreign threads is
not scanned during GC, so @code{SCM} values generally cannot be held
there.
@c FIXME:
@c
@c Describe SCM_TICK which can be called if no other libguile
@c function is being used by a C function.
@c
@c Describe "Guile mode", which a thread can enter and exit. There
@c are no functions for doing this yet.
@c
@c When in guile mode a thread can call libguile, is subject to the
@c tick rule, and its stack is scanned. When not in guile mode it
@c cannot call libguile, it doesn't have to tick, and its stack is
@c not scanned. The strange guile control flow things like
@c exceptions, continuations and asyncs only occur when in guile
@c mode.
@c
@c When guile mode is exited, the portion of the stack allocated
@c while it was in guile mode is still scanned. This portion may not
@c be modified when outside guile mode. The stack ends up
@c partitioned into alternating guile and non-guile regions.
@c
@c Leaving guile mode is convenient when running an extended
@c calculation not involving guile, since one doesn't need to worry
@c about SCM_TICK calls.
@deftp {C Data Type} scm_t_thread
This data type represents a thread, to be used with scm_thread_create,
etc.
@end deftp
@deftypefn {C Function} int scm_thread_create (scm_t_thread *t, void (*proc)(void *), void *data)
Create a new thread that will start by calling @var{proc}, passing it
@var{data}. A handle for the new thread is stored in @var{t}, which
must be non-NULL. The thread terminated when @var{proc} returns.
When the thread has not been detached, its handle remains valid after
is has terminated so that it can be used with @var{scm_thread_join},
for example. When it has been detached, the handle becomes invalid as
soon as the thread terminates.
@end deftypefn
@deftypefn {C Function} void scm_thread_detach (scm_t_thread t)
Detach the thread @var{t}. See @code{scm_thread_create}.
@end deftypefn
@deftypefn {C Function} void scm_thread_join (scm_t_thread t)
Wait for thread @var{t} to terminate. The thread must not have been
detached at the time that @code{scm_thread_join} is called, but it
might have been detached by the time it terminates.
@end deftypefn
@deftypefn {C Function} scm_t_thread scm_thread_self ()
Return the handle of the calling thread.
@end deftypefn
@deftp {C Data Type} scm_t_mutex
This data type represents a mutex, to be used with scm_mutex_init,
etc.
@end deftp
@deftypefn {C Function} void scm_mutex_init (scm_t_mutex *m)
Initialize the mutex structure pointed to by @var{m}.
@end deftypefn
@deftypefn {C Function} void scm_mutex_destroy (scm_t_mutex *m)
Deallocate all resources associated with @var{m}.
@end deftypefn
@deftypefn {C Function} void scm_mutex_lock (scm_t_mutex *m)
Lock the mutex @var{m}. When it is already locked by a different
thread, wait until it becomes available. Locking a mutex that is
already locked by the current threads is not allowd and results in
undefined behavior. The mutices are not guaranteed to be fair. That
is, a thread that attempts a lock after yourself might be granted it
before you.
@end deftypefn
@deftypefn {C Function} int scm_mutex_trylock (scm_t_mutex *m)
Lock @var{m} as with @code{scm_mutex_lock} but don't wait when this
does succeed immediately. Returns non-zero when the mutex could in
fact be locked , and zero when it is already locked by some other
thread.
@end deftypefn
@deftypefn {C Function} void scm_mutex_unlock (scm_t_mutex *m)
Unlock the mutex @var{m}. The mutex must have been locked by the
current thread, else the behavior is undefined.
@end deftypefn
@deftp {C Data Type} scm_t_cond
This data type represents a condition variable, to be used with
scm_cond_init, etc.
@end deftp
@deftypefn {C Function} void scm_cond_init (scm_t_cond *c)
Initialize the mutex structure pointed to by @var{c}.
@end deftypefn
@deftypefn {C Function} void scm_cond_destroy (scm_t_cond *c)
Deallocate all resources associated with @var{c}.
@end deftypefn
@deftypefn {C Function} void scm_cond_wait (scm_t_cond *c, scm_t_mutex *m)
Wait for @var{c} to be signalled. While waiting @var{m} is unlocked
and locked again before @code{scm_cond_wait} returns.
@end deftypefn
@deftypefn {C Function} void scm_cond_timedwait (scm_t_cond *c, scm_t_mutex *m, timespec *abstime)
Wait for @var{c} to be signalled as with @code{scm_cond_wait} but
don't wait longer than the point in time specified by @var{abstime}.
when the waiting is aborted, zero is returned; non-zero else.
@end deftypefn
@deftypefn {C Function} void scm_cond_signal (scm_t_cond *c)
Signal the condition variable @var{c}. When one or more threads are
waiting for it to be signalled, select one arbitrarily and let its
wait succeed.
@end deftypefn
@deftypefn {C Function} void scm_cond_broadcast (scm_t_cond *c)
Signal the condition variable @var{c}. When there are threads waiting
for it to be signalled, wake them all up and make all their waits
succeed.
@end deftypefn
@deftp {C Type} scm_t_key
This type represents a key for a thread-specific value.
@end deftp
@deftypefn {C Function} void scm_key_create (scm_t_key *keyp)
Create a new key for a thread-specific value. Each thread has its own
value associated to such a handle. The new handle is stored into
@var{keyp}, which must be non-NULL.
@end deftypefn
@deftypefn {C Function} void scm_key_delete (scm_t_key key)
This function makes @var{key} invalid as a key for thread-specific data.
@end deftypefn
@deftypefn {C Function} void scm_key_setspecific (scm_t_key key, const void *value)
Associate @var{value} with @var{key} in the calling thread.
@end deftypefn
@deftypefn {C Function} int scm_key_getspecific (scm_t_key key)
Return the value currently associated with @var{key} in the calling
thread. When @code{scm_key_setspecific} has not yet been called in
this thread with this key, @code{NULL} is returned.
@end deftypefn
@deftypefn {C Function} int scm_thread_select (...)
This function does the same thing as the system's @code{select}
function, but in a way that is friendly to the thread implementation.
You should call it in preference to the system @code{select}.
@end deftypefn
@node Fluids
@subsection Fluids
@cindex fluids
Fluids are objects to store values in. They have a few properties
which make them useful in certain situations: Fluids can have one
value per dynamic root (@pxref{Dynamic Roots}), so that changes to the
value in a fluid are only visible in the same dynamic root. Since
threads are executed in separate dynamic roots, fluids can be used for
thread local storage (@pxref{Threads}).
Fluids can 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 of a certain type (a smob) that can hold one SCM
value per dynamic root. That is, modifications to this value are
only visible to code that executes within the same dynamic root as
the modifying code. When a new dynamic root is constructed, it
inherits the values from its parent. Because each thread executes
in its own dynamic root, 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-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_frame_fluid (SCM fluid, SCM val)
This function must be used inside a pair of calls to
@code{scm_frame_begin} and @code{scm_frame_end} (@pxref{Frames}).
During the dynamic extent of the frame, the fluid @var{fluid} is set
to @var{val}.
More precisely, the value of the fluid is swapped with a `backup'
value whenever the frame is entered or left. The backup value is
initialized with the @var{val} argument.
@end deftypefn
@node Futures
@subsection Futures
@cindex futures
Futures are a convenient way to run a calculation in a new thread, and
only wait for the result when it's actually needed.
Futures are similar to promises (@pxref{Delayed Evaluation}), in that
they allow mainline code to continue immediately. But @code{delay}
doesn't evaluate at all until forced, whereas @code{future} starts
immediately in a new thread.
@deffn {syntax} future expr
Begin evaluating @var{expr} in a new thread, and return a ``future''
object representing the calculation.
@end deffn
@deffn {Scheme Procedure} make-future thunk
@deffnx {C Function} scm_make_future (thunk)
Begin evaluating the call @code{(@var{thunk})} in a new thread, and
return a ``future'' object representing the calculation.
@end deffn
@deffn {Scheme Procedure} future-ref f
@deffnx {C Function} scm_future_ref (f)
Return the value computed by the future @var{f}. If @var{f} has not
yet finished executing then wait for it to do so.
@end deffn
@node Parallel Forms
@subsection Parallel forms
@cindex parallel forms
The functions described in this section are available from
@example
(use-modules (ice-9 threads))
@end example
@deffn syntax parallel expr1 @dots{} exprN
Evaluate each @var{expr} expression in parallel, each in a new 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 a new 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 a new 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} new 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 new threads. No more
than @var{n} new 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 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:

45
doc/ref/api-scm.texi Normal file
View file

@ -0,0 +1,45 @@
@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

185
doc/ref/api-smobs.texi Normal file
View file

@ -0,0 +1,185 @@
@c -*-texinfo-*-
@c This is part of the GNU Guile Reference Manual.
@c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004
@c Free Software Foundation, Inc.
@c See the file guile.texi for copying conditions.
@page
@node Smobs
@section Smobs
This chapter contains reference information related to defining and
working with smobs. See @ref{Defining New Types (Smobs)} for a
tutorial-like introduction to smobs.
@deftypefun scm_t_bits scm_make_smob_type (const char *name, size_t size)
This function adds a new smob type, named @var{name}, with instance size
@var{size}, to the system. The return value is a tag that is used in
creating instances of the type.
If @var{size} is 0, the default @emph{free} function will do nothing.
If @var{size} is not 0, the default @emph{free} function will
deallocate the memory block pointed to by @code{SCM_SMOB_DATA} with
@code{scm_gc_free}. The @var{WHAT} parameter in the call to
@code{scm_gc_free} will be @var{NAME}.
Default values are provided for the @emph{mark}, @emph{free},
@emph{print}, and @emph{equalp} functions, as described in
@ref{Defining New Types (Smobs)}. If you want to customize any of
these functions, the call to @code{scm_make_smob_type} should be
immediately followed by calls to one or several of
@code{scm_set_smob_mark}, @code{scm_set_smob_free},
@code{scm_set_smob_print}, and/or @code{scm_set_smob_equalp}.
@end deftypefun
@deftypefn {C Function} void scm_set_smob_mark (scm_t_bits tc, SCM (*mark) (SCM obj))
This function sets the smob marking procedure for the smob type specified by
the tag @var{tc}. @var{tc} is the tag returned by @code{scm_make_smob_type}.
The @var{mark} procedure must cause @code{scm_gc_mark} to be called
for every @code{SCM} value that is directly referenced by the smob
instance @var{obj}. One of these @code{SCM} values can be returned
from the procedure and Guile will call @code{scm_gc_mark} for it.
This can be used to avoid deep recursions for smob instances that form
a list.
@end deftypefn
@deftypefn {C Function} void scm_set_smob_free (scm_t_bits tc, size_t (*free) (SCM obj))
This function sets the smob freeing procedure for the smob type
specified by the tag @var{tc}. @var{tc} is the tag returned by
@code{scm_make_smob_type}.
The @var{free} procedure must deallocate all resources that are
directly associated with the smob instance @var{OBJ}. It must assume
that all @code{SCM} values that it references have already been freed
and are thus invalid.
The @var{free} procedure must return 0.
@end deftypefn
@deftypefn {C Function} void scm_set_smob_print (scm_t_bits tc, int (*print) (SCM obj, SCM port, scm_print_state* pstate))
This function sets the smob printing procedure for the smob type
specified by the tag @var{tc}. @var{tc} is the tag returned by
@code{scm_make_smob_type}.
The @var{print} procedure should output a textual representation of
the smob instance @var{obj} to @var{port}, using information in
@var{pstate}.
The textual representation should be of the form @code{#<name ...>}.
This ensures that @code{read} will not interpret it as some other
Scheme value.
It is often best to ignore @var{pstate} and just print to @var{port}
with @code{scm_display}, @code{scm_write}, @code{scm_simple_format},
and @code{scm_puts}.
@end deftypefn
@deftypefn {C Function} void scm_set_smob_equalp (scm_t_bits tc, SCM (*equalp) (SCM obj1, SCM obj1))
This function sets the smob equality-testing predicate for the smob
type specified by the tag @var{tc}. @var{tc} is the tag returned by
@code{scm_make_smob_type}.
The @var{equalp} procedure should return @code{SCM_BOOL_T} when
@var{obj1} is @code{equal?} to @var{obj2}. Else it should return
@var{SCM_BOOL_F}. Both @var{obj1} and @var{obj2} are instances of the
smob type @var{tc}.
@end deftypefn
@deftypefn {C Macro} int SCM_SMOB_PREDICATE (scm_t_bits tag, SCM exp)
Return true iff @var{exp} is a smob instance of the type indicated by
@var{tag}. The expression @var{exp} can be evaluated more than once,
so it shouldn't contain any side effects.
@end deftypefn
@deftypefn {C Macro} void SCM_NEWSMOB (SCM value, scm_t_bits tag, void *data)
@deftypefnx {C Macro} void SCM_NEWSMOB2 (SCM value, scm_t_bits tag, void *data, void *data2)
@deftypefnx {C Macro} void SCM_NEWSMOB3 (SCM value, scm_t_bits tag, void *data, void *data2, void *data3)
Make @var{value} contain a smob instance of the type with tag
@var{tag} and smob data @var{data}, @var{data2}, and @var{data3}, as
appropriate.
The @var{tag} is what has been returned by @code{scm_make_smob_type}.
The initial values @var{data}, @var{data2}, and @var{data3} are of
type @code{scm_t_bits}; when you want to use them for @code{SCM}
values, these values need to be converted to a @code{scm_t_bits} first
by using @code{SCM_UNPACK}.
The flags of the smob instance start out as zero.
@end deftypefn
Since it is often the case (e.g., in smob constructors) that you will
create a smob instance and return it, there is also a slightly specialized
macro for this situation:
@deftypefn {C Macro} {} SCM_RETURN_NEWSMOB (scm_t_bits tag, void *data)
@deftypefnx {C Macro} {} SCM_RETURN_NEWSMOB2 (scm_t_bits tag, void *data1, void *data2)
@deftypefnx {C Macro} {} SCM_RETURN_NEWSMOB3 (scm_t_bits tag, void *data1, void *data2, void *data3)
This macro expands to a block of code that creates a smob instance of
the type with tag @var{tag} and smob data @var{data}, @var{data2}, and
@var{data3}, as with @code{SCM_NEWSMOB}, etc., and causes the
surrounding function to return that @code{SCM} value. It should be
the last piece of code in a block.
@end deftypefn
@deftypefn {C Macro} scm_t_bits SCM_SMOB_FLAGS (SCM obj)
Return the 16 extra bits of the smob @var{obj}. No meaning is
predefined for these bits, you can use them freely.
@end deftypefn
@deftypefn {C Macro} scm_t_bits SCM_SET_SMOB_FLAGS (SCM obj, scm_t_bits flags)
Set the 16 extra bits of the smob @var{obj} to @var{flags}. No
meaning is predefined for these bits, you can use them freely.
@end deftypefn
@deftypefn {C Macro} scm_t_bits SCM_SMOB_DATA (SCM obj)
@deftypefnx {C Macro} scm_t_bits SCM_SMOB_DATA_2 (SCM obj)
@deftypefnx {C Macro} scm_t_bits SCM_SMOB_DATA_3 (SCM obj)
Return the first (second, third) immediate word of the smob @var{obj}
as a @code{scm_t_bits} value. When the word contains a @code{SCM}
value, use @code{SCM_SMOB_OBJECT} (etc.) instead.
@end deftypefn
@deftypefn {C Macro} void SCM_SET_SMOB_DATA (SCM obj, scm_t_bits val)
@deftypefnx {C Macro} void SCM_SET_SMOB_DATA_2 (SCM obj, scm_t_bits val)
@deftypefnx {C Macro} void SCM_SET_SMOB_DATA_3 (SCM obj, scm_t_bits val)
Set the first (second, third) immediate word of the smob @var{obj} to
@var{val}. When the word should be set to a @code{SCM} value, use
@code{SCM_SMOB_SET_OBJECT} (etc.) instead.
@end deftypefn
@deftypefn {C Macro} SCM SCM_SMOB_OBJECT (SCM obj)
@deftypefnx {C Macro} SCM SCM_SMOB_OBJECT_2 (SCM obj)
@deftypefnx {C Macro} SCM SCM_SMOB_OBJECT_3 (SCM obj)
Return the first (second, third) immediate word of the smob @var{obj}
as a @code{SCM} value. When the word contains a @code{scm_t_bits}
value, use @code{SCM_SMOB_DATA} (etc.) instead.
@end deftypefn
@deftypefn {C Macro} void SCM_SET_SMOB_OBJECT (SCM obj, SCM val)
@deftypefnx {C Macro} void SCM_SET_SMOB_OBJECT_2 (SCM obj, SCM val)
@deftypefnx {C Macro} void SCM_SET_SMOB_OBJECT_3 (SCM obj, SCM val)
Set the first (second, third) immediate word of the smob @var{obj} to
@var{val}. When the word should be set to a @code{scm_t_bits} value, use
@code{SCM_SMOB_SET_DATA} (etc.) instead.
@end deftypefn
@deftypefn {C Macro} {SCM *} SCM_SMOB_OBJECT_LOC (SCM obj)
@deftypefnx {C Macro} {SCM *} SCM_SMOB_OBJECT_2_LOC (SCM obj)
@deftypefnx {C Macro} {SCM *} SCM_SMOB_OBJECT_3_LOC (SCM obj)
Return a pointer to the first (second, third) immediate word of the
smob @var{obj}. Note that this is a pointer to @code{SCM}. If you
need to work with @code{scm_t_bits} values, use @code{SCM_PACK} and
@code{SCM_UNPACK}, as appropriate.
@end deftypefn
@deftypefun SCM scm_markcdr (SCM @var{x})
Mark the references in the smob @var{x}, assuming that @var{x}'s first
data word contains an ordinary Scheme object, and @var{x} refers to no
other objects. This function simply returns @var{x}'s first data word.
@end deftypefun
@c Local Variables:
@c TeX-master: "guile.texi"
@c End:

143
doc/ref/api-snarf.texi Normal file
View file

@ -0,0 +1,143 @@
@c -*-texinfo-*-
@c This is part of the GNU Guile Reference Manual.
@c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004
@c Free Software Foundation, Inc.
@c See the file guile.texi for copying conditions.
@node Snarfing Macros
@section Snarfing Macros
@cindex guile-snarf recognized macros
@cindex guile-snarf deprecated macros
The following macros do two different things: when compiled normally,
they expand in one way; when processed during snarfing, they cause the
@code{guile-snarf} program to pick up some initialization code,
@xref{Function Snarfing}.
The descriptions below use the term `normally' to refer to the case
when the code is compiled normally, and `while snarfing' when the code
is processed by @code{guile-snarf}.
@deffn {C Macro} SCM_SNARF_INIT (code)
Normally, @code{SCM_SNARF_INIT} expands to nothing; while snarfing, it
causes @var{code} to be included in the initialization action file,
followed by a semicolon.
This is the fundamental macro for snarfing initialization actions.
The more specialized macros below use it internally.
@end deffn
@deffn {C Macro} SCM_DEFINE (c_name, scheme_name, req, opt, var, arglist, docstring)
Normally, this macro expands into
@smallexample
static const char s_@var{c_name}[] = @var{scheme_name};
SCM
@var{c_name} @var{arglist}
@end smallexample
While snarfing, it causes
@smallexample
scm_c_define_gsubr (s_@var{c_name}, @var{req}, @var{opt}, @var{var},
@var{c_name});
@end smallexample
to be added to the initialization actions. Thus, you can use it to
declare a C function named @var{c_name} that will be made available to
Scheme with the name @var{scheme_name}.
Note that the @var{arglist} argument must have parentheses around it.
@end deffn
@deffn {C Macro} SCM_SYMBOL (c_name, scheme_name)
@deffnx {C Macro} SCM_GLOBAL_SYMBOL (c_name, scheme_name)
Normally, these macros expand into
@smallexample
static SCM @var{c_name}
@end smallexample
or
@smallexample
SCM @var{c_name}
@end smallexample
respectively. While snarfing, they both expand into the
initialization code
@smallexample
@var{c_name} = scm_permanent_object (scm_from_symbol (@var{scheme_name}));
@end smallexample
Thus, you can use them declare a static or global variable of type
@code{SCM} that will be initialized to the symbol named
@var{scheme_name}.
@end deffn
@deffn {C Macro} SCM_KEYWORD (c_name, scheme_name)
@deffnx {C Macro} SCM_GLOBAL_KEYWORD (c_name, scheme_name)
Normally, these macros expand into
@smallexample
static SCM @var{c_name}
@end smallexample
or
@smallexample
SCM @var{c_name}
@end smallexample
respectively. While snarfing, they both expand into the
initialization code
@smallexample
@var{c_name} = scm_permanent_object (scm_from_keyword (@var{scheme_name}));
@end smallexample
Thus, you can use them declare a static or global variable of type
@code{SCM} that will be initialized to the keyword named
@var{scheme_name}.
@end deffn
@deffn {C Macro} SCM_VARIABLE (c_name, scheme_name)
@deffnx {C Macro} SCM_GLOBAL_VARIABLE (c_name, scheme_name)
These macros are equivalent to @code{SCM_VARIABLE_INIT} and
@code{SCM_GLOBAL_VARIABLE_INIT}, respectively, with a @var{value} of
@code{SCM_BOOL_F}.
@end deffn
@deffn {C Macro} SCM_VARIABLE_INIT (c_name, scheme_name, value)
@deffnx {C Macro} SCM_GLOBAL_VARIABLE_INIT (c_name, scheme_name, value)
Normally, these macros expand into
@smallexample
static SCM @var{c_name}
@end smallexample
or
@smallexample
SCM @var{c_name}
@end smallexample
respectively. While snarfing, they both expand into the
initialization code
@smallexample
@var{c_name} = scm_permanent_object (scm_c_define (@var{scheme_name}, @var{value});
@end smallexample
Thus, you can use them declare a static or global C variable of type
@code{SCM} that will be initialized to the object representing the
Scheme variable named d@var{scheme_name} in the current module. The
variable will be defined when it doesn't already exist. It is always
set to @var{value}.
@end deffn

View file

@ -0,0 +1,54 @@
@c -*-texinfo-*-
@c This is part of the GNU Guile Reference Manual.
@c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004
@c Free Software Foundation, Inc.
@c See the file guile.texi for copying conditions.
@page
@node Translation
@section Support for Translating Other Languages
[Describe translation framework.]
@menu
* Emacs Lisp Support:: Helper primitives for Emacs Lisp.
@end menu
@node Emacs Lisp Support
@subsection Emacs Lisp Support
@deffn {Scheme Procedure} nil-car x
@deffnx {C Function} scm_nil_car (x)
Return the car of @var{x}, but convert it to LISP nil if it
is Scheme's end-of-list.
@end deffn
@deffn {Scheme Procedure} nil-cdr x
@deffnx {C Function} scm_nil_cdr (x)
Return the cdr of @var{x}, but convert it to LISP nil if it
is Scheme's end-of-list.
@end deffn
@deffn {Scheme Procedure} nil-cons x y
@deffnx {C Function} scm_nil_cons (x, y)
Create a new cons cell with @var{x} as the car and @var{y} as
the cdr, but convert @var{y} to Scheme's end-of-list if it is
a Lisp nil.
@end deffn
@deffn {Scheme Procedure} nil-eq x y
Compare @var{x} and @var{y} and return Lisp's t if they are
@code{eq?}, return Lisp's nil otherwise.
@end deffn
@deffn {Scheme Procedure} null x
@deffnx {C Function} scm_null (x)
Return Lisp's @code{t} if @var{x} is nil in the LISP sense,
return Lisp's nil otherwise.
@end deffn
@c Local Variables:
@c TeX-master: "guile.texi"
@c End:

762
doc/ref/api-utility.texi Normal file
View file

@ -0,0 +1,762 @@
@c -*-texinfo-*-
@c This is part of the GNU Guile Reference Manual.
@c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004
@c Free Software Foundation, Inc.
@c See the file guile.texi for copying conditions.
@page
@node Utility Functions
@section General Utility Functions
@c FIXME::martin: Review me!
This chapter contains information about procedures which are not cleanly
tied to a specific data type. Because of their wide range of
applications, they are collected in a @dfn{utility} chapter.
@menu
* Equality:: When are two values `the same'?
* Object Properties:: A modern interface to object properties.
* Sorting:: Sort utility procedures.
* Copying:: Copying deep structures.
* General Conversion:: Converting objects to strings.
* Hooks:: User-customizable event lists.
@end menu
@node Equality
@subsection Equality
@c FIXME::martin: Review me!
@cindex sameness
@cindex equality
Three different kinds of @dfn{sameness} are defined in Scheme.
@itemize @bullet
@item
Two values can refer to exactly the same object.
@item
Two objects can have the same @dfn{value}.
@item
Two objects can be structurally equivalent.
@end itemize
The differentiation between these three kinds is important, because
determining whether two values are the same objects is very efficient,
while determining structural equivalence can be quite expensive
(consider comparing two very long lists). Therefore, three different
procedures for testing for equality are provided, which correspond to
the three kinds of @dfn{sameness} defined above.
@rnindex eq?
@deffn {Scheme Procedure} eq? x y
@deffnx {C Function} scm_eq_p (x, y)
Return @code{#t} iff @var{x} references the same object as @var{y}.
@code{eq?} is similar to @code{eqv?} except that in some cases it is
capable of discerning distinctions finer than those detectable by
@code{eqv?}.
@end deffn
@deftypefn {C Function} int scm_is_eq (SCM x, SCM y)
Return @code{1} when @var{x} and @var{y} are equal in the sense of
@code{eq?}, else return @code{0}.
@end deftypefn
@rnindex eqv?
@deffn {Scheme Procedure} eqv? x y
@deffnx {C Function} scm_eqv_p (x, y)
The @code{eqv?} procedure defines a useful equivalence relation on objects.
Briefly, it returns @code{#t} if @var{x} and @var{y} should normally be
regarded as the same object. This relation is left slightly open to
interpretation, but works for comparing immediate integers, characters,
and inexact numbers.
@end deffn
@rnindex equal?
@deffn {Scheme Procedure} equal? x y
@deffnx {C Function} scm_equal_p (x, y)
Return @code{#t} iff @var{x} and @var{y} are recursively @code{eqv?}
equivalent. @code{equal?} recursively compares the contents of pairs,
vectors, and strings, applying @code{eqv?} on other objects such as
numbers and symbols. A rule of thumb is that objects are generally
@code{equal?} if they print the same. @code{equal?} may fail to
terminate if its arguments are circular data structures.
@end deffn
@node Object Properties
@subsection Object Properties
It's often useful to associate a piece of additional information with a
Scheme object even though that object does not have a dedicated slot
available in which the additional information could be stored. Object
properties allow you to do just that.
An object property is most commonly used to associate one kind of
additional information with each instance of a class of similar Scheme
objects. For example, all procedures have a `name' property, which
stores the name of the variable in which the procedure was stored by a
@code{define} expression, or @code{#f} if the procedure wasn't created
by that kind of expression.
Guile's representation of an object property is a procedure-with-setter
(@pxref{Procedures with Setters}) that can be used with the generalized
form of @code{set!} (REFFIXME) to set and retrieve that property for any
Scheme object. So, setting a property looks like this:
@lisp
(set! (my-property obj1) value-for-obj1)
(set! (my-property obj2) value-for-obj2)
@end lisp
@noindent
And retrieving values of the same property looks like this:
@lisp
(my-property obj1)
@result{}
value-for-obj1
(my-property obj2)
@result{}
value-for-obj2
@end lisp
To create an object property in the first place, use the
@code{make-object-property} procedure:
@lisp
(define my-property (make-object-property))
@end lisp
@deffn {Scheme Procedure} make-object-property
Create and return an object property. An object property is a
procedure-with-setter that can be called in two ways. @code{(set!
(@var{property} @var{obj}) @var{val})} sets @var{obj}'s @var{property}
to @var{val}. @code{(@var{property} @var{obj})} returns the current
setting of @var{obj}'s @var{property}.
@end deffn
A single object property created by @code{make-object-property} can
associate distinct property values with all Scheme values that are
distinguishable by @code{eq?} (including, for example, integers).
Internally, object properties are implemented using a weak key hash
table. This means that, as long as a Scheme value with property values
is protected from garbage collection, its property values are also
protected. When the Scheme value is collected, its entry in the
property table is removed and so the (ex-) property values are no longer
protected by the table.
@menu
* Property Primitives:: Low level property implementation.
* Old-fashioned Properties:: An older approach to properties.
@end menu
@node Property Primitives
@subsubsection Low Level Property Implementation.
@deffn {Scheme Procedure} primitive-make-property not-found-proc
@deffnx {C Function} scm_primitive_make_property (not_found_proc)
Create a @dfn{property token} that can be used with
@code{primitive-property-ref} and @code{primitive-property-set!}.
See @code{primitive-property-ref} for the significance of
@var{not-found-proc}.
@end deffn
@deffn {Scheme Procedure} primitive-property-ref prop obj
@deffnx {C Function} scm_primitive_property_ref (prop, obj)
Return the property @var{prop} of @var{obj}.
When no value has yet been associated with @var{prop} and @var{obj},
the @var{not-found-proc} from @var{prop} is used. A call
@code{(@var{not-found-proc} @var{prop} @var{obj})} is made and the
result set as the property value. If @var{not-found-proc} is
@code{#f} then @code{#f} is the property value.
@end deffn
@deffn {Scheme Procedure} primitive-property-set! prop obj val
@deffnx {C Function} scm_primitive_property_set_x (prop, obj, val)
Set the property @var{prop} of @var{obj} to @var{val}.
@end deffn
@deffn {Scheme Procedure} primitive-property-del! prop obj
@deffnx {C Function} scm_primitive_property_del_x (prop, obj)
Remove any value associated with @var{prop} and @var{obj}.
@end deffn
@node Old-fashioned Properties
@subsubsection An Older Approach to Properties
Traditionally, Lisp systems provide a different object property
interface to that provided by @code{make-object-property}, in which the
object property that is being set or retrieved is indicated by a symbol.
Guile includes this older kind of interface as well, but it may well be
removed in a future release, as it is less powerful than
@code{make-object-property} and so increases the size of the Guile
library for no benefit. (And it is trivial to write a compatibility
layer in Scheme.)
@deffn {Scheme Procedure} object-properties obj
@deffnx {C Function} scm_object_properties (obj)
Return @var{obj}'s property list.
@end deffn
@deffn {Scheme Procedure} set-object-properties! obj alist
@deffnx {C Function} scm_set_object_properties_x (obj, alist)
Set @var{obj}'s property list to @var{alist}.
@end deffn
@deffn {Scheme Procedure} object-property obj key
@deffnx {C Function} scm_object_property (obj, key)
Return the property of @var{obj} with name @var{key}.
@end deffn
@deffn {Scheme Procedure} set-object-property! obj key value
@deffnx {C Function} scm_set_object_property_x (obj, key, value)
In @var{obj}'s property list, set the property named @var{key}
to @var{value}.
@end deffn
@node Sorting
@subsection Sorting
@c FIXME::martin: Review me!
@cindex sorting
@cindex sorting lists
@cindex sorting vectors
Sorting is very important in computer programs. Therefore, Guile comes
with several sorting procedures built-in. As always, procedures with
names ending in @code{!} are side-effecting, that means that they may
modify their parameters in order to produce their results.
The first group of procedures can be used to merge two lists (which must
be already sorted on their own) and produce sorted lists containing
all elements of the input lists.
@deffn {Scheme Procedure} merge alist blist less
@deffnx {C Function} scm_merge (alist, blist, less)
Merge two already sorted lists into one.
Given two lists @var{alist} and @var{blist}, such that
@code{(sorted? alist less?)} and @code{(sorted? blist less?)},
return a new list in which the elements of @var{alist} and
@var{blist} have been stably interleaved so that
@code{(sorted? (merge alist blist less?) less?)}.
Note: this does _not_ accept vectors.
@end deffn
@deffn {Scheme Procedure} merge! alist blist less
@deffnx {C Function} scm_merge_x (alist, blist, less)
Takes two lists @var{alist} and @var{blist} such that
@code{(sorted? alist less?)} and @code{(sorted? blist less?)} and
returns a new list in which the elements of @var{alist} and
@var{blist} have been stably interleaved so that
@code{(sorted? (merge alist blist less?) less?)}.
This is the destructive variant of @code{merge}
Note: this does _not_ accept vectors.
@end deffn
The following procedures can operate on sequences which are either
vectors or list. According to the given arguments, they return sorted
vectors or lists, respectively. The first of the following procedures
determines whether a sequence is already sorted, the other sort a given
sequence. The variants with names starting with @code{stable-} are
special in that they maintain a special property of the input sequences:
If two or more elements are the same according to the comparison
predicate, they are left in the same order as they appeared in the
input.
@deffn {Scheme Procedure} sorted? items less
@deffnx {C Function} scm_sorted_p (items, less)
Return @code{#t} iff @var{items} is a list or a vector such that
for all 1 <= i <= m, the predicate @var{less} returns true when
applied to all elements i - 1 and i
@end deffn
@deffn {Scheme Procedure} sort items less
@deffnx {C Function} scm_sort (items, less)
Sort the sequence @var{items}, which may be a list or a
vector. @var{less} is used for comparing the sequence
elements. This is not a stable sort.
@end deffn
@deffn {Scheme Procedure} sort! items less
@deffnx {C Function} scm_sort_x (items, less)
Sort the sequence @var{items}, which may be a list or a
vector. @var{less} is used for comparing the sequence
elements. The sorting is destructive, that means that the
input sequence is modified to produce the sorted result.
This is not a stable sort.
@end deffn
@deffn {Scheme Procedure} stable-sort items less
@deffnx {C Function} scm_stable_sort (items, less)
Sort the sequence @var{items}, which may be a list or a
vector. @var{less} is used for comparing the sequence elements.
This is a stable sort.
@end deffn
@deffn {Scheme Procedure} stable-sort! items less
@deffnx {C Function} scm_stable_sort_x (items, less)
Sort the sequence @var{items}, which may be a list or a
vector. @var{less} is used for comparing the sequence elements.
The sorting is destructive, that means that the input sequence
is modified to produce the sorted result.
This is a stable sort.
@end deffn
The procedures in the last group only accept lists or vectors as input,
as their names indicate.
@deffn {Scheme Procedure} sort-list items less
@deffnx {C Function} scm_sort_list (items, less)
Sort the list @var{items}, using @var{less} for comparing the
list elements. This is a stable sort.
@end deffn
@deffn {Scheme Procedure} sort-list! items less
@deffnx {C Function} scm_sort_list_x (items, less)
Sort the list @var{items}, using @var{less} for comparing the
list elements. The sorting is destructive, that means that the
input list is modified to produce the sorted result.
This is a stable sort.
@end deffn
@deffn {Scheme Procedure} restricted-vector-sort! vec less startpos endpos
@deffnx {C Function} scm_restricted_vector_sort_x (vec, less, startpos, endpos)
Sort the vector @var{vec}, using @var{less} for comparing
the vector elements. @var{startpos} and @var{endpos} delimit
the range of the vector which gets sorted. The return value
is not specified.
@end deffn
@node Copying
@subsection Copying Deep Structures
@c FIXME::martin: Review me!
The procedures for copying lists (@pxref{Lists}) only produce a flat
copy of the input list, and currently Guile does not even contain
procedures for copying vectors. @code{copy-tree} can be used for these
application, as it does not only copy the spine of a list, but also
copies any pairs in the cars of the input lists.
@deffn {Scheme Procedure} copy-tree obj
@deffnx {C Function} scm_copy_tree (obj)
Recursively copy the data tree that is bound to @var{obj}, and return a
pointer to the new data structure. @code{copy-tree} recurses down the
contents of both pairs and vectors (since both cons cells and vector
cells may point to arbitrary objects), and stops recursing when it hits
any other object.
@end deffn
@node General Conversion
@subsection General String Conversion
@c FIXME::martin: Review me!
When debugging Scheme programs, but also for providing a human-friendly
interface, a procedure for converting any Scheme object into string
format is very useful. Conversion from/to strings can of course be done
with specialized procedures when the data type of the object to convert
is known, but with this procedure, it is often more comfortable.
@code{object->string} converts an object by using a print procedure for
writing to a string port, and then returning the resulting string.
Converting an object back from the string is only possible if the object
type has a read syntax and the read syntax is preserved by the printing
procedure.
@deffn {Scheme Procedure} object->string obj [printer]
@deffnx {C Function} scm_object_to_string (obj, printer)
Return a Scheme string obtained by printing @var{obj}.
Printing function can be specified by the optional second
argument @var{printer} (default: @code{write}).
@end deffn
@node Hooks
@subsection Hooks
@tpindex Hooks
A hook is a list of procedures to be called at well defined points in
time. Typically, an application provides a hook @var{h} and promises
its users that it will call all of the procedures in @var{h} at a
defined point in the application's processing. By adding its own
procedure to @var{h}, an application user can tap into or even influence
the progress of the application.
Guile itself provides several such hooks for debugging and customization
purposes: these are listed in a subsection below.
When an application first creates a hook, it needs to know how many
arguments will be passed to the hook's procedures when the hook is run.
The chosen number of arguments (which may be none) is declared when the
hook is created, and all the procedures that are added to that hook must
be capable of accepting that number of arguments.
A hook is created using @code{make-hook}. A procedure can be added to
or removed from a hook using @code{add-hook!} or @code{remove-hook!},
and all of a hook's procedures can be removed together using
@code{reset-hook!}. When an application wants to run a hook, it does so
using @code{run-hook}.
@menu
* Hook Example:: Hook usage by example.
* Hook Reference:: Reference of all hook procedures.
* C Hooks:: Hooks for use from C code.
* GC Hooks:: Garbage collection hooks.
* REPL Hooks:: Hooks into the Guile REPL.
@end menu
@node Hook Example
@subsubsection Hook Usage by Example
Hook usage is shown by some examples in this section. First, we will
define a hook of arity 2 --- that is, the procedures stored in the hook
will have to accept two arguments.
@lisp
(define hook (make-hook 2))
hook
@result{} #<hook 2 40286c90>
@end lisp
Now we are ready to add some procedures to the newly created hook with
@code{add-hook!}. In the following example, two procedures are added,
which print different messages and do different things with their
arguments.
@lisp
(add-hook! hook (lambda (x y)
(display "Foo: ")
(display (+ x y))
(newline)))
(add-hook! hook (lambda (x y)
(display "Bar: ")
(display (* x y))
(newline)))
@end lisp
Once the procedures have been added, we can invoke the hook using
@code{run-hook}.
@lisp
(run-hook hook 3 4)
@print{} Bar: 12
@print{} Foo: 7
@end lisp
Note that the procedures are called in the reverse of the order with
which they were added. This is because the default behaviour of
@code{add-hook!} is to add its procedure to the @emph{front} of the
hook's procedure list. You can force @code{add-hook!} to add its
procedure to the @emph{end} of the list instead by providing a third
@code{#t} argument on the second call to @code{add-hook!}.
@lisp
(add-hook! hook (lambda (x y)
(display "Foo: ")
(display (+ x y))
(newline)))
(add-hook! hook (lambda (x y)
(display "Bar: ")
(display (* x y))
(newline))
#t) ; @r{<- Change here!}
(run-hook hook 3 4)
@print{} Foo: 7
@print{} Bar: 12
@end lisp
@node Hook Reference
@subsubsection Hook Reference
When you create a hook with @code{make-hook}, you must specify the arity
of the procedures which can be added to the hook. If the arity is not
given explicitly as an argument to @code{make-hook}, it defaults to
zero. All procedures of a given hook must have the same arity, and when
the procedures are invoked using @code{run-hook}, the number of
arguments passed must match the arity specified at hook creation time.
The order in which procedures are added to a hook matters. If the third
parameter to @code{add-hook!} is omitted or is equal to @code{#f}, the
procedure is added in front of the procedures which might already be on
that hook, otherwise the procedure is added at the end. The procedures
are always called from the front to the end of the list when they are
invoked via @code{run-hook}.
The ordering of the list of procedures returned by @code{hook->list}
matches the order in which those procedures would be called if the hook
was run using @code{run-hook}.
Note that the C functions in the following entries are for handling
@dfn{Scheme-level} hooks in C. There are also @dfn{C-level} hooks which
have their own interface (@pxref{C Hooks}).
@deffn {Scheme Procedure} make-hook [n_args]
@deffnx {C Function} scm_make_hook (n_args)
Create a hook for storing procedure of arity @var{n_args}.
@var{n_args} defaults to zero. The returned value is a hook
object to be used with the other hook procedures.
@end deffn
@deffn {Scheme Procedure} hook? x
@deffnx {C Function} scm_hook_p (x)
Return @code{#t} if @var{x} is a hook, @code{#f} otherwise.
@end deffn
@deffn {Scheme Procedure} hook-empty? hook
@deffnx {C Function} scm_hook_empty_p (hook)
Return @code{#t} if @var{hook} is an empty hook, @code{#f}
otherwise.
@end deffn
@deffn {Scheme Procedure} add-hook! hook proc [append_p]
@deffnx {C Function} scm_add_hook_x (hook, proc, append_p)
Add the procedure @var{proc} to the hook @var{hook}. The
procedure is added to the end if @var{append_p} is true,
otherwise it is added to the front. The return value of this
procedure is not specified.
@end deffn
@deffn {Scheme Procedure} remove-hook! hook proc
@deffnx {C Function} scm_remove_hook_x (hook, proc)
Remove the procedure @var{proc} from the hook @var{hook}. The
return value of this procedure is not specified.
@end deffn
@deffn {Scheme Procedure} reset-hook! hook
@deffnx {C Function} scm_reset_hook_x (hook)
Remove all procedures from the hook @var{hook}. The return
value of this procedure is not specified.
@end deffn
@deffn {Scheme Procedure} hook->list hook
@deffnx {C Function} scm_hook_to_list (hook)
Convert the procedure list of @var{hook} to a list.
@end deffn
@deffn {Scheme Procedure} run-hook hook . args
@deffnx {C Function} scm_run_hook (hook, args)
Apply all procedures from the hook @var{hook} to the arguments
@var{args}. The order of the procedure application is first to
last. The return value of this procedure is not specified.
@end deffn
If, in C code, you are certain that you have a hook object and well
formed argument list for that hook, you can also use
@code{scm_c_run_hook}, which is identical to @code{scm_run_hook} but
does no type checking.
@deftypefn {C Function} void scm_c_run_hook (SCM hook, SCM args)
The same as @code{scm_run_hook} but without any type checking to confirm
that @var{hook} is actually a hook object and that @var{args} is a
well-formed list matching the arity of the hook.
@end deftypefn
For C code, @code{SCM_HOOKP} is a faster alternative to
@code{scm_hook_p}:
@deftypefn {C Macro} int SCM_HOOKP (x)
Return 1 if @var{x} is a Scheme-level hook, 0 otherwise.
@end deftypefn
@subsubsection Handling Scheme-level hooks from C code
Here is an example of how to handle Scheme-level hooks from C code using
the above functions.
@example
if (scm_is_true (scm_hook_p (obj)))
/* handle Scheme-level hook using C functions */
scm_reset_hook_x (obj);
else
/* do something else (obj is not a hook) */
@end example
@node C Hooks
@subsubsection Hooks For C Code.
The hooks already described are intended to be populated by Scheme-level
procedures. In addition to this, the Guile library provides an
independent set of interfaces for the creation and manipulation of hooks
that are designed to be populated by functions implemented in C.
The original motivation here was to provide a kind of hook that could
safely be invoked at various points during garbage collection.
Scheme-level hooks are unsuitable for this purpose as running them could
itself require memory allocation, which would then invoke garbage
collection recursively @dots{} However, it is also the case that these
hooks are easier to work with than the Scheme-level ones if you only
want to register C functions with them. So if that is mainly what your
code needs to do, you may prefer to use this interface.
To create a C hook, you should allocate storage for a structure of type
@code{scm_t_c_hook} and then initialize it using @code{scm_c_hook_init}.
@deftp {C Type} scm_t_c_hook
Data type for a C hook. The internals of this type should be treated as
opaque.
@end deftp
@deftp {C Enum} scm_t_c_hook_type
Enumeration of possible hook types, which are:
@table @code
@item SCM_C_HOOK_NORMAL
@vindex SCM_C_HOOK_NORMAL
Type of hook for which all the registered functions will always be called.
@item SCM_C_HOOK_OR
@vindex SCM_C_HOOK_OR
Type of hook for which the sequence of registered functions will be
called only until one of them returns C true (a non-NULL pointer).
@item SCM_C_HOOK_AND
@vindex SCM_C_HOOK_AND
Type of hook for which the sequence of registered functions will be
called only until one of them returns C false (a NULL pointer).
@end table
@end deftp
@deftypefn {C Function} void scm_c_hook_init (scm_t_c_hook *hook, void *hook_data, scm_t_c_hook_type type)
Initialize the C hook at memory pointed to by @var{hook}. @var{type}
should be one of the values of the @code{scm_t_c_hook_type} enumeration,
and controls how the hook functions will be called. @var{hook_data} is
a closure parameter that will be passed to all registered hook functions
when they are called.
@end deftypefn
To add or remove a C function from a C hook, use @code{scm_c_hook_add}
or @code{scm_c_hook_remove}. A hook function must expect three
@code{void *} parameters which are, respectively:
@table @var
@item hook_data
The hook closure data that was specified at the time the hook was
initialized by @code{scm_c_hook_init}.
@item func_data
The function closure data that was specified at the time that that
function was registered with the hook by @code{scm_c_hook_add}.
@item data
The call closure data specified by the @code{scm_c_hook_run} call that
runs the hook.
@end table
@deftp {C Type} scm_t_c_hook_function
Function type for a C hook function: takes three @code{void *}
parameters and returns a @code{void *} result.
@end deftp
@deftypefn {C Function} void scm_c_hook_add (scm_t_c_hook *hook, scm_t_c_hook_function func, void *func_data, int appendp)
Add function @var{func}, with function closure data @var{func_data}, to
the C hook @var{hook}. The new function is appended to the hook's list
of functions if @var{appendp} is non-zero, otherwise prepended.
@end deftypefn
@deftypefn {C Function} void scm_c_hook_remove (scm_t_c_hook *hook, scm_t_c_hook_function func, void *func_data)
Remove function @var{func}, with function closure data @var{func_data},
from the C hook @var{hook}. @code{scm_c_hook_remove} checks both
@var{func} and @var{func_data} so as to allow for the same @var{func}
being registered multiple times with different closure data.
@end deftypefn
Finally, to invoke a C hook, call the @code{scm_c_hook_run} function
specifying the hook and the call closure data for this run:
@deftypefn {C Function} {void *} scm_c_hook_run (scm_t_c_hook *hook, void *data)
Run the C hook @var{hook} will call closure data @var{data}. Subject to
the variations for hook types @code{SCM_C_HOOK_OR} and
@code{SCM_C_HOOK_AND}, @code{scm_c_hook_run} calls @var{hook}'s
registered functions in turn, passing them the hook's closure data, each
function's closure data, and the call closure data.
@code{scm_c_hook_run}'s return value is the return value of the last
function to be called.
@end deftypefn
@node GC Hooks
@subsubsection Hooks for Garbage Collection
Whenever Guile performs a garbage collection, it calls the following
hooks in the order shown.
@defvr {C Hook} scm_before_gc_c_hook
C hook called at the very start of a garbage collection, after setting
@code{scm_gc_running_p} to 1, but before entering the GC critical
section.
If garbage collection is blocked because @code{scm_block_gc} is
non-zero, GC exits early soon after calling this hook, and no further
hooks will be called.
@end defvr
@defvr {C Hook} scm_before_mark_c_hook
C hook called before beginning the mark phase of garbage collection,
after the GC thread has entered a critical section.
@end defvr
@defvr {C Hook} scm_before_sweep_c_hook
C hook called before beginning the sweep phase of garbage collection.
This is the same as at the end of the mark phase, since nothing else
happens between marking and sweeping.
@end defvr
@defvr {C Hook} scm_after_sweep_c_hook
C hook called after the end of the sweep phase of garbage collection,
but while the GC thread is still inside its critical section.
@end defvr
@defvr {C Hook} scm_after_gc_c_hook
C hook called at the very end of a garbage collection, after the GC
thread has left its critical section.
@end defvr
@defvr {Scheme Hook} after-gc-hook
@vindex scm_after_gc_hook
Scheme hook with arity 0. This hook is run asynchronously
(@pxref{Asyncs}) soon after the GC has completed and any other events
that were deferred during garbage collection have been processed. (Also
accessible from C with the name @code{scm_after_gc_hook}.)
@end defvr
All the C hooks listed here have type @code{SCM_C_HOOK_NORMAL}, are
initialized with hook closure data NULL, are are invoked by
@code{scm_c_hook_run} with call closure data NULL.
@cindex guardians, testing for GC'd objects
The Scheme hook @code{after-gc-hook} is particularly useful in
conjunction with guardians (@pxref{Guardians}). Typically, if you are
using a guardian, you want to call the guardian after garbage collection
to see if any of the objects added to the guardian have been collected.
By adding a thunk that performs this call to @code{after-gc-hook}, you
can ensure that your guardian is tested after every garbage collection
cycle.
@node REPL Hooks
@subsubsection Hooks into the Guile REPL
@c Local Variables:
@c TeX-master: "guile.texi"
@c End:

View file

@ -137,7 +137,7 @@ x
@comment The title is printed in a large font.
@title Guile Reference Manual
@subtitle Edition @value{MANUAL-EDITION}, for use with Guile @value{VERSION}
@c @subtitle $Id: guile.texi,v 1.34 2004-08-02 11:46:57 mvo Exp $
@c @subtitle $Id: guile.texi,v 1.35 2004-08-02 12:29:00 mvo Exp $
@c See preface.texi for the list of authors
@author The Guile Developers
@ -225,8 +225,8 @@ etc. that make up Guile's application programming interface (API),
@include scheme-ideas.texi
@include scheme-intro.texi
@include scripts.texi
@include debugging.texi
@include scheme-scripts.texi
@include scheme-debugging.texi
@include scheme-reading.texi
@node Programming in C
@ -306,27 +306,27 @@ available through both Scheme and C interfaces.
* GH:: The deprecated GH interface.
@end menu
@include scm.texi
@include scheme-scm.texi
@include ref-init.texi
@include scheme-snarf.texi
@include scheme-data.texi
@include scheme-compound.texi
@include scheme-smobs.texi
@include scheme-procedures.texi
@include scheme-utility.texi
@include scheme-binding.texi
@include scheme-control.texi
@include scheme-io.texi
@include scheme-evaluation.texi
@include scheme-memory.texi
@include scheme-modules.texi
@include scheme-scheduling.texi
@include api-overview.texi
@include api-scm.texi
@include api-init.texi
@include api-snarf.texi
@include api-data.texi
@include api-compound.texi
@include api-smobs.texi
@include api-procedures.texi
@include api-utility.texi
@include api-binding.texi
@include api-control.texi
@include api-io.texi
@include api-evaluation.texi
@include api-memory.texi
@include api-modules.texi
@include api-scheduling.texi
@c object orientation support here
@include scheme-options.texi
@include scheme-translation.texi
@include scheme-debug.texi
@include deprecated.texi
@include api-options.texi
@include api-translation.texi
@include api-debug.texi
@include api-deprecated.texi
@include gh.texi
@node Guile Modules

View file

File diff suppressed because it is too large Load diff

View file

508
doc/ref/scheme-scripts.texi Normal file
View file

@ -0,0 +1,508 @@
@c -*-texinfo-*-
@c This is part of the GNU Guile Reference Manual.
@c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004
@c Free Software Foundation, Inc.
@c See the file guile.texi for copying conditions.
@page
@node Guile Scripting
@section Guile Scripting
Like AWK, Perl, or any shell, Guile can interpret script files. A Guile
script is simply a file of Scheme code with some extra information at
the beginning which tells the operating system how to invoke Guile, and
then tells Guile how to handle the Scheme code.
@menu
* The Top of a Script File:: How to start a Guile script.
* Invoking Guile:: Command line options understood by Guile.
* The Meta Switch:: Passing complex argument lists to Guile
from shell scripts.
* Command Line Handling:: Accessing the command line from a script.
* Scripting Examples::
@end menu
@node The Top of a Script File
@subsection The Top of a Script File
The first line of a Guile script must tell the operating system to use
Guile to evaluate the script, and then tell Guile how to go about doing
that. Here is the simplest case:
@itemize @bullet
@item
The first two characters of the file must be @samp{#!}.
The operating system interprets this to mean that the rest of the line
is the name of an executable that can interpret the script. Guile,
however, interprets these characters as the beginning of a multi-line
comment, terminated by the characters @samp{!#} on a line by themselves.
(This is an extension to the syntax described in R5RS, added to support
shell scripts.)
@item
Immediately after those two characters must come the full pathname to
the Guile interpreter. On most systems, this would be
@samp{/usr/local/bin/guile}.
@item
Then must come a space, followed by a command-line argument to pass to
Guile; this should be @samp{-s}. This switch tells Guile to run a
script, instead of soliciting the user for input from the terminal.
There are more elaborate things one can do here; see @ref{The Meta
Switch}.
@item
Follow this with a newline.
@item
The second line of the script should contain only the characters
@samp{!#} --- just like the top of the file, but reversed. The
operating system never reads this far, but Guile treats this as the end
of the comment begun on the first line by the @samp{#!} characters.
@item
The rest of the file should be a Scheme program.
@end itemize
Guile reads the program, evaluating expressions in the order that they
appear. Upon reaching the end of the file, Guile exits.
@node Invoking Guile
@subsection Invoking Guile
Here we describe Guile's command-line processing in detail. Guile
processes its arguments from left to right, recognizing the switches
described below. For examples, see @ref{Scripting Examples}.
@table @code
@item -s @var{script} @var{arg...}
Read and evaluate Scheme source code from the file @var{script}, as the
@code{load} function would. After loading @var{script}, exit. Any
command-line arguments @var{arg...} following @var{script} become the
script's arguments; the @code{command-line} function returns a list of
strings of the form @code{(@var{script} @var{arg...})}.
@item -c @var{expr} @var{arg...}
Evaluate @var{expr} as Scheme code, and then exit. Any command-line
arguments @var{arg...} following @var{expr} become command-line arguments; the
@code{command-line} function returns a list of strings of the form
@code{(@var{guile} @var{arg...})}, where @var{guile} is the path of the
Guile executable.
@item -- @var{arg...}
Run interactively, prompting the user for expressions and evaluating
them. Any command-line arguments @var{arg...} following the @code{--}
become command-line arguments for the interactive session; the
@code{command-line} function returns a list of strings of the form
@code{(@var{guile} @var{arg...})}, where @var{guile} is the path of the
Guile executable.
@item -l @var{file}
Load Scheme source code from @var{file}, and continue processing the
command line.
@item -e @var{function}
Make @var{function} the @dfn{entry point} of the script. After loading
the script file (with @code{-s}) or evaluating the expression (with
@code{-c}), apply @var{function} to a list containing the program name
and the command-line arguments --- the list provided by the
@code{command-line} function.
A @code{-e} switch can appear anywhere in the argument list, but Guile
always invokes the @var{function} as the @emph{last} action it performs.
This is weird, but because of the way script invocation works under
POSIX, the @code{-s} option must always come last in the list.
The @var{function} is most often a simple symbol that names a function
that is defined in the script. It can also be of the form @code{(@@
@var{module-name} @var{symbol})} and in that case, the symbol is
looked up in the module named @var{module-name}.
@xref{Scripting Examples}.
@item -ds
Treat a final @code{-s} option as if it occurred at this point in the
command line; load the script here.
This switch is necessary because, although the POSIX script invocation
mechanism effectively requires the @code{-s} option to appear last, the
programmer may well want to run the script before other actions
requested on the command line. For examples, see @ref{Scripting
Examples}.
@item \
Read more command-line arguments, starting from the second line of the
script file. @xref{The Meta Switch}.
@item --emacs
Assume Guile is running as an inferior process of Emacs, and use a
special protocol to communicate with Emacs's Guile interaction mode.
This switch sets the global variable use-emacs-interface to @code{#t}.
This switch is still experimental.
@item --use-srfi=@var{list}
The option @code{--use-srfi} expects a comma-separated list of numbers,
each representing a SRFI number to be loaded into the interpreter
before starting evaluating a script file or the REPL. Additionally,
the feature identifier for the loaded SRFIs is recognized by
`cond-expand' when using this option.
@example
guile --use-srfi=8,13
@end example
@item --debug
Start with the debugging evaluator and enable backtraces. Using the
debugging evaluator will give you better error messages but it will
slow down execution. By default, the debugging evaluator is only used
when entering an interactive session. When executing a script with
@code{-s} or @code{-c}, the normal, faster evaluator is used by default.
@vnew{1.8}
@item --no-debug
Do not use the debugging evaluator, even when entering an interactive
session.
@item -h@r{, }--help
Display help on invoking Guile, and then exit.
@item -v@r{, }--version
Display the current version of Guile, and then exit.
@end table
@node The Meta Switch
@subsection The Meta Switch
Guile's command-line switches allow the programmer to describe
reasonably complicated actions in scripts. Unfortunately, the POSIX
script invocation mechanism only allows one argument to appear on the
@samp{#!} line after the path to the Guile executable, and imposes
arbitrary limits on that argument's length. Suppose you wrote a script
starting like this:
@example
#!/usr/local/bin/guile -e main -s
!#
(define (main args)
(map (lambda (arg) (display arg) (display " "))
(cdr args))
(newline))
@end example
The intended meaning is clear: load the file, and then call @code{main}
on the command-line arguments. However, the system will treat
everything after the Guile path as a single argument --- the string
@code{"-e main -s"} --- which is not what we want.
As a workaround, the meta switch @code{\} allows the Guile programmer to
specify an arbitrary number of options without patching the kernel. If
the first argument to Guile is @code{\}, Guile will open the script file
whose name follows the @code{\}, parse arguments starting from the
file's second line (according to rules described below), and substitute
them for the @code{\} switch.
Working in concert with the meta switch, Guile treats the characters
@samp{#!} as the beginning of a comment which extends through the next
line containing only the characters @samp{!#}. This sort of comment may
appear anywhere in a Guile program, but it is most useful at the top of
a file, meshing magically with the POSIX script invocation mechanism.
Thus, consider a script named @file{/u/jimb/ekko} which starts like this:
@example
#!/usr/local/bin/guile \
-e main -s
!#
(define (main args)
(map (lambda (arg) (display arg) (display " "))
(cdr args))
(newline))
@end example
Suppose a user invokes this script as follows:
@example
$ /u/jimb/ekko a b c
@end example
Here's what happens:
@itemize @bullet
@item
the operating system recognizes the @samp{#!} token at the top of the
file, and rewrites the command line to:
@example
/usr/local/bin/guile \ /u/jimb/ekko a b c
@end example
This is the usual behavior, prescribed by POSIX.
@item
When Guile sees the first two arguments, @code{\ /u/jimb/ekko}, it opens
@file{/u/jimb/ekko}, parses the three arguments @code{-e}, @code{main},
and @code{-s} from it, and substitutes them for the @code{\} switch.
Thus, Guile's command line now reads:
@example
/usr/local/bin/guile -e main -s /u/jimb/ekko a b c
@end example
@item
Guile then processes these switches: it loads @file{/u/jimb/ekko} as a
file of Scheme code (treating the first three lines as a comment), and
then performs the application @code{(main "/u/jimb/ekko" "a" "b" "c")}.
@end itemize
When Guile sees the meta switch @code{\}, it parses command-line
argument from the script file according to the following rules:
@itemize @bullet
@item
Each space character terminates an argument. This means that two
spaces in a row introduce an argument @code{""}.
@item
The tab character is not permitted (unless you quote it with the
backslash character, as described below), to avoid confusion.
@item
The newline character terminates the sequence of arguments, and will
also terminate a final non-empty argument. (However, a newline
following a space will not introduce a final empty-string argument;
it only terminates the argument list.)
@item
The backslash character is the escape character. It escapes backslash,
space, tab, and newline. The ANSI C escape sequences like @code{\n} and
@code{\t} are also supported. These produce argument constituents; the
two-character combination @code{\n} doesn't act like a terminating
newline. The escape sequence @code{\@var{NNN}} for exactly three octal
digits reads as the character whose ASCII code is @var{NNN}. As above,
characters produced this way are argument constituents. Backslash
followed by other characters is not allowed.
@end itemize
@node Command Line Handling
@subsection Command Line Handling
@c This section was written and contributed by Martin Grabmueller.
The ability to accept and handle command line arguments is very
important when writing Guile scripts to solve particular problems, such
as extracting information from text files or interfacing with existing
command line applications. This chapter describes how Guile makes
command line arguments available to a Guile script, and the utilities
that Guile provides to help with the processing of command line
arguments.
When a Guile script is invoked, Guile makes the command line arguments
accessible via the procedure @code{command-line}, which returns the
arguments as a list of strings.
For example, if the script
@example
#! /usr/local/bin/guile -s
!#
(write (command-line))
(newline)
@end example
@noindent
is saved in a file @file{cmdline-test.scm} and invoked using the command
line @code{./cmdline-test.scm bar.txt -o foo -frumple grob}, the output
is
@example
("./cmdline-test.scm" "bar.txt" "-o" "foo" "-frumple" "grob")
@end example
If the script invocation includes a @code{-e} option, specifying a
procedure to call after loading the script, Guile will call that
procedure with @code{(command-line)} as its argument. So a script that
uses @code{-e} doesn't need to refer explicitly to @code{command-line}
in its code. For example, the script above would have identical
behaviour if it was written instead like this:
@example
#! /usr/local/bin/guile \
-e main -s
!#
(define (main args)
(write args)
(newline))
@end example
(Note the use of the meta switch @code{\} so that the script invocation
can include more than one Guile option: @xref{The Meta Switch}.)
These scripts use the @code{#!} POSIX convention so that they can be
executed using their own file names directly, as in the example command
line @code{./cmdline-test.scm bar.txt -o foo -frumple grob}. But they
can also be executed by typing out the implied Guile command line in
full, as in:
@example
$ guile -s ./cmdline-test.scm bar.txt -o foo -frumple grob
@end example
@noindent
or
@example
$ guile -e main -s ./cmdline-test2.scm bar.txt -o foo -frumple grob
@end example
Even when a script is invoked using this longer form, the arguments that
the script receives are the same as if it had been invoked using the
short form. Guile ensures that the @code{(command-line)} or @code{-e}
arguments are independent of how the script is invoked, by stripping off
the arguments that Guile itself processes.
A script is free to parse and handle its command line arguments in any
way that it chooses. Where the set of possible options and arguments is
complex, however, it can get tricky to extract all the options, check
the validity of given arguments, and so on. This task can be greatly
simplified by taking advantage of the module @code{(ice-9 getopt-long)},
which is distributed with Guile, @xref{getopt-long}.
@node Scripting Examples
@subsection Scripting Examples
To start with, here are some examples of invoking Guile directly:
@table @code
@item guile -- a b c
Run Guile interactively; @code{(command-line)} will return @*
@code{("/usr/local/bin/guile" "a" "b" "c")}.
@item guile -s /u/jimb/ex2 a b c
Load the file @file{/u/jimb/ex2}; @code{(command-line)} will return @*
@code{("/u/jimb/ex2" "a" "b" "c")}.
@item guile -c '(write %load-path) (newline)'
Write the value of the variable @code{%load-path}, print a newline,
and exit.
@item guile -e main -s /u/jimb/ex4 foo
Load the file @file{/u/jimb/ex4}, and then call the function
@code{main}, passing it the list @code{("/u/jimb/ex4" "foo")}.
@item guile -l first -ds -l last -s script
Load the files @file{first}, @file{script}, and @file{last}, in that
order. The @code{-ds} switch says when to process the @code{-s}
switch. For a more motivated example, see the scripts below.
@end table
Here is a very simple Guile script:
@example
#!/usr/local/bin/guile -s
!#
(display "Hello, world!")
(newline)
@end example
The first line marks the file as a Guile script. When the user invokes
it, the system runs @file{/usr/local/bin/guile} to interpret the script,
passing @code{-s}, the script's filename, and any arguments given to the
script as command-line arguments. When Guile sees @code{-s
@var{script}}, it loads @var{script}. Thus, running this program
produces the output:
@example
Hello, world!
@end example
Here is a script which prints the factorial of its argument:
@example
#!/usr/local/bin/guile -s
!#
(define (fact n)
(if (zero? n) 1
(* n (fact (- n 1)))))
(display (fact (string->number (cadr (command-line)))))
(newline)
@end example
In action:
@example
$ fact 5
120
$
@end example
However, suppose we want to use the definition of @code{fact} in this
file from another script. We can't simply @code{load} the script file,
and then use @code{fact}'s definition, because the script will try to
compute and display a factorial when we load it. To avoid this problem,
we might write the script this way:
@example
#!/usr/local/bin/guile \
-e main -s
!#
(define (fact n)
(if (zero? n) 1
(* n (fact (- n 1)))))
(define (main args)
(display (fact (string->number (cadr args))))
(newline))
@end example
This version packages the actions the script should perform in a
function, @code{main}. This allows us to load the file purely for its
definitions, without any extraneous computation taking place. Then we
used the meta switch @code{\} and the entry point switch @code{-e} to
tell Guile to call @code{main} after loading the script.
@example
$ fact 50
30414093201713378043612608166064768844377641568960512000000000000
@end example
Suppose that we now want to write a script which computes the
@code{choose} function: given a set of @var{m} distinct objects,
@code{(choose @var{n} @var{m})} is the number of distinct subsets
containing @var{n} objects each. It's easy to write @code{choose} given
@code{fact}, so we might write the script this way:
@example
#!/usr/local/bin/guile \
-l fact -e main -s
!#
(define (choose n m)
(/ (fact m) (* (fact (- m n)) (fact n))))
(define (main args)
(let ((n (string->number (cadr args)))
(m (string->number (caddr args))))
(display (choose n m))
(newline)))
@end example
The command-line arguments here tell Guile to first load the file
@file{fact}, and then run the script, with @code{main} as the entry
point. In other words, the @code{choose} script can use definitions
made in the @code{fact} script. Here are some sample runs:
@example
$ choose 0 4
1
$ choose 1 4
4
$ choose 2 4
6
$ choose 3 4
4
$ choose 4 4
1
$ choose 50 100
100891344545564193334812497256
@end example

View file

View file