This is guile.info, produced by makeinfo version 7.1 from guile.texi.

This reference manual documents Guile, GNU's Ubiquitous Intelligent
Language for Extensions.  This is edition 1.1 corresponding to Guile
1.8.8.

   Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004, 2005, 2006,
2007, 2008, 2009, 2010 Free Software Foundation.

   Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.2 or
any later version published by the Free Software Foundation; with the no
Invariant Sections, with the Front-Cover Texts being "A GNU Manual," and
with the Back-Cover Text "You are free to copy and modify this GNU
Manual.".  A copy of the license is included in the section entitled
"GNU Free Documentation License".
INFO-DIR-SECTION The Algorithmic Language Scheme
START-INFO-DIR-ENTRY
* Guile Reference: (guile).     The Guile reference manual.
END-INFO-DIR-ENTRY


File: guile.info,  Node: Lambda,  Next: Primitive Procedures,  Up: Procedures and Macros

5.8.1 Lambda: Basic Procedure Creation
--------------------------------------

A ‘lambda’ expression evaluates to a procedure.  The environment which
is in effect when a ‘lambda’ expression is evaluated is enclosed in the
newly created procedure, this is referred to as a “closure” (*note About
Closure::).

   When a procedure created by ‘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 ‘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
‘lambda’, and what you can do with these procedures.

     (lambda (x) (+ x x))       ⇒ a procedure
     ((lambda (x) (+ x x)) 4)   ⇒ 8

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

     (define add4
       (let ((x 4))
         (lambda (y) (+ x y))))
     (add4 6)                   ⇒ 10

 -- syntax: lambda formals body
     FORMALS should be a formal argument list as described in the
     following table.

     ‘(VARIABLE1 ...)’
          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.
     ‘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.
     ‘(VARIABLE1 ... VARIABLEN . VARIABLEN+1)’
          If a space-delimited period precedes the last variable, then
          the procedure takes N or more variables where N is the number
          of formal arguments before the period.  There must be at least
          one argument before the period.  The first N actual arguments
          will be stored into the newly allocated locations for the
          first 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 N actual arguments, the empty list is stored into the
          location of the last formal argument.

     The list in VARIABLE or 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 ‘apply’, the required part of the list
     argument there will be copied (*note Procedures for On the Fly
     Evaluation: Fly Evaluation.).

     BODY is a sequence of Scheme expressions which are evaluated in
     order when the procedure is invoked.


File: guile.info,  Node: Primitive Procedures,  Next: Optional Arguments,  Prev: Lambda,  Up: Procedures and Macros

5.8.2 Primitive Procedures
--------------------------

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

 -- Function: SCM scm_c_make_gsubr (const char *name, int req, int opt,
          int rst, fcn)
     Register a C procedure FCN as a "subr" -- a primitive subroutine
     that can be called from Scheme.  It will be associated with the
     given NAME but no environment binding will be created.  The
     arguments REQ, OPT and 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 FCN.  The
     number of rest arguments should be 0 or 1.  ‘scm_c_make_gsubr’
     returns a value of type ‘SCM’ which is a "handle" for the
     procedure.

 -- Function: SCM scm_c_define_gsubr (const char *name, int req, int
          opt, int rst, fcn)
     Register a C procedure FCN, as for ‘scm_c_make_gsubr’ above, and
     additionally create a top-level Scheme binding for the procedure in
     the "current environment" using ‘scm_define’.  ‘scm_c_define_gsubr’
     returns a handle for the procedure in the same way as
     ‘scm_c_make_gsubr’, which is usually not further required.

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


File: guile.info,  Node: Optional Arguments,  Next: Procedure Properties,  Prev: Primitive Procedures,  Up: Procedures and Macros

5.8.3 Optional Arguments
------------------------

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

   Guile comes with the module ‘(ice-9 optargs)’, which makes using
optional arguments much more convenient.  In addition, this module
provides syntax for handling keywords in argument lists (*note
Keywords::).

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

     (use-modules (ice-9 optargs))

* 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.


File: guile.info,  Node: let-optional Reference,  Next: let-keywords Reference,  Up: Optional Arguments

5.8.3.1 let-optional Reference
..............................

The syntax ‘let-optional’ and ‘let-optional*’ are for destructuring rest
argument lists and giving names to the various list elements.
‘let-optional’ binds all variables simultaneously, while ‘let-optional*’
binds them sequentially, consistent with ‘let’ and ‘let*’ (*note Local
Bindings::).

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

     After binding the variables, the expressions EXPR ... are evaluated
     in order.


File: guile.info,  Node: let-keywords Reference,  Next: lambda* Reference,  Prev: let-optional Reference,  Up: Optional Arguments

5.8.3.2 let-keywords Reference
..............................

‘let-keywords’ and ‘let-keywords*’ extract values from keyword style
argument lists, binding local variables to those values or to defaults.

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

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

          (let-keywords args #t
                ((foo  "default for foo")
                 (bar  (string-append "default" "for" "bar")))
            (display foo)
            (display ", ")
            (display bar))
          ⊣ world, defaultforbar

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

     ALLOW-OTHER-KEYS? is evaluated and controls whether unknown
     keywords are allowed in the ARGS list.  When true other keys are
     ignored (such as ‘#:xyzzy’ in the example), when ‘#f’ an error is
     thrown for anything unknown.

     ‘let-keywords’ is like ‘let’ (*note Local Bindings::) in that all
     bindings are made at once, the defaults expressions are evaluated
     (if needed) outside the scope of the ‘let-keywords’.

     ‘let-keywords*’ is like ‘let*’, each binding is made successively,
     and the default expressions see the bindings previously made.  This
     is the style used by ‘lambda*’ keywords (*note lambda*
     Reference::).  For example,

          (define args '(#:foo 3))

          (let-keywords* args #f
                ((foo  99)
                 (bar  (+ foo 6)))
            (display bar))
          ⊣ 9

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

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

          (let-keywords* args #t
                ((start 0)
                 (stop  (error "missing #:stop argument")))
            ...)
          ⇒ ERROR: missing #:stop argument


File: guile.info,  Node: lambda* Reference,  Next: define* Reference,  Prev: let-keywords Reference,  Up: Optional Arguments

5.8.3.3 lambda* Reference
.........................

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

 -- library syntax: lambda* ([var...]
          [#:optional vardef...]
          [#:key vardef... [#:allow-other-keys]]
          [#:rest var | . var])
          body

     Create a procedure which takes optional and/or keyword arguments
     specified with ‘#:optional’ and ‘#:key’.  For example,

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

     is a procedure with fixed arguments A and B, optional arguments C
     and D, and rest argument E.  If the optional arguments are omitted
     in a call, the variables for them are bound to ‘#f’.

     ‘lambda*’ can also take keyword arguments.  For example, a
     procedure defined like this:

          (lambda* (#:key xyzzy larch) '())

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

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

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

     FOO is a fixed argument, BAR is an optional argument with default
     value 42, and baz is a keyword argument with default value 73.
     Default value expressions are not evaluated unless they are needed,
     and until the procedure is called.

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

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

          ((lambda* (#:key (heads 0) (tails 0))
             (display (list heads tails)))
           #:heads 37 #:tails 42 #:heads 99)
          ⊣ (99 42)

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

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

          ((lambda* (#:key (x 0) #:allow-other-keys #:rest r)
             (display r))
           #:x 123 #:y 456)
          ⊣ (#:x 123 #:y 456)

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

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


File: guile.info,  Node: define* Reference,  Prev: lambda* Reference,  Up: Optional Arguments

5.8.3.4 define* Reference
.........................

Just like ‘define’ has a shorthand notation for defining procedures
(*note Lambda Alternatives::), ‘define*’ is provided as an abbreviation
of the combination of ‘define’ and ‘lambda*’.

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

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

          (define* (x y #:optional a (z 3) #:key w . u)
             (display (list y z u)))
     defines a procedure ‘x’ with a fixed argument Y, an optional
     argument A, another optional argument Z with default value 3, a
     keyword argument W, and a rest argument U.

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

     This illustrates currying.  A procedure ‘foo’ is defined, which,
     when called with an optional argument BAR, returns a procedure that
     takes an optional argument BAZ.

     Of course, ‘define*[-public]’ also supports ‘#:rest’ and
     ‘#:allow-other-keys’ in the same way as ‘lambda*’.

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

          (defmacro* transmorgify (a #:optional b)
              (a 1))


File: guile.info,  Node: Procedure Properties,  Next: Procedures with Setters,  Prev: Optional Arguments,  Up: Procedures and Macros

5.8.4 Procedure Properties and Meta-information
-----------------------------------------------

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.
‘procedure?’ is the most general predicates, it returns ‘#t’ for any
kind of procedure.  ‘closure?’ does not return ‘#t’ for primitive
procedures, and ‘thunk?’ only returns ‘#t’ for procedures which do not
accept any arguments.

 -- Scheme Procedure: procedure? obj
 -- C Function: scm_procedure_p (obj)
     Return ‘#t’ if OBJ is a procedure.

 -- Scheme Procedure: closure? obj
 -- C Function: scm_closure_p (obj)
     Return ‘#t’ if OBJ is a closure.

 -- Scheme Procedure: thunk? obj
 -- C Function: scm_thunk_p (obj)
     Return ‘#t’ if OBJ is a thunk.

   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.

 -- Scheme Procedure: procedure-name proc
 -- C Function: scm_procedure_name (proc)
     Return the name of the procedure PROC

 -- Scheme Procedure: procedure-source proc
 -- C Function: scm_procedure_source (proc)
     Return the source of the procedure PROC.

 -- Scheme Procedure: procedure-environment proc
 -- C Function: scm_procedure_environment (proc)
     Return the environment of the procedure PROC.

 -- Scheme Procedure: procedure-properties proc
 -- C Function: scm_procedure_properties (proc)
     Return OBJ's property list.

 -- Scheme Procedure: procedure-property obj key
 -- C Function: scm_procedure_property (obj, key)
     Return the property of OBJ with name KEY.

 -- Scheme Procedure: set-procedure-properties! proc alist
 -- C Function: scm_set_procedure_properties_x (proc, alist)
     Set OBJ's property list to ALIST.

 -- Scheme Procedure: set-procedure-property! obj key value
 -- C Function: scm_set_procedure_property_x (obj, key, value)
     In OBJ's property list, set the property named KEY to VALUE.

   Documentation for a procedure can be accessed with the procedure
‘procedure-documentation’.

 -- Scheme Procedure: procedure-documentation proc
 -- C Function: scm_procedure_documentation (proc)
     Return the documentation string associated with ‘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.


File: guile.info,  Node: Procedures with Setters,  Next: Macros,  Prev: Procedure Properties,  Up: Procedures and Macros

5.8.5 Procedures with Setters
-----------------------------

A “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 “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 ‘set!’ (REFFIXME). How it works is best
shown by example.

   Suppose we have a procedure called ‘foo-ref’, which accepts two
arguments, a value of type ‘foo’ and an integer.  The procedure returns
the value stored at the given index in the ‘foo’ object.  Let ‘f’ be a
variable containing such a ‘foo’ data structure.(1)

     (foo-ref f 0)       ⇒ bar
     (foo-ref f 1)       ⇒ braz

   Also suppose that a corresponding setter procedure called ‘foo-set!’
does exist.

     (foo-set! f 0 'bla)
     (foo-ref f 0)       ⇒ bla

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

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

   ‘foo’ can from now an be used to either read from the data structure
stored in ‘f’, or to write into the structure.

     (set! (foo f 0) 'dum)
     (foo f 0)          ⇒ dum

 -- Scheme Procedure: make-procedure-with-setter procedure setter
 -- C Function: scm_make_procedure_with_setter (procedure, setter)
     Create a new procedure which behaves like PROCEDURE, but with the
     associated setter SETTER.

 -- Scheme Procedure: procedure-with-setter? obj
 -- C Function: scm_procedure_with_setter_p (obj)
     Return ‘#t’ if OBJ is a procedure with an associated setter
     procedure.

 -- Scheme Procedure: procedure proc
 -- C Function: scm_procedure (proc)
     Return the procedure of PROC, which must be either a procedure with
     setter, or an operator struct.

 -- Scheme Procedure: setter proc
     Return the setter of PROC, which must be either a procedure with
     setter or an operator struct.

   ---------- Footnotes ----------

   (1) Working definitions would be:
     (define foo-ref vector-ref)
     (define foo-set! vector-set!)
     (define f (make-vector 2 #f))


File: guile.info,  Node: Macros,  Next: Syntax Rules,  Prev: Procedures with Setters,  Up: Procedures and Macros

5.8.6 Lisp Style Macro Definitions
----------------------------------

Macros are objects which cause the expression that they appear in to be
transformed in some way _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:

     (MACRO-NAME MACRO-ARGS ...)

   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, ‘defmacro’ rather than ‘defun’,
and in Scheme, ‘define-macro’ rather than ‘define’.

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

     (defmacro NAME (ARGS ...) BODY ...)

is the same as

     (define-macro (NAME ARGS ...) BODY ...)

The difference is analogous to the corresponding difference between
Lisp's ‘defun’ and Scheme's ‘define’.

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

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

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

     (false-if-exception (open-input-file "may-not-exist"))
     ≡
     (catch #t
            (lambda () (open-input-file "may-not-exist"))
            (lambda args #f))


File: guile.info,  Node: Syntax Rules,  Next: Syntax Case,  Prev: Macros,  Up: Procedures and Macros

5.8.7 The R5RS ‘syntax-rules’ System
------------------------------------

R5RS defines an alternative system for macro and syntax transformations
using the keywords ‘define-syntax’, ‘let-syntax’, ‘letrec-syntax’ and
‘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

   • does not require complicated quoting and extraction of components
     of the source expression using ‘caddr’ etc.

   • 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.

The last point is commonly referred to as being “hygienic”: the R5RS
‘syntax-case’ system provides “hygienic macros”.

   For example, the R5RS pattern language for the ‘false-if-exception’
example of the previous section looks like this:

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

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

* Menu:

* Pattern Language::            The ‘syntax-rules’ pattern language.
* Define-Syntax::               Top level syntax definitions.
* Let-Syntax::                  Local syntax definitions.


File: guile.info,  Node: Pattern Language,  Next: Define-Syntax,  Up: Syntax Rules

5.8.7.1 The ‘syntax-rules’ Pattern Language
...........................................


File: guile.info,  Node: Define-Syntax,  Next: Let-Syntax,  Prev: Pattern Language,  Up: Syntax Rules

5.8.7.2 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>.


File: guile.info,  Node: Let-Syntax,  Prev: Define-Syntax,  Up: Syntax Rules

5.8.7.3 Local Syntax Definitions
................................


File: guile.info,  Node: Syntax Case,  Next: Internal Macros,  Prev: Syntax Rules,  Up: Procedures and Macros

5.8.8 Support for the ‘syntax-case’ System
------------------------------------------


File: guile.info,  Node: Internal Macros,  Prev: Syntax Case,  Up: Procedures and Macros

5.8.9 Internal Representation of Macros and Syntax
--------------------------------------------------

Internally, Guile uses three different flavors of macros.  The three
flavors are called “acro” (or “syntax”), “macro” and “mmacro”.

   Given the expression

     (foo ...)

with ‘foo’ being some flavor of macro, one of the following things will
happen when the expression is evaluated.

   • When ‘foo’ has been defined to be an “acro”, the procedure used in
     the acro definition of ‘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.

   • When ‘foo’ has been defined to be a “macro”, the procedure used in
     the macro definition of ‘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.

   • When ‘foo’ has been defined to be a “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.

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

   The primitives ‘procedure->syntax’, ‘procedure->macro’ and
‘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 ‘defmacro’, ‘define-macro’ (*note Macros::) or
‘define-syntax’ (*note Syntax Rules::) instead.  (In low level terms,
‘defmacro’, ‘define-macro’ and ‘define-syntax’ are all implemented as
mmacros.)

 -- Scheme Procedure: procedure->syntax code
 -- 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 CODE to the expression and the environment.

 -- Scheme Procedure: procedure->macro code
 -- 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 CODE to the expression and the environment.  For example:

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

          (trace foo)
          ≡
          (set! foo (tracef foo 'foo)).

 -- Scheme Procedure: procedure->memoizing-macro code
 -- 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 CODE to the expression and the environment.
     ‘procedure->memoizing-macro’ is the same as ‘procedure->macro’,
     except that the expression returned by CODE replaces the original
     macro expression in the memoized form of the containing code.

   In the following primitives, “acro” flavor macros are referred to as
“syntax transformers”.

 -- Scheme Procedure: macro? obj
 -- C Function: scm_macro_p (obj)
     Return ‘#t’ if OBJ is a regular macro, a memoizing macro or a
     syntax transformer.

 -- Scheme Procedure: macro-type m
 -- C Function: scm_macro_type (m)
     Return one of the symbols ‘syntax’, ‘macro’ or ‘macro!’, depending
     on whether M is a syntax transformer, a regular macro, or a
     memoizing macro, respectively.  If M is not a macro, ‘#f’ is
     returned.

 -- Scheme Procedure: macro-name m
 -- C Function: scm_macro_name (m)
     Return the name of the macro M.

 -- Scheme Procedure: macro-transformer m
 -- C Function: scm_macro_transformer (m)
     Return the transformer of the macro M.

 -- Scheme Procedure: cons-source xorig x y
 -- C Function: scm_cons_source (xorig, x, y)
     Create and return a new pair whose car and cdr are X and Y.  Any
     source properties associated with XORIG are also associated with
     the new pair.


File: guile.info,  Node: Utility Functions,  Next: Binding Constructs,  Prev: Procedures and Macros,  Up: API Reference

5.9 General Utility Functions
=============================

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 “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.


File: guile.info,  Node: Equality,  Next: Object Properties,  Up: Utility Functions

5.9.1 Equality
--------------

There are three kinds of core equality predicates in Scheme, described
below.  The same kinds of comparisons arise in other functions, like
‘memq’ and friends (*note List Searching::).

   For all three tests, objects of different types are never equal.  So
for instance a list and a vector are not ‘equal?’, even if their
contents are the same.  Exact and inexact numbers are considered
different types too, and are hence not equal even if their values are
the same.

   ‘eq?’ tests just for the same object (essentially a pointer
comparison).  This is fast, and can be used when searching for a
particular object, or when working with symbols or keywords (which are
always unique objects).

   ‘eqv?’ extends ‘eq?’ to look at the value of numbers and characters.
It can for instance be used somewhat like ‘=’ (*note Comparison::) but
without an error if one operand isn't a number.

   ‘equal?’ goes further, it looks (recursively) into the contents of
lists, vectors, etc.  This is good for instance on lists that have been
read or calculated in various places and are the same, just not made up
of the same pairs.  Such lists look the same (when printed), and
‘equal?’ will consider them the same.


 -- Scheme Procedure: eq? x y
 -- C Function: scm_eq_p (x, y)
     Return ‘#t’ if X and Y are the same object, except for numbers and
     characters.  For example,

          (define x (vector 1 2 3))
          (define y (vector 1 2 3))

          (eq? x x)  ⇒ #t
          (eq? x y)  ⇒ #f

     Numbers and characters are not equal to any other object, but the
     problem is they're not necessarily ‘eq?’ to themselves either.
     This is even so when the number comes directly from a variable,

          (let ((n (+ 2 3)))
            (eq? n n))       ⇒ *unspecified*

     Generally ‘eqv?’ below should be used when comparing numbers or
     characters.  ‘=’ (*note Comparison::) or ‘char=?’ (*note
     Characters::) can be used too.

     It's worth noting that end-of-list ‘()’, ‘#t’, ‘#f’, a symbol of a
     given name, and a keyword of a given name, are unique objects.
     There's just one of each, so for instance no matter how ‘()’ arises
     in a program, it's the same object and can be compared with ‘eq?’,

          (define x (cdr '(123)))
          (define y (cdr '(456)))
          (eq? x y) ⇒ #t

          (define x (string->symbol "foo"))
          (eq? x 'foo) ⇒ #t

 -- C Function: int scm_is_eq (SCM x, SCM y)
     Return ‘1’ when X and Y are equal in the sense of ‘eq?’, otherwise
     return ‘0’.

     The ‘==’ operator should not be used on ‘SCM’ values, an ‘SCM’ is a
     C type which cannot necessarily be compared using ‘==’ (*note The
     SCM Type::).


 -- Scheme Procedure: eqv? x y
 -- C Function: scm_eqv_p (x, y)
     Return ‘#t’ if X and Y are the same object, or for characters and
     numbers the same value.

     On objects except characters and numbers, ‘eqv?’ is the same as
     ‘eq?’ above, it's true if X and Y are the same object.

     If X and Y are numbers or characters, ‘eqv?’ compares their type
     and value.  An exact number is not ‘eqv?’ to an inexact number
     (even if their value is the same).

          (eqv? 3 (+ 1 2)) ⇒ #t
          (eqv? 1 1.0)     ⇒ #f


 -- Scheme Procedure: equal? x y
 -- C Function: scm_equal_p (x, y)
     Return ‘#t’ if X and Y are the same type, and their contents or
     value are equal.

     For a pair, string, vector, array or structure, ‘equal?’ compares
     the contents, and does so using using the same ‘equal?’
     recursively, so a deep structure can be traversed.

          (equal? (list 1 2 3) (list 1 2 3))   ⇒ #t
          (equal? (list 1 2 3) (vector 1 2 3)) ⇒ #f

     For other objects, ‘equal?’ compares as per ‘eqv?’ above, which
     means characters and numbers are compared by type and value (and
     like ‘eqv?’, exact and inexact numbers are not ‘equal?’, even if
     their value is the same).

          (equal? 3 (+ 1 2)) ⇒ #t
          (equal? 1 1.0)     ⇒ #f

     Hash tables are currently only compared as per ‘eq?’, so two
     different tables are not ‘equal?’, even if their contents are the
     same.

     ‘equal?’ does not support circular data structures, it may go into
     an infinite loop if asked to compare two circular lists or similar.

     New application-defined object types (*note Defining New Types
     (Smobs)::) have an ‘equalp’ handler which is called by ‘equal?’.
     This lets an application traverse the contents or control what is
     considered ‘equal?’ for two objects of such a type.  If there's no
     such handler, the default is to just compare as per ‘eq?’.


File: guile.info,  Node: Object Properties,  Next: Sorting,  Prev: Equality,  Up: Utility Functions

5.9.2 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.

   Guile's representation of an object property is a
procedure-with-setter (*note Procedures with Setters::) that can be used
with the generalized form of ‘set!’ (REFFIXME) to set and retrieve that
property for any Scheme object.  So, setting a property looks like this:

     (set! (my-property obj1) value-for-obj1)
     (set! (my-property obj2) value-for-obj2)

And retrieving values of the same property looks like this:

     (my-property obj1)
     ⇒
     value-for-obj1

     (my-property obj2)
     ⇒
     value-for-obj2

   To create an object property in the first place, use the
‘make-object-property’ procedure:

     (define my-property (make-object-property))

 -- 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.  ‘(set!
     (PROPERTY OBJ) VAL)’ sets OBJ's PROPERTY to VAL.  ‘(PROPERTY OBJ)’
     returns the current setting of OBJ's PROPERTY.

   A single object property created by ‘make-object-property’ can
associate distinct property values with all Scheme values that are
distinguishable by ‘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.


File: guile.info,  Node: Property Primitives,  Next: Old-fashioned Properties,  Up: Object Properties

5.9.2.1 Low Level Property Implementation.
..........................................

 -- Scheme Procedure: primitive-make-property not-found-proc
 -- C Function: scm_primitive_make_property (not_found_proc)
     Create a “property token” that can be used with
     ‘primitive-property-ref’ and ‘primitive-property-set!’.  See
     ‘primitive-property-ref’ for the significance of NOT-FOUND-PROC.

 -- Scheme Procedure: primitive-property-ref prop obj
 -- C Function: scm_primitive_property_ref (prop, obj)
     Return the property PROP of OBJ.

     When no value has yet been associated with PROP and OBJ, the
     NOT-FOUND-PROC from PROP is used.  A call ‘(NOT-FOUND-PROC PROP
     OBJ)’ is made and the result set as the property value.  If
     NOT-FOUND-PROC is ‘#f’ then ‘#f’ is the property value.

 -- Scheme Procedure: primitive-property-set! prop obj val
 -- C Function: scm_primitive_property_set_x (prop, obj, val)
     Set the property PROP of OBJ to VAL.

 -- Scheme Procedure: primitive-property-del! prop obj
 -- C Function: scm_primitive_property_del_x (prop, obj)
     Remove any value associated with PROP and OBJ.


File: guile.info,  Node: Old-fashioned Properties,  Prev: Property Primitives,  Up: Object Properties

5.9.2.2 An Older Approach to Properties
.......................................

Traditionally, Lisp systems provide a different object property
interface to that provided by ‘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
‘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.)

 -- Scheme Procedure: object-properties obj
 -- C Function: scm_object_properties (obj)
     Return OBJ's property list.

 -- Scheme Procedure: set-object-properties! obj alist
 -- C Function: scm_set_object_properties_x (obj, alist)
     Set OBJ's property list to ALIST.

 -- Scheme Procedure: object-property obj key
 -- C Function: scm_object_property (obj, key)
     Return the property of OBJ with name KEY.

 -- Scheme Procedure: set-object-property! obj key value
 -- C Function: scm_set_object_property_x (obj, key, value)
     In OBJ's property list, set the property named KEY to VALUE.


File: guile.info,  Node: Sorting,  Next: Copying,  Prev: Object Properties,  Up: Utility Functions

5.9.3 Sorting
-------------

Sorting is very important in computer programs.  Therefore, Guile comes
with several sorting procedures built-in.  As always, procedures with
names ending in ‘!’ 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.

 -- Scheme Procedure: merge alist blist less
 -- C Function: scm_merge (alist, blist, less)
     Merge two already sorted lists into one.  Given two lists ALIST and
     BLIST, such that ‘(sorted? alist less?)’ and ‘(sorted? blist
     less?)’, return a new list in which the elements of ALIST and BLIST
     have been stably interleaved so that ‘(sorted? (merge alist blist
     less?) less?)’.  Note: this does _not_ accept vectors.

 -- Scheme Procedure: merge! alist blist less
 -- C Function: scm_merge_x (alist, blist, less)
     Takes two lists ALIST and BLIST such that ‘(sorted? alist less?)’
     and ‘(sorted? blist less?)’ and returns a new list in which the
     elements of ALIST and BLIST have been stably interleaved so that
     ‘(sorted? (merge alist blist less?) less?)’.  This is the
     destructive variant of ‘merge’ Note: this does _not_ accept
     vectors.

   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 ‘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.

 -- Scheme Procedure: sorted? items less
 -- C Function: scm_sorted_p (items, less)
     Return ‘#t’ iff ITEMS is a list or a vector such that for all 1 <=
     i <= m, the predicate LESS returns true when applied to all
     elements i - 1 and i

 -- Scheme Procedure: sort items less
 -- C Function: scm_sort (items, less)
     Sort the sequence ITEMS, which may be a list or a vector.  LESS is
     used for comparing the sequence elements.  This is not a stable
     sort.

 -- Scheme Procedure: sort! items less
 -- C Function: scm_sort_x (items, less)
     Sort the sequence ITEMS, which may be a list or a vector.  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.

 -- Scheme Procedure: stable-sort items less
 -- C Function: scm_stable_sort (items, less)
     Sort the sequence ITEMS, which may be a list or a vector.  LESS is
     used for comparing the sequence elements.  This is a stable sort.

 -- Scheme Procedure: stable-sort! items less
 -- C Function: scm_stable_sort_x (items, less)
     Sort the sequence ITEMS, which may be a list or a vector.  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.

   The procedures in the last group only accept lists or vectors as
input, as their names indicate.

 -- Scheme Procedure: sort-list items less
 -- C Function: scm_sort_list (items, less)
     Sort the list ITEMS, using LESS for comparing the list elements.
     This is a stable sort.

 -- Scheme Procedure: sort-list! items less
 -- C Function: scm_sort_list_x (items, less)
     Sort the list ITEMS, using 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.

 -- Scheme Procedure: restricted-vector-sort! vec less startpos endpos
 -- C Function: scm_restricted_vector_sort_x (vec, less, startpos,
          endpos)
     Sort the vector VEC, using LESS for comparing the vector elements.
     STARTPOS (inclusively) and ENDPOS (exclusively) delimit the range
     of the vector which gets sorted.  The return value is not
     specified.


File: guile.info,  Node: Copying,  Next: General Conversion,  Prev: Sorting,  Up: Utility Functions

5.9.4 Copying Deep Structures
-----------------------------

The procedures for copying lists (*note Lists::) only produce a flat
copy of the input list, and currently Guile does not even contain
procedures for copying vectors.  ‘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.

 -- Scheme Procedure: copy-tree obj
 -- C Function: scm_copy_tree (obj)
     Recursively copy the data tree that is bound to OBJ, and return a
     the new data structure.  ‘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.


File: guile.info,  Node: General Conversion,  Next: Hooks,  Prev: Copying,  Up: Utility Functions

5.9.5 General String Conversion
-------------------------------

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.

   ‘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.

 -- Scheme Procedure: object->string obj [printer]
 -- C Function: scm_object_to_string (obj, printer)
     Return a Scheme string obtained by printing OBJ.  Printing function
     can be specified by the optional second argument PRINTER (default:
     ‘write’).


File: guile.info,  Node: Hooks,  Prev: General Conversion,  Up: Utility Functions

5.9.6 Hooks
-----------

A hook is a list of procedures to be called at well defined points in
time.  Typically, an application provides a hook H and promises its
users that it will call all of the procedures in H at a defined point in
the application's processing.  By adding its own procedure to 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 ‘make-hook’.  A procedure can be added to or
removed from a hook using ‘add-hook!’ or ‘remove-hook!’, and all of a
hook's procedures can be removed together using ‘reset-hook!’.  When an
application wants to run a hook, it does so using ‘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.


File: guile.info,  Node: Hook Example,  Next: Hook Reference,  Up: Hooks

5.9.6.1 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.

     (define hook (make-hook 2))
     hook
     ⇒ #<hook 2 40286c90>

   Now we are ready to add some procedures to the newly created hook
with ‘add-hook!’.  In the following example, two procedures are added,
which print different messages and do different things with their
arguments.

     (add-hook! hook (lambda (x y)
                         (display "Foo: ")
                         (display (+ x y))
                         (newline)))
     (add-hook! hook (lambda (x y)
                         (display "Bar: ")
                         (display (* x y))
                         (newline)))

   Once the procedures have been added, we can invoke the hook using
‘run-hook’.

     (run-hook hook 3 4)
     ⊣ Bar: 12
     ⊣ Foo: 7

   Note that the procedures are called in the reverse of the order with
which they were added.  This is because the default behaviour of
‘add-hook!’ is to add its procedure to the _front_ of the hook's
procedure list.  You can force ‘add-hook!’ to add its procedure to the
_end_ of the list instead by providing a third ‘#t’ argument on the
second call to ‘add-hook!’.

     (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)             ; <- Change here!

     (run-hook hook 3 4)
     ⊣ Foo: 7
     ⊣ Bar: 12


File: guile.info,  Node: Hook Reference,  Next: C Hooks,  Prev: Hook Example,  Up: Hooks

5.9.6.2 Hook Reference
......................

When you create a hook with ‘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 ‘make-hook’, it defaults to zero.
All procedures of a given hook must have the same arity, and when the
procedures are invoked using ‘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 ‘add-hook!’ is omitted or is equal to ‘#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 ‘run-hook’.

   The ordering of the list of procedures returned by ‘hook->list’
matches the order in which those procedures would be called if the hook
was run using ‘run-hook’.

   Note that the C functions in the following entries are for handling
“Scheme-level” hooks in C. There are also “C-level” hooks which have
their own interface (*note C Hooks::).

 -- Scheme Procedure: make-hook [n_args]
 -- C Function: scm_make_hook (n_args)
     Create a hook for storing procedure of arity N_ARGS.  N_ARGS
     defaults to zero.  The returned value is a hook object to be used
     with the other hook procedures.

 -- Scheme Procedure: hook? x
 -- C Function: scm_hook_p (x)
     Return ‘#t’ if X is a hook, ‘#f’ otherwise.

 -- Scheme Procedure: hook-empty? hook
 -- C Function: scm_hook_empty_p (hook)
     Return ‘#t’ if HOOK is an empty hook, ‘#f’ otherwise.

 -- Scheme Procedure: add-hook! hook proc [append_p]
 -- C Function: scm_add_hook_x (hook, proc, append_p)
     Add the procedure PROC to the hook HOOK.  The procedure is added to
     the end if APPEND_P is true, otherwise it is added to the front.
     The return value of this procedure is not specified.

 -- Scheme Procedure: remove-hook! hook proc
 -- C Function: scm_remove_hook_x (hook, proc)
     Remove the procedure PROC from the hook HOOK.  The return value of
     this procedure is not specified.

 -- Scheme Procedure: reset-hook! hook
 -- C Function: scm_reset_hook_x (hook)
     Remove all procedures from the hook HOOK.  The return value of this
     procedure is not specified.

 -- Scheme Procedure: hook->list hook
 -- C Function: scm_hook_to_list (hook)
     Convert the procedure list of HOOK to a list.

 -- Scheme Procedure: run-hook hook . args
 -- C Function: scm_run_hook (hook, args)
     Apply all procedures from the hook HOOK to the arguments ARGS.  The
     order of the procedure application is first to last.  The return
     value of this procedure is not specified.

   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 ‘scm_c_run_hook’,
which is identical to ‘scm_run_hook’ but does no type checking.

 -- C Function: void scm_c_run_hook (SCM hook, SCM args)
     The same as ‘scm_run_hook’ but without any type checking to confirm
     that HOOK is actually a hook object and that ARGS is a well-formed
     list matching the arity of the hook.

   For C code, ‘SCM_HOOKP’ is a faster alternative to ‘scm_hook_p’:

 -- C Macro: int SCM_HOOKP (x)
     Return 1 if X is a Scheme-level hook, 0 otherwise.

5.9.6.3 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.

     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) */


File: guile.info,  Node: C Hooks,  Next: GC Hooks,  Prev: Hook Reference,  Up: Hooks

5.9.6.4 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 ... 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 ‘scm_t_c_hook’ and then initialize it using ‘scm_c_hook_init’.

 -- C Type: scm_t_c_hook
     Data type for a C hook.  The internals of this type should be
     treated as opaque.

 -- C Enum: scm_t_c_hook_type
     Enumeration of possible hook types, which are:

     ‘SCM_C_HOOK_NORMAL’
          Type of hook for which all the registered functions will
          always be called.
     ‘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).
     ‘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).

 -- 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 HOOK.  TYPE should be
     one of the values of the ‘scm_t_c_hook_type’ enumeration, and
     controls how the hook functions will be called.  HOOK_DATA is a
     closure parameter that will be passed to all registered hook
     functions when they are called.

   To add or remove a C function from a C hook, use ‘scm_c_hook_add’ or
‘scm_c_hook_remove’.  A hook function must expect three ‘void *’
parameters which are, respectively:

HOOK_DATA
     The hook closure data that was specified at the time the hook was
     initialized by ‘scm_c_hook_init’.

FUNC_DATA
     The function closure data that was specified at the time that that
     function was registered with the hook by ‘scm_c_hook_add’.

DATA
     The call closure data specified by the ‘scm_c_hook_run’ call that
     runs the hook.

 -- C Type: scm_t_c_hook_function
     Function type for a C hook function: takes three ‘void *’
     parameters and returns a ‘void *’ result.

 -- 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 FUNC, with function closure data FUNC_DATA, to the C
     hook HOOK.  The new function is appended to the hook's list of
     functions if APPENDP is non-zero, otherwise prepended.

 -- C Function: void scm_c_hook_remove (scm_t_c_hook *hook,
          scm_t_c_hook_function func, void *func_data)
     Remove function FUNC, with function closure data FUNC_DATA, from
     the C hook HOOK.  ‘scm_c_hook_remove’ checks both FUNC and
     FUNC_DATA so as to allow for the same FUNC being registered
     multiple times with different closure data.

   Finally, to invoke a C hook, call the ‘scm_c_hook_run’ function
specifying the hook and the call closure data for this run:

 -- C Function: void * scm_c_hook_run (scm_t_c_hook *hook, void *data)
     Run the C hook HOOK will call closure data DATA.  Subject to the
     variations for hook types ‘SCM_C_HOOK_OR’ and ‘SCM_C_HOOK_AND’,
     ‘scm_c_hook_run’ calls HOOK's registered functions in turn, passing
     them the hook's closure data, each function's closure data, and the
     call closure data.

     ‘scm_c_hook_run’'s return value is the return value of the last
     function to be called.


File: guile.info,  Node: GC Hooks,  Next: REPL Hooks,  Prev: C Hooks,  Up: Hooks

5.9.6.5 Hooks for Garbage Collection
....................................

Whenever Guile performs a garbage collection, it calls the following
hooks in the order shown.

 -- C Hook: scm_before_gc_c_hook
     C hook called at the very start of a garbage collection, after
     setting ‘scm_gc_running_p’ to 1, but before entering the GC
     critical section.

     If garbage collection is blocked because ‘scm_block_gc’ is
     non-zero, GC exits early soon after calling this hook, and no
     further hooks will be called.

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

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

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

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

 -- Scheme Hook: after-gc-hook
     Scheme hook with arity 0.  This hook is run asynchronously (*note
     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 ‘scm_after_gc_hook’.)

   All the C hooks listed here have type ‘SCM_C_HOOK_NORMAL’, are
initialized with hook closure data NULL, are are invoked by
‘scm_c_hook_run’ with call closure data NULL.

   The Scheme hook ‘after-gc-hook’ is particularly useful in conjunction
with guardians (*note 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 ‘after-gc-hook’, you can
ensure that your guardian is tested after every garbage collection
cycle.


File: guile.info,  Node: REPL Hooks,  Prev: GC Hooks,  Up: Hooks

5.9.6.6 Hooks into the Guile REPL
.................................


File: guile.info,  Node: Binding Constructs,  Next: Control Mechanisms,  Prev: Utility Functions,  Up: API Reference

5.10 Definitions and Variable Bindings
======================================

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.


File: guile.info,  Node: Top Level,  Next: Local Bindings,  Up: Binding Constructs

5.10.1 Top Level Variable Definitions
-------------------------------------

On the top level of a program (i.e.  when not inside the body of a
procedure definition or a ‘let’, ‘let*’ or ‘letrec’ expression), a
definition of the form

     (define a VALUE)

defines a variable called ‘a’ and sets it to the value VALUE.

   If the variable already exists, because it has already been created
by a previous ‘define’ expression with the same name, its value is
simply changed to the new VALUE.  In this case, then, the above form is
completely equivalent to

     (set! a VALUE)

This equivalence means that ‘define’ can be used interchangeably with
‘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
‘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 ‘define’ and ‘set!’ are not always equivalent.
For example, a ‘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.

 -- Scheme Syntax: define name value
     Create a top level variable named NAME with value VALUE.  If the
     named variable already exists, just change its value.  The return
     value of a ‘define’ expression is unspecified.

   The C API equivalents of ‘define’ are ‘scm_define’ and
‘scm_c_define’, which differ from each other in whether the variable
name is specified as a ‘SCM’ symbol or as a null-terminated C string.

 -- C Function: scm_define (sym, value)
 -- C Function: scm_c_define (const char *name, value)
     C equivalents of ‘define’, with variable name specified either by
     SYM, a symbol, or by NAME, a null-terminated C string.  Both
     variants return the new or preexisting variable object.

   ‘define’ (when it occurs at top level), ‘scm_define’ and
‘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 (*note
Local Bindings::) act differently (*note Internal Definitions::).


File: guile.info,  Node: Local Bindings,  Next: Internal Definitions,  Prev: Top Level,  Up: Binding Constructs

5.10.2 Local Variable Bindings
------------------------------

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 (‘let’, ‘let*’ and ‘letrec’),
the Scheme language has a block structure like most other programming
languages since the days of ALGOL 60.  Readers familiar to languages
like C or Java should already be used to this concept, but the family of
‘let’ expressions has a few properties which are well worth knowing.

   The first local binding construct is ‘let’.  The other constructs
‘let*’ and ‘letrec’ are specialized versions for usage where using plain
‘let’ is a bit inconvenient.

 -- syntax: let bindings body
     BINDINGS has the form

          ((VARIABLE1 INIT1) ...)

     that is zero or more two-element lists of a variable and an
     arbitrary expression each.  All VARIABLE names must be distinct.

     A ‘let’ expression is evaluated as follows.

        • All INIT expressions are evaluated.

        • New storage is allocated for the VARIABLES.

        • The values of the INIT expressions are stored into the
          variables.

        • The expressions in BODY are evaluated in order, and the value
          of the last expression is returned as the value of the ‘let’
          expression.

        • The storage for the VARIABLES is freed.

     The INIT expressions are not allowed to refer to any of the
     VARIABLES.

 -- syntax: let* bindings body
     Similar to ‘let’, but the variable bindings are performed
     sequentially, that means that all INIT expression are allowed to
     use the variables defined on their left in the binding list.

     A ‘let*’ expression can always be expressed with nested ‘let’
     expressions.

          (let* ((a 1) (b a))
             b)
          ≡
          (let ((a 1))
            (let ((b a))
              b))

 -- syntax: letrec bindings body
     Similar to ‘let’, but it is possible to refer to the VARIABLE from
     lambda expression created in any of the INITS.  That is, procedures
     created in the INIT expression can recursively refer to the defined
     variables.

          (letrec ((even?
                    (lambda (n)
                        (if (zero? n)
                            #t
                            (odd? (- n 1)))))
                   (odd?
                    (lambda (n)
                        (if (zero? n)
                            #f
                            (even? (- n 1))))))
            (even? 88))
          ⇒
          #t

   There is also an alternative form of the ‘let’ form, which is used
for expressing iteration.  Because of the use as a looping construct,
this form (the “named let”) is documented in the section about iteration
(*note Iteration: while do.)


File: guile.info,  Node: Internal Definitions,  Next: Binding Reflection,  Prev: Local Bindings,  Up: Binding Constructs

5.10.3 Internal definitions
---------------------------

A ‘define’ form which appears inside the body of a ‘lambda’, ‘let’,
‘let*’, ‘letrec’ or equivalent expression is called an “internal
definition”.  An internal definition differs from a top level definition
(*note Top Level::), because the definition is only visible inside the
complete body of the enclosing form.  Let us examine the following
example.

     (let ((frumble "froz"))
        (define banana (lambda () (apple 'peach)))
        (define apple (lambda (x) x))
        (banana))
     ⇒
     peach

   Here the enclosing form is a ‘let’, so the ‘define’s in the
‘let’-body are internal definitions.  Because the scope of the internal
definitions is the *complete* body of the ‘let’-expression, the
‘lambda’-expression which gets bound to the variable ‘banana’ may refer
to the variable ‘apple’, even though it's definition appears lexically
_after_ the definition of ‘banana’.  This is because a sequence of
internal definition acts as if it were a ‘letrec’ expression.

     (let ()
       (define a 1)
       (define b 2)
       (+ a b))

is equivalent to

     (let ()
       (letrec ((a 1) (b 2))
         (+ a b)))

   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 ‘set!’, an exception is thrown for internal definitions with
duplicate bindings.


File: guile.info,  Node: Binding Reflection,  Prev: Internal Definitions,  Up: Binding Constructs

5.10.4 Querying variable bindings
---------------------------------

Guile provides a procedure for checking whether a symbol is bound in the
top level environment.

 -- Scheme Procedure: defined? sym [env]
 -- C Function: scm_defined_p (sym, env)
     Return ‘#t’ if SYM is defined in the lexical environment ENV.  When
     ENV is not specified, look in the top-level environment as defined
     by the current module.


File: guile.info,  Node: Control Mechanisms,  Next: Input and Output,  Prev: Binding Constructs,  Up: API Reference

5.11 Controlling the Flow of Program Execution
==============================================

See *note Control Flow:: for a discussion of how the more general
control flow of Scheme affects C code.

* Menu:

* begin::                       Evaluating a sequence of expressions.
* if cond case::                Simple conditional evaluation.
* and or::                      Conditional evaluation of a sequence.
* while do::                    Iteration mechanisms.
* Continuations::               Continuations.
* Multiple Values::             Returning and accepting multiple values.
* Exceptions::                  Throwing and catching exceptions.
* Error Reporting::             Procedures for signaling errors.
* Dynamic Wind::                Dealing with non-local entrance/exit.
* Handling Errors::             How to handle errors in C code.


File: guile.info,  Node: begin,  Next: if cond case,  Up: Control Mechanisms

5.11.1 Evaluating a Sequence of Expressions
-------------------------------------------

The ‘begin’ syntax is used for grouping several expressions together so
that they are treated as if they were one expression.  This is
particularly important when syntactic expressions are used which only
allow one expression, but the programmer wants to use more than one
expression in that place.  As an example, consider the conditional
expression below:

     (if (> x 0)
         (begin (display "greater") (newline)))

   If the two calls to ‘display’ and ‘newline’ were not embedded in a
‘begin’-statement, the call to ‘newline’ would get misinterpreted as the
else-branch of the ‘if’-expression.

 -- syntax: begin expr1 expr2 ...
     The expression(s) are evaluated in left-to-right order and the
     value of the last expression is returned as the value of the
     ‘begin’-expression.  This expression type is used when the
     expressions before the last one are evaluated for their side
     effects.

     Guile also allows the expression ‘(begin)’, a ‘begin’ with no
     sub-expressions.  Such an expression returns the 'unspecified'
     value.


File: guile.info,  Node: if cond case,  Next: and or,  Prev: begin,  Up: Control Mechanisms

5.11.2 Simple Conditional Evaluation
------------------------------------

Guile provides three syntactic constructs for conditional evaluation.
‘if’ is the normal if-then-else expression (with an optional else
branch), ‘cond’ is a conditional expression with multiple branches and
‘case’ branches if an expression has one of a set of constant values.

 -- syntax: if test consequent [alternate]
     All arguments may be arbitrary expressions.  First, TEST is
     evaluated.  If it returns a true value, the expression CONSEQUENT
     is evaluated and ALTERNATE is ignored.  If TEST evaluates to ‘#f’,
     ALTERNATE is evaluated instead.  The value of the evaluated branch
     (CONSEQUENT or ALTERNATE) is returned as the value of the ‘if’
     expression.

     When ALTERNATE is omitted and the TEST evaluates to ‘#f’, the value
     of the expression is not specified.

 -- syntax: cond clause1 clause2 ...
     Each ‘cond’-clause must look like this:

          (TEST EXPRESSION ...)

     where TEST and EXPRESSION are arbitrary expression, or like this

          (TEST => EXPRESSION)

     where EXPRESSION must evaluate to a procedure.

     The TESTs of the clauses are evaluated in order and as soon as one
     of them evaluates to a true values, the corresponding EXPRESSIONs
     are evaluated in order and the last value is returned as the value
     of the ‘cond’-expression.  For the ‘=>’ clause type, EXPRESSION is
     evaluated and the resulting procedure is applied to the value of
     TEST.  The result of this procedure application is then the result
     of the ‘cond’-expression.

     One additional ‘cond’-clause is available as an extension to
     standard Scheme:

          (TEST GUARD => EXPRESSION)

     where GUARD and EXPRESSION must evaluate to procedures.  For this
     clause type, TEST may return multiple values, and ‘cond’ ignores
     its boolean state; instead, ‘cond’ evaluates GUARD and applies the
     resulting procedure to the value(s) of TEST, as if GUARD were the
     CONSUMER argument of ‘call-with-values’.  Iff the result of that
     procedure call is a true value, it evaluates EXPRESSION and applies
     the resulting procedure to the value(s) of TEST, in the same manner
     as the GUARD was called.

     The TEST of the last CLAUSE may be the symbol ‘else’.  Then, if
     none of the preceding TESTs is true, the EXPRESSIONs following the
     ‘else’ are evaluated to produce the result of the
     ‘cond’-expression.

 -- syntax: case key clause1 clause2 ...
     KEY may be any expression, the CLAUSEs must have the form

          ((DATUM1 ...) EXPR1 EXPR2 ...)

     and the last CLAUSE may have the form

          (else EXPR1 EXPR2 ...)

     All DATUMs must be distinct.  First, KEY is evaluated.  The the
     result of this evaluation is compared against all DATUMs using
     ‘eqv?’.  When this comparison succeeds, the expression(s) following
     the DATUM are evaluated from left to right, returning the value of
     the last expression as the result of the ‘case’ expression.

     If the KEY matches no DATUM and there is an ‘else’-clause, the
     expressions following the ‘else’ are evaluated.  If there is no
     such clause, the result of the expression is unspecified.


File: guile.info,  Node: and or,  Next: while do,  Prev: if cond case,  Up: Control Mechanisms

5.11.3 Conditional Evaluation of a Sequence of Expressions
----------------------------------------------------------

‘and’ and ‘or’ evaluate all their arguments in order, similar to
‘begin’, but evaluation stops as soon as one of the expressions
evaluates to false or true, respectively.

 -- syntax: and expr ...
     Evaluate the EXPRs from left to right and stop evaluation as soon
     as one expression evaluates to ‘#f’; the remaining expressions are
     not evaluated.  The value of the last evaluated expression is
     returned.  If no expression evaluates to ‘#f’, the value of the
     last expression is returned.

     If used without expressions, ‘#t’ is returned.

 -- syntax: or expr ...
     Evaluate the EXPRs from left to right and stop evaluation as soon
     as one expression evaluates to a true value (that is, a value
     different from ‘#f’); the remaining expressions are not evaluated.
     The value of the last evaluated expression is returned.  If all
     expressions evaluate to ‘#f’, ‘#f’ is returned.

     If used without expressions, ‘#f’ is returned.


File: guile.info,  Node: while do,  Next: Continuations,  Prev: and or,  Up: Control Mechanisms

5.11.4 Iteration mechanisms
---------------------------

Scheme has only few iteration mechanisms, mainly because iteration in
Scheme programs is normally expressed using recursion.  Nevertheless,
R5RS defines a construct for programming loops, calling ‘do’.  In
addition, Guile has an explicit looping syntax called ‘while’.

 -- syntax: do ((variable init [step]) ...) (test [expr ...]) body ...
     Bind VARIABLEs and evaluate BODY until TEST is true.  The return
     value is the last EXPR after TEST, if given.  A simple example will
     illustrate the basic form,

          (do ((i 1 (1+ i)))
              ((> i 4))
            (display i))
          ⊣ 1234

     Or with two variables and a final return value,

          (do ((i 1 (1+ i))
               (p 3 (* 3 p)))
              ((> i 4)
               p)
            (format #t "3**~s is ~s\n" i p))
          ⊣
          3**1 is 3
          3**2 is 9
          3**3 is 27
          3**4 is 81
          ⇒
          789

     The VARIABLE bindings are established like a ‘let’, in that the
     expressions are all evaluated and then all bindings made.  When
     iterating, the optional STEP expressions are evaluated with the
     previous bindings in scope, then new bindings all made.

     The TEST expression is a termination condition.  Looping stops when
     the TEST is true.  It's evaluated before running the BODY each
     time, so if it's true the first time then BODY is not run at all.

     The optional EXPRs after the TEST are evaluated at the end of
     looping, with the final VARIABLE bindings available.  The last EXPR
     gives the return value, or if there are no EXPRs the return value
     is unspecified.

     Each iteration establishes bindings to fresh locations for the
     VARIABLEs, like a new ‘let’ for each iteration.  This is done for
     VARIABLEs without STEP expressions too.  The following illustrates
     this, showing how a new ‘i’ is captured by the ‘lambda’ in each
     iteration (*note The Concept of Closure: About Closure.).

          (define lst '())
          (do ((i 1 (1+ i)))
              ((> i 4))
            (set! lst (cons (lambda () i) lst)))
          (map (lambda (proc) (proc)) lst)
          ⇒
          (4 3 2 1)

 -- syntax: while cond body ...
     Run a loop executing the BODY forms while COND is true.  COND is
     tested at the start of each iteration, so if it's ‘#f’ the first
     time then BODY is not executed at all.  The return value is
     unspecified.

     Within ‘while’, two extra bindings are provided, they can be used
     from both COND and BODY.

      -- Scheme Procedure: break
          Break out of the ‘while’ form.

      -- Scheme Procedure: continue
          Abandon the current iteration, go back to the start and test
          COND again, etc.

     Each ‘while’ form gets its own ‘break’ and ‘continue’ procedures,
     operating on that ‘while’.  This means when loops are nested the
     outer ‘break’ can be used to escape all the way out.  For example,

          (while (test1)
            (let ((outer-break break))
              (while (test2)
                (if (something)
                  (outer-break #f))
                ...)))

     Note that each ‘break’ and ‘continue’ procedure can only be used
     within the dynamic extent of its ‘while’.  Outside the ‘while’
     their behaviour is unspecified.

   Another very common way of expressing iteration in Scheme programs is
the use of the so-called “named let”.

   Named let is a variant of ‘let’ which creates a procedure and calls
it in one step.  Because of the newly created procedure, named let is
more powerful than ‘do’-it can be used for iteration, but also for
arbitrary recursion.

 -- syntax: let variable bindings body
     For the definition of BINDINGS see the documentation about ‘let’
     (*note Local Bindings::).

     Named ‘let’ works as follows:

        • A new procedure which accepts as many arguments as are in
          BINDINGS is created and bound locally (using ‘let’) to
          VARIABLE.  The new procedure's formal argument names are the
          name of the VARIABLES.

        • The BODY expressions are inserted into the newly created
          procedure.

        • The procedure is called with the INIT expressions as the
          formal arguments.

     The next example implements a loop which iterates (by recursion)
     1000 times.

          (let lp ((x 1000))
            (if (positive? x)
                (lp (- x 1))
                x))
          ⇒
          0


File: guile.info,  Node: Continuations,  Next: Multiple Values,  Prev: while do,  Up: Control Mechanisms

5.11.5 Continuations
--------------------

A "continuation" is the code that will execute when a given function or
expression returns.  For example, consider

     (define (foo)
       (display "hello\n")
       (display (bar)) (newline)
       (exit))

   The continuation from the call to ‘bar’ comprises a ‘display’ of the
value returned, a ‘newline’ and an ‘exit’.  This can be expressed as a
function of one argument.

     (lambda (r)
       (display r) (newline)
       (exit))

   In Scheme, continuations are represented as special procedures just
like this.  The special property is that when a continuation is called
it abandons the current program location and jumps directly to that
represented by the continuation.

   A continuation is like a dynamic label, capturing at run-time a point
in program execution, including all the nested calls that have lead to
it (or rather the code that will execute when those calls return).

   Continuations are created with the following functions.

 -- Scheme Procedure: call-with-current-continuation proc
 -- Scheme Procedure: call/cc proc
     Capture the current continuation and call ‘(PROC CONT)’ with it.
     The return value is the value returned by PROC, or when ‘(CONT
     VALUE)’ is later invoked, the return is the VALUE passed.

     Normally CONT should be called with one argument, but when the
     location resumed is expecting multiple values (*note Multiple
     Values::) then they should be passed as multiple arguments, for
     instance ‘(CONT X Y Z)’.

     CONT may only be used from the same side of a continuation barrier
     as it was created (*note Continuation Barriers::), and in a
     multi-threaded program only from the thread in which it was
     created.

     The call to PROC is not part of the continuation captured, it runs
     only when the continuation is created.  Often a program will want
     to store CONT somewhere for later use; this can be done in PROC.

     The ‘call’ in the name ‘call-with-current-continuation’ refers to
     the way a call to PROC gives the newly created continuation.  It's
     not related to the way a call is used later to invoke that
     continuation.

     ‘call/cc’ is an alias for ‘call-with-current-continuation’.  This
     is in common use since the latter is rather long.

 -- C Function: SCM scm_make_continuation (int *first)
     Capture the current continuation as described above.  The return
     value is the new continuation, and *FIRST is set to 1.

     When the continuation is invoked, ‘scm_make_continuation’ will
     return again, this time returning the value (or set of multiple
     values) passed in that invocation, and with *FIRST set to 0.


Here is a simple example,

     (define kont #f)
     (format #t "the return is ~a\n"
             (call/cc (lambda (k)
                        (set! kont k)
                        1)))
     ⇒ the return is 1

     (kont 2)
     ⇒ the return is 2

   ‘call/cc’ captures a continuation in which the value returned is
going to be displayed by ‘format’.  The ‘lambda’ stores this in ‘kont’
and gives an initial return ‘1’ which is displayed.  The later
invocation of ‘kont’ resumes the captured point, but this time returning
‘2’, which is displayed.

   When Guile is run interactively, a call to ‘format’ like this has an
implicit return back to the read-eval-print loop.  ‘call/cc’ captures
that like any other return, which is why interactively ‘kont’ will come
back to read more input.


   C programmers may note that ‘call/cc’ is like ‘setjmp’ in the way it
records at runtime a point in program execution.  A call to a
continuation is like a ‘longjmp’ in that it abandons the present
location and goes to the recorded one.  Like ‘longjmp’, the value passed
to the continuation is the value returned by ‘call/cc’ on resuming
there.  However ‘longjmp’ can only go up the program stack, but the
continuation mechanism can go anywhere.

   When a continuation is invoked, ‘call/cc’ and subsequent code
effectively "returns" a second time.  It can be confusing to imagine a
function returning more times than it was called.  It may help instead
to think of it being stealthily re-entered and then program flow going
on as normal.

   ‘dynamic-wind’ (*note Dynamic Wind::) can be used to ensure setup and
cleanup code is run when a program locus is resumed or abandoned through
the continuation mechanism.


   Continuations are a powerful mechanism, and can be used to implement
almost any sort of control structure, such as loops, coroutines, or
exception handlers.

   However the implementation of continuations in Guile is not as
efficient as one might hope, because Guile is designed to cooperate with
programs written in other languages, such as C, which do not know about
continuations.  Basically continuations are captured by a block copy of
the stack, and resumed by copying back.

   For this reason, generally continuations should be used only when
there is no other simple way to achieve the desired result, or when the
elegance of the continuation mechanism outweighs the need for
performance.

   Escapes upwards from loops or nested functions are generally best
handled with exceptions (*note Exceptions::).  Coroutines can be
efficiently implemented with cooperating threads (a thread holds a full
program stack but doesn't copy it around the way continuations do).


File: guile.info,  Node: Multiple Values,  Next: Exceptions,  Prev: Continuations,  Up: Control Mechanisms

5.11.6 Returning and Accepting Multiple Values
----------------------------------------------

Scheme allows a procedure to return more than one value to its caller.
This is quite different to other languages which only allow single-value
returns.  Returning multiple values is different from returning a list
(or pair or vector) of values to the caller, because conceptually not
_one_ compound object is returned, but several distinct values.

   The primitive procedures for handling multiple values are ‘values’
and ‘call-with-values’.  ‘values’ is used for returning multiple values
from a procedure.  This is done by placing a call to ‘values’ with zero
or more arguments in tail position in a procedure body.
‘call-with-values’ combines a procedure returning multiple values with a
procedure which accepts these values as parameters.

 -- Scheme Procedure: values arg1 ... argN
 -- C Function: scm_values (args)
     Delivers all of its arguments to its continuation.  Except for
     continuations created by the ‘call-with-values’ procedure, all
     continuations take exactly one value.  The effect of passing no
     value or more than one value to continuations that were not created
     by ‘call-with-values’ is unspecified.

     For ‘scm_values’, ARGS is a list of arguments and the return is a
     multiple-values object which the caller can return.  In the current
     implementation that object shares structure with ARGS, so ARGS
     should not be modified subsequently.

 -- Scheme Procedure: call-with-values producer consumer
     Calls its PRODUCER argument with no values and a continuation that,
     when passed some values, calls the CONSUMER procedure with those
     values as arguments.  The continuation for the call to CONSUMER is
     the continuation of the call to ‘call-with-values’.

          (call-with-values (lambda () (values 4 5))
                            (lambda (a b) b))
          ⇒ 5

          (call-with-values * -)
          ⇒ -1

   In addition to the fundamental procedures described above, Guile has
a module which exports a syntax called ‘receive’, which is much more
convenient.  This is in the ‘(ice-9 receive)’ and is the same as
specified by SRFI-8 (*note SRFI-8::).

     (use-modules (ice-9 receive))

 -- library syntax: receive formals expr body ...
     Evaluate the expression EXPR, and bind the result values (zero or
     more) to the formal arguments in FORMALS.  FORMALS is a list of
     symbols, like the argument list in a ‘lambda’ (*note Lambda::).
     After binding the variables, the expressions in BODY ... are
     evaluated in order, the return value is the result from the last
     expression.

     For example getting results from ‘partition’ in SRFI-1 (*note
     SRFI-1::),

          (receive (odds evens)
              (partition odd? '(7 4 2 8 3))
            (display odds)
            (display " and ")
            (display evens))
          ⊣ (7 3) and (4 2 8)


File: guile.info,  Node: Exceptions,  Next: Error Reporting,  Prev: Multiple Values,  Up: Control Mechanisms

5.11.7 Exceptions
-----------------

A common requirement in applications is to want to jump “non-locally”
from the depths of a computation back to, say, the application's main
processing loop.  Usually, the place that is the target of the jump is
somewhere in the calling stack of procedures that called the procedure
that wants to jump back.  For example, typical logic for a key press
driven application might look something like this:

     main-loop:
       read the next key press and call dispatch-key

     dispatch-key:
       lookup the key in a keymap and call an appropriate procedure,
       say find-file

     find-file:
       interactively read the required file name, then call
       find-specified-file

     find-specified-file:
       check whether file exists; if not, jump back to main-loop
       ...

   The jump back to ‘main-loop’ could be achieved by returning through
the stack one procedure at a time, using the return value of each
procedure to indicate the error condition, but Guile (like most modern
programming languages) provides an additional mechanism called
“exception handling” that can be used to implement such jumps much more
conveniently.

* Menu:

* Exception Terminology::       Different ways to say the same thing.
* Catch::                       Setting up to catch exceptions.
* Throw Handlers::              Adding extra handling to a throw.
* Lazy Catch::                  Catch without unwinding the stack.
* Throw::                       Throwing an exception.
* Exception Implementation::    How Guile implements exceptions.


File: guile.info,  Node: Exception Terminology,  Next: Catch,  Up: Exceptions

5.11.7.1 Exception Terminology
..............................

There are several variations on the terminology for dealing with
non-local jumps.  It is useful to be aware of them, and to realize that
they all refer to the same basic mechanism.

   • Actually making a non-local jump may be called “raising an
     exception”, “raising a signal”, “throwing an exception” or “doing a
     long jump”.  When the jump indicates an error condition, people may
     talk about “signalling”, “raising” or “throwing” “an error”.

   • Handling the jump at its target may be referred to as “catching” or
     “handling” the “exception”, “signal” or, where an error condition
     is involved, “error”.

   Where “signal” and “signalling” are used, special care is needed to
avoid the risk of confusion with POSIX signals.

   This manual prefers to speak of throwing and catching exceptions,
since this terminology matches the corresponding Guile primitives.


File: guile.info,  Node: Catch,  Next: Throw Handlers,  Prev: Exception Terminology,  Up: Exceptions

5.11.7.2 Catching Exceptions
............................

‘catch’ is used to set up a target for a possible non-local jump.  The
arguments of a ‘catch’ expression are a “key”, which restricts the set
of exceptions to which this ‘catch’ applies, a thunk that specifies the
code to execute and one or two “handler” procedures that say what to do
if an exception is thrown while executing the code.  If the execution
thunk executes “normally”, which means without throwing any exceptions,
the handler procedures are not called at all.

   When an exception is thrown using the ‘throw’ function, the first
argument of the ‘throw’ is a symbol that indicates the type of the
exception.  For example, Guile throws an exception using the symbol
‘numerical-overflow’ to indicate numerical overflow errors such as
division by zero:

     (/ 1 0)
     ⇒
     ABORT: (numerical-overflow)

   The KEY argument in a ‘catch’ expression corresponds to this symbol.
KEY may be a specific symbol, such as ‘numerical-overflow’, in which
case the ‘catch’ applies specifically to exceptions of that type; or it
may be ‘#t’, which means that the ‘catch’ applies to all exceptions,
irrespective of their type.

   The second argument of a ‘catch’ expression should be a thunk (i.e.
a procedure that accepts no arguments) that specifies the normal case
code.  The ‘catch’ is active for the execution of this thunk, including
any code called directly or indirectly by the thunk's body.  Evaluation
of the ‘catch’ expression activates the catch and then calls this thunk.

   The third argument of a ‘catch’ expression is a handler procedure.
If an exception is thrown, this procedure is called with exactly the
arguments specified by the ‘throw’.  Therefore, the handler procedure
must be designed to accept a number of arguments that corresponds to the
number of arguments in all ‘throw’ expressions that can be caught by
this ‘catch’.

   The fourth, optional argument of a ‘catch’ expression is another
handler procedure, called the “pre-unwind” handler.  It differs from the
third argument in that if an exception is thrown, it is called, _before_
the third argument handler, in exactly the dynamic context of the
‘throw’ expression that threw the exception.  This means that it is
useful for capturing or displaying the stack at the point of the
‘throw’, or for examining other aspects of the dynamic context, such as
fluid values, before the context is unwound back to that of the
prevailing ‘catch’.

 -- Scheme Procedure: catch key thunk handler [pre-unwind-handler]
 -- C Function: scm_catch_with_pre_unwind_handler (key, thunk, handler,
          pre_unwind_handler)
 -- C Function: scm_catch (key, thunk, handler)
     Invoke THUNK in the dynamic context of HANDLER for exceptions
     matching KEY.  If thunk throws to the symbol KEY, then HANDLER is
     invoked this way:
          (handler key args ...)

     KEY is a symbol or ‘#t’.

     THUNK takes no arguments.  If THUNK returns normally, that is the
     return value of ‘catch’.

     Handler is invoked outside the scope of its own ‘catch’.  If
     HANDLER again throws to the same key, a new handler from further up
     the call chain is invoked.

     If the key is ‘#t’, then a throw to _any_ symbol will match this
     call to ‘catch’.

     If a PRE-UNWIND-HANDLER is given and THUNK throws an exception that
     matches KEY, Guile calls the PRE-UNWIND-HANDLER before unwinding
     the dynamic state and invoking the main HANDLER.
     PRE-UNWIND-HANDLER should be a procedure with the same signature as
     HANDLER, that is ‘(lambda (key . args))’.  It is typically used to
     save the stack at the point where the exception occurred, but can
     also query other parts of the dynamic state at that point, such as
     fluid values.

     A PRE-UNWIND-HANDLER can exit either normally or non-locally.  If
     it exits normally, Guile unwinds the stack and dynamic context and
     then calls the normal (third argument) handler.  If it exits
     non-locally, that exit determines the continuation.

   If a handler procedure needs to match a variety of ‘throw’
expressions with varying numbers of arguments, you should write it like
this:

     (lambda (key . args)
       ...)

The KEY argument is guaranteed always to be present, because a ‘throw’
without a KEY is not valid.  The number and interpretation of the ARGS
varies from one type of exception to another, but should be specified by
the documentation for each exception type.

   Note that, once the normal (post-unwind) handler procedure is
invoked, the catch that led to the handler procedure being called is no
longer active.  Therefore, if the handler procedure itself throws an
exception, that exception can only be caught by another active catch
higher up the call stack, if there is one.


 -- C Function: SCM scm_c_catch (SCM tag, scm_t_catch_body body, void
          *body_data, scm_t_catch_handler handler, void *handler_data,
          scm_t_catch_handler pre_unwind_handler, void
          *pre_unwind_handler_data)
 -- C Function: SCM scm_internal_catch (SCM tag, scm_t_catch_body body,
          void *body_data, scm_t_catch_handler handler, void
          *handler_data)
     The above ‘scm_catch_with_pre_unwind_handler’ and ‘scm_catch’ take
     Scheme procedures as body and handler arguments.  ‘scm_c_catch’ and
     ‘scm_internal_catch’ are equivalents taking C functions.

     BODY is called as ‘BODY (BODY_DATA)’ with a catch on exceptions of
     the given TAG type.  If an exception is caught, PRE_UNWIND_HANDLER
     and HANDLER are called as ‘HANDLER (HANDLER_DATA, KEY, ARGS)’.  KEY
     and ARGS are the ‘SCM’ key and argument list from the ‘throw’.

     BODY and HANDLER should have the following prototypes.
     ‘scm_t_catch_body’ and ‘scm_t_catch_handler’ are pointer typedefs
     for these.

          SCM body (void *data);
          SCM handler (void *data, SCM key, SCM args);

     The BODY_DATA and HANDLER_DATA parameters are passed to the
     respective calls so an application can communicate extra
     information to those functions.

     If the data consists of an ‘SCM’ object, care should be taken that
     it isn't garbage collected while still required.  If the ‘SCM’ is a
     local C variable, one way to protect it is to pass a pointer to
     that variable as the data parameter, since the C compiler will then
     know the value must be held on the stack.  Another way is to use
     ‘scm_remember_upto_here_1’ (*note Remembering During Operations::).


File: guile.info,  Node: Throw Handlers,  Next: Lazy Catch,  Prev: Catch,  Up: Exceptions

5.11.7.3 Throw Handlers
.......................

It's sometimes useful to be able to intercept an exception that is being
thrown, but without changing where in the dynamic context that exception
will eventually be caught.  This could be to clean up some related state
or to pass information about the exception to a debugger, for example.
The ‘with-throw-handler’ procedure provides a way to do this.

 -- Scheme Procedure: with-throw-handler key thunk handler
 -- C Function: scm_with_throw_handler (key, thunk, handler)
     Add HANDLER to the dynamic context as a throw handler for key KEY,
     then invoke THUNK.

 -- C Function: SCM scm_c_with_throw_handler (SCM tag, scm_t_catch_body
          body, void *body_data, scm_t_catch_handler handler, void
          *handler_data, int lazy_catch_p)
     The above ‘scm_with_throw_handler’ takes Scheme procedures as body
     (thunk) and handler arguments.  ‘scm_c_with_throw_handler’ is an
     equivalent taking C functions.  See ‘scm_c_catch’ (*note Catch::)
     for a description of the parameters, the behaviour however of
     course follows ‘with-throw-handler’.

   If THUNK throws an exception, Guile handles that exception by
invoking the innermost ‘catch’ or throw handler whose key matches that
of the exception.  When the innermost thing is a throw handler, Guile
calls the specified handler procedure using ‘(apply HANDLER key args)’.
The handler procedure may either return normally or exit non-locally.
If it returns normally, Guile passes the exception on to the next
innermost ‘catch’ or throw handler.  If it exits non-locally, that exit
determines the continuation.

   The behaviour of a throw handler is very similar to that of a ‘catch’
expression's optional pre-unwind handler.  In particular, a throw
handler's handler procedure is invoked in the exact dynamic context of
the ‘throw’ expression, just as a pre-unwind handler is.
‘with-throw-handler’ may be seen as a half-‘catch’: it does everything
that a ‘catch’ would do until the point where ‘catch’ would start
unwinding the stack and dynamic context, but then it rethrows to the
next innermost ‘catch’ or throw handler instead.


File: guile.info,  Node: Lazy Catch,  Next: Throw,  Prev: Throw Handlers,  Up: Exceptions

5.11.7.4 Catch Without Unwinding
................................

Before version 1.8, Guile's closest equivalent to ‘with-throw-handler’
was ‘lazy-catch’.  From version 1.8 onwards we recommend using
‘with-throw-handler’ because its behaviour is more useful than that of
‘lazy-catch’, but ‘lazy-catch’ is still supported as well.

   A “lazy catch” is used in the same way as a normal ‘catch’, with KEY,
THUNK and HANDLER arguments specifying the exception type, normal case
code and handler procedure, but differs in one important respect: the
handler procedure is executed without unwinding the call stack from the
context of the ‘throw’ expression that caused the handler to be invoked.

 -- Scheme Procedure: lazy-catch key thunk handler
 -- C Function: scm_lazy_catch (key, thunk, handler)
     This behaves exactly like ‘catch’, except that it does not unwind
     the stack before invoking HANDLER.  If the HANDLER procedure
     returns normally, Guile rethrows the same exception again to the
     next innermost catch, lazy-catch or throw handler.  If the HANDLER
     exits non-locally, that exit determines the continuation.

 -- C Function: SCM scm_internal_lazy_catch (SCM tag, scm_t_catch_body
          body, void *body_data, scm_t_catch_handler handler, void
          *handler_data)
     The above ‘scm_lazy_catch’ takes Scheme procedures as body and
     handler arguments.  ‘scm_internal_lazy_catch’ is an equivalent
     taking C functions.  See ‘scm_internal_catch’ (*note Catch::) for a
     description of the parameters, the behaviour however of course
     follows ‘lazy-catch’.

   Typically HANDLER is used to display a backtrace of the stack at the
point where the corresponding ‘throw’ occurred, or to save off this
information for possible display later.

   Not unwinding the stack means that throwing an exception that is
caught by a ‘lazy-catch’ is _almost_ equivalent to calling the
‘lazy-catch’'s handler inline instead of each ‘throw’, and then omitting
the surrounding ‘lazy-catch’.  In other words,

     (lazy-catch 'key
       (lambda () ... (throw 'key args ...) ...)
       handler)

is _almost_ equivalent to

     ((lambda () ... (handler 'key args ...) ...))

But why only _almost_?  The difference is that with ‘lazy-catch’ (as
with normal ‘catch’), the dynamic context is unwound back to just
outside the ‘lazy-catch’ expression before invoking the handler.  (For
an introduction to what is meant by dynamic context, *Note Dynamic
Wind::.)

   Then, when the handler _itself_ throws an exception, that exception
must be caught by some kind of ‘catch’ (including perhaps another
‘lazy-catch’) higher up the call stack.

   The dynamic context also includes ‘with-fluids’ blocks (*note Fluids
and Dynamic States::), so the effect of unwinding the dynamic context
can also be seen in fluid variable values.  This is illustrated by the
following code, in which the normal case thunk uses ‘with-fluids’ to
temporarily change the value of a fluid:

     (define f (make-fluid))
     (fluid-set! f "top level value")

     (define (handler . args)
       (cons (fluid-ref f) args))

     (lazy-catch 'foo
                 (lambda ()
                   (with-fluids ((f "local value"))
                     (throw 'foo)))
                 handler)
     ⇒
     ("top level value" foo)

     ((lambda ()
        (with-fluids ((f "local value"))
          (handler 'foo))))
     ⇒
     ("local value" foo)

In the ‘lazy-catch’ version, the unwinding of dynamic context restores
‘f’ to its value outside the ‘with-fluids’ block before the handler is
invoked, so the handler's ‘(fluid-ref f)’ returns the external value.

   ‘lazy-catch’ is useful because it permits the implementation of
debuggers and other reflective programming tools that need to access the
state of the call stack at the exact point where an exception or an
error is thrown.  For an example of this, see REFFIXME:stack-catch.

   It should be obvious from the above that ‘lazy-catch’ is very similar
to ‘with-throw-handler’.  In fact Guile implements ‘lazy-catch’ in
exactly the same way as ‘with-throw-handler’, except with a flag set to
say "where there are slight differences between what
‘with-throw-handler’ and ‘lazy-catch’ would do, do what ‘lazy-catch’ has
always done".  There are two such differences:

  1. ‘with-throw-handler’ handlers execute in the full dynamic context
     of the originating ‘throw’ call.  ‘lazy-catch’ handlers execute in
     the dynamic context of the ‘lazy-catch’ expression, excepting only
     that the stack has not yet been unwound from the point of the
     ‘throw’ call.

  2. If a ‘with-throw-handler’ handler throws to a key that does not
     match the ‘with-throw-handler’ expression's KEY, the new throw may
     be handled by a ‘catch’ or throw handler that is _closer_ to the
     throw than the first ‘with-throw-handler’.  If a ‘lazy-catch’
     handler throws, it will always be handled by a ‘catch’ or throw
     handler that is higher up the dynamic context than the first
     ‘lazy-catch’.

   Here is an example to illustrate the second difference:

     (catch 'a
       (lambda ()
         (with-throw-handler 'b
           (lambda ()
             (catch 'a
               (lambda ()
                 (throw 'b))
               inner-handler))
           (lambda (key . args)
             (throw 'a))))
       outer-handler)

This code will call ‘inner-handler’ and then continue with the
continuation of the inner ‘catch’.  If the ‘with-throw-handler’ was
changed to ‘lazy-catch’, however, the code would call ‘outer-handler’
and then continue with the continuation of the outer ‘catch’.

   Modulo these two differences, any statements in the previous and
following subsections about throw handlers apply to lazy catches as
well.


File: guile.info,  Node: Throw,  Next: Exception Implementation,  Prev: Lazy Catch,  Up: Exceptions

5.11.7.5 Throwing Exceptions
............................

The ‘throw’ primitive is used to throw an exception.  One argument, the
KEY, is mandatory, and must be a symbol; it indicates the type of
exception that is being thrown.  Following the KEY, ‘throw’ accepts any
number of additional arguments, whose meaning depends on the exception
type.  The documentation for each possible type of exception should
specify the additional arguments that are expected for that kind of
exception.

 -- Scheme Procedure: throw key . args
 -- C Function: scm_throw (key, args)
     Invoke the catch form matching KEY, passing ARGS to the HANDLER.

     KEY is a symbol.  It will match catches of the same symbol or of
     ‘#t’.

     If there is no handler at all, Guile prints an error and then
     exits.

   When an exception is thrown, it will be caught by the innermost
‘catch’ or throw handler that applies to the type of the thrown
exception; in other words, whose KEY is either ‘#t’ or the same symbol
as that used in the ‘throw’ expression.  Once Guile has identified the
appropriate ‘catch’ or throw handler, it handles the exception by
applying the relevant handler procedure(s) to the arguments of the
‘throw’.

   If there is no appropriate ‘catch’ or throw handler for a thrown
exception, Guile prints an error to the current error port indicating an
uncaught exception, and then exits.  In practice, it is quite difficult
to observe this behaviour, because Guile when used interactively
installs a top level ‘catch’ handler that will catch all exceptions and
print an appropriate error message _without_ exiting.  For example, this
is what happens if you try to throw an unhandled exception in the
standard Guile REPL; note that Guile's command loop continues after the
error message:

     guile> (throw 'badex)
     <unnamed port>:3:1: In procedure gsubr-apply ...
     <unnamed port>:3:1: unhandled-exception: badex
     ABORT: (misc-error)
     guile>

   The default uncaught exception behaviour can be observed by
evaluating a ‘throw’ expression from the shell command line:

     $ guile -c "(begin (throw 'badex) (display \"here\\n\"))"
     guile: uncaught throw to badex: ()
     $

That Guile exits immediately following the uncaught exception is shown
by the absence of any output from the ‘display’ expression, because
Guile never gets to the point of evaluating that expression.


File: guile.info,  Node: Exception Implementation,  Prev: Throw,  Up: Exceptions

5.11.7.6 How Guile Implements Exceptions
........................................

It is traditional in Scheme to implement exception systems using
‘call-with-current-continuation’.  Continuations (*note Continuations::)
are such a powerful concept that any other control mechanism --
including ‘catch’ and ‘throw’ -- can be implemented in terms of them.

   Guile does not implement ‘catch’ and ‘throw’ like this, though.  Why
not?  Because Guile is specifically designed to be easy to integrate
with applications written in C. In a mixed Scheme/C environment, the
concept of “continuation” must logically include "what happens next" in
the C parts of the application as well as the Scheme parts, and it turns
out that the only reasonable way of implementing continuations like this
is to save and restore the complete C stack.

   So Guile's implementation of ‘call-with-current-continuation’ is a
stack copying one.  This allows it to interact well with ordinary C
code, but means that creating and calling a continuation is slowed down
by the time that it takes to copy the C stack.

   The more targeted mechanism provided by ‘catch’ and ‘throw’ does not
need to save and restore the C stack because the ‘throw’ always jumps to
a location higher up the stack of the code that executes the ‘throw’.
Therefore Guile implements the ‘catch’ and ‘throw’ primitives
independently of ‘call-with-current-continuation’, in a way that takes
advantage of this _upwards only_ nature of exceptions.


File: guile.info,  Node: Error Reporting,  Next: Dynamic Wind,  Prev: Exceptions,  Up: Control Mechanisms

5.11.8 Procedures for Signaling Errors
--------------------------------------

Guile provides a set of convenience procedures for signaling error
conditions that are implemented on top of the exception primitives just
described.

 -- Scheme Procedure: error msg args ...
     Raise an error with key ‘misc-error’ and a message constructed by
     displaying MSG and writing ARGS.

 -- Scheme Procedure: scm-error key subr message args data
 -- C Function: scm_error_scm (key, subr, message, args, data)
     Raise an error with key KEY.  SUBR can be a string naming the
     procedure associated with the error, or ‘#f’.  MESSAGE is the error
     message string, possibly containing ‘~S’ and ‘~A’ escapes.  When an
     error is reported, these are replaced by formatting the
     corresponding members of ARGS: ‘~A’ (was ‘%s’ in older versions of
     Guile) formats using ‘display’ and ‘~S’ (was ‘%S’) formats using
     ‘write’.  DATA is a list or ‘#f’ depending on KEY: if KEY is
     ‘system-error’ then it should be a list containing the Unix ‘errno’
     value; If KEY is ‘signal’ then it should be a list containing the
     Unix signal number; If KEY is ‘out-of-range’ or ‘wrong-type-arg’,
     it is a list containing the bad value; otherwise it will usually be
     ‘#f’.

 -- Scheme Procedure: strerror err
 -- C Function: scm_strerror (err)
     Return the Unix error message corresponding to ERR, an integer
     ‘errno’ value.

     When ‘setlocale’ has been called (*note Locales::), the message is
     in the language and charset of ‘LC_MESSAGES’.  (This is done by the
     C library.)

 -- syntax: false-if-exception expr
     Returns the result of evaluating its argument; however if an
     exception occurs then ‘#f’ is returned instead.


File: guile.info,  Node: Dynamic Wind,  Next: Handling Errors,  Prev: Error Reporting,  Up: Control Mechanisms

5.11.9 Dynamic Wind
-------------------

For Scheme code, the fundamental procedure to react to non-local entry
and exits of dynamic contexts is ‘dynamic-wind’.  C code could use
‘scm_internal_dynamic_wind’, but since C does not allow the convenient
construction of anonymous procedures that close over lexical variables,
this will be, well, inconvenient.

   Therefore, Guile offers the functions ‘scm_dynwind_begin’ and
‘scm_dynwind_end’ to delimit a dynamic extent.  Within this dynamic
extent, which is called a “dynwind context”, you can perform various
“dynwind actions” that control what happens when the dynwind context is
entered or left.  For example, you can register a cleanup routine with
‘scm_dynwind_unwind_handler’ that is executed when the context is left.
There are several other more specialized dynwind actions as well, for
example to temporarily block the execution of asyncs or to temporarily
change the current output port.  They are described elsewhere in this
manual.

   Here is an example that shows how to prevent memory leaks.


     /* Suppose there is a function called FOO in some library that you
        would like to make available to Scheme code (or to C code that
        follows the Scheme conventions).

        FOO takes two C strings and returns a new string.  When an error has
        occurred in FOO, it returns NULL.
     */

     char *foo (char *s1, char *s2);

     /* SCM_FOO interfaces the C function FOO to the Scheme way of life.
        It takes care to free up all temporary strings in the case of
        non-local exits.
      */

     SCM
     scm_foo (SCM s1, SCM s2)
     {
       char *c_s1, *c_s2, *c_res;

       scm_dynwind_begin (0);

       c_s1 = scm_to_locale_string (s1);

       /* Call 'free (c_s1)' when the dynwind context is left.
       */
       scm_dynwind_unwind_handler (free, c_s1, SCM_F_WIND_EXPLICITLY);

       c_s2 = scm_to_locale_string (s2);

       /* Same as above, but more concisely.
       */
       scm_dynwind_free (c_s2);

       c_res = foo (c_s1, c_s2);
       if (c_res == NULL)
         scm_memory_error ("foo");

       scm_dynwind_end ();

       return scm_take_locale_string (res);
     }

 -- Scheme Procedure: dynamic-wind in_guard thunk out_guard
 -- C Function: scm_dynamic_wind (in_guard, thunk, out_guard)
     All three arguments must be 0-argument procedures.  IN_GUARD is
     called, then THUNK, then OUT_GUARD.

     If, any time during the execution of THUNK, the dynamic extent of
     the ‘dynamic-wind’ expression is escaped non-locally, OUT_GUARD is
     called.  If the dynamic extent of the dynamic-wind is re-entered,
     IN_GUARD is called.  Thus IN_GUARD and OUT_GUARD may be called any
     number of times.

          (define x 'normal-binding)
          ⇒ x
          (define a-cont
            (call-with-current-continuation
             (lambda (escape)
               (let ((old-x x))
                 (dynamic-wind
                     ;; in-guard:
                     ;;
                     (lambda () (set! x 'special-binding))

                     ;; thunk
                     ;;
                     (lambda () (display x) (newline)
                                (call-with-current-continuation escape)
                                (display x) (newline)
                                x)

                     ;; out-guard:
                     ;;
                     (lambda () (set! x old-x)))))))
          ;; Prints:
          special-binding
          ;; Evaluates to:
          ⇒ a-cont
          x
          ⇒ normal-binding
          (a-cont #f)
          ;; Prints:
          special-binding
          ;; Evaluates to:
          ⇒ a-cont  ;; the value of the (define a-cont...)
          x
          ⇒ normal-binding
          a-cont
          ⇒ special-binding

 -- C Type: scm_t_dynwind_flags
     This is an enumeration of several flags that modify the behavior of
     ‘scm_dynwind_begin’.  The flags are listed in the following table.

     ‘SCM_F_DYNWIND_REWINDABLE’
          The dynamic context is “rewindable”.  This means that it can
          be reentered non-locally (via the invokation of a
          continuation).  The default is that a dynwind context can not
          be reentered non-locally.

 -- C Function: void scm_dynwind_begin (scm_t_dynwind_flags flags)
     The function ‘scm_dynwind_begin’ starts a new dynamic context and
     makes it the 'current' one.

     The FLAGS argument determines the default behavior of the context.
     Normally, use 0.  This will result in a context that can not be
     reentered with a captured continuation.  When you are prepared to
     handle reentries, include ‘SCM_F_DYNWIND_REWINDABLE’ in FLAGS.

     Being prepared for reentry means that the effects of unwind
     handlers can be undone on reentry.  In the example above, we want
     to prevent a memory leak on non-local exit and thus register an
     unwind handler that frees the memory.  But once the memory is
     freed, we can not get it back on reentry.  Thus reentry can not be
     allowed.

     The consequence is that continuations become less useful when
     non-reenterable contexts are captured, but you don't need to worry
     about that too much.

     The context is ended either implicitly when a non-local exit
     happens, or explicitly with ‘scm_dynwind_end’.  You must make sure
     that a dynwind context is indeed ended properly.  If you fail to
     call ‘scm_dynwind_end’ for each ‘scm_dynwind_begin’, the behavior
     is undefined.

 -- C Function: void scm_dynwind_end ()
     End the current dynamic context explicitly and make the previous
     one current.

 -- C Type: scm_t_wind_flags
     This is an enumeration of several flags that modify the behavior of
     ‘scm_dynwind_unwind_handler’ and ‘scm_dynwind_rewind_handler’.  The
     flags are listed in the following table.

     ‘SCM_F_WIND_EXPLICITLY’
          The registered action is also carried out when the dynwind
          context is entered or left locally.

 -- C Function: void scm_dynwind_unwind_handler (void (*func)(void *),
          void *data, scm_t_wind_flags flags)
 -- C Function: void scm_dynwind_unwind_handler_with_scm (void
          (*func)(SCM), SCM data, scm_t_wind_flags flags)
     Arranges for FUNC to be called with DATA as its arguments when the
     current context ends implicitly.  If FLAGS contains
     ‘SCM_F_WIND_EXPLICITLY’, FUNC is also called when the context ends
     explicitly with ‘scm_dynwind_end’.

     The function ‘scm_dynwind_unwind_handler_with_scm’ takes care that
     DATA is protected from garbage collection.

 -- C Function: void scm_dynwind_rewind_handler (void (*func)(void *),
          void *data, scm_t_wind_flags flags)
 -- C Function: void scm_dynwind_rewind_handler_with_scm (void
          (*func)(SCM), SCM data, scm_t_wind_flags flags)
     Arrange for FUNC to be called with DATA as its argument when the
     current context is restarted by rewinding the stack.  When FLAGS
     contains ‘SCM_F_WIND_EXPLICITLY’, FUNC is called immediately as
     well.

     The function ‘scm_dynwind_rewind_handler_with_scm’ takes care that
     DATA is protected from garbage collection.

 -- C Function: void scm_dynwind_free (void *mem)
     Arrange for MEM to be freed automatically whenever the current
     context is exited, whether normally or non-locally.
     ‘scm_dynwind_free (mem)’ is an equivalent shorthand for
     ‘scm_dynwind_unwind_handler (free, mem, SCM_F_WIND_EXPLICITLY)’.


File: guile.info,  Node: Handling Errors,  Prev: Dynamic Wind,  Up: Control Mechanisms

5.11.10 How to Handle Errors
----------------------------

Error handling is based on ‘catch’ and ‘throw’.  Errors are always
thrown with a KEY and four arguments:

   • KEY: a symbol which indicates the type of error.  The symbols used
     by libguile are listed below.

   • SUBR: the name of the procedure from which the error is thrown, or
     ‘#f’.

   • MESSAGE: a string (possibly language and system dependent)
     describing the error.  The tokens ‘~A’ and ‘~S’ can be embedded
     within the message: they will be replaced with members of the ARGS
     list when the message is printed.  ‘~A’ indicates an argument
     printed using ‘display’, while ‘~S’ indicates an argument printed
     using ‘write’.  MESSAGE can also be ‘#f’, to allow it to be derived
     from the KEY by the error handler (may be useful if the KEY is to
     be thrown from both C and Scheme).

   • ARGS: a list of arguments to be used to expand ‘~A’ and ‘~S’ tokens
     in MESSAGE.  Can also be ‘#f’ if no arguments are required.

   • REST: a list of any additional objects required.  e.g., when the
     key is ‘'system-error’, this contains the C errno value.  Can also
     be ‘#f’ if no additional objects are required.

   In addition to ‘catch’ and ‘throw’, the following Scheme facilities
are available:

 -- Scheme Procedure: display-error stack port subr message args rest
 -- C Function: scm_display_error (stack, port, subr, message, args,
          rest)
     Display an error message to the output port PORT.  STACK is the
     saved stack for the error, SUBR is the name of the procedure in
     which the error occurred and MESSAGE is the actual error message,
     which may contain formatting instructions.  These will format the
     arguments in the list ARGS accordingly.  REST is currently ignored.

   The following are the error keys defined by libguile and the
situations in which they are used:

   • ‘error-signal’: thrown after receiving an unhandled fatal signal
     such as SIGSEGV, SIGBUS, SIGFPE etc.  The REST argument in the
     throw contains the coded signal number (at present this is not the
     same as the usual Unix signal number).

   • ‘system-error’: thrown after the operating system indicates an
     error condition.  The REST argument in the throw contains the errno
     value.

   • ‘numerical-overflow’: numerical overflow.

   • ‘out-of-range’: the arguments to a procedure do not fall within the
     accepted domain.

   • ‘wrong-type-arg’: an argument to a procedure has the wrong type.

   • ‘wrong-number-of-args’: a procedure was called with the wrong
     number of arguments.

   • ‘memory-allocation-error’: memory allocation error.

   • ‘stack-overflow’: stack overflow error.

   • ‘regular-expression-syntax’: errors generated by the regular
     expression library.

   • ‘misc-error’: other errors.

5.11.10.1 C Support
...................

In the following C functions, SUBR and MESSAGE parameters can be ‘NULL’
to give the effect of ‘#f’ described above.

 -- C Function: SCM scm_error (SCM KEY, char *SUBR, char *MESSAGE, SCM
          ARGS, SCM REST)
     Throw an error, as per ‘scm-error’ (*note Error Reporting::).

 -- C Function: void scm_syserror (char *SUBR)
 -- C Function: void scm_syserror_msg (char *SUBR, char *MESSAGE, SCM
          ARGS)
     Throw an error with key ‘system-error’ and supply ‘errno’ in the
     REST argument.  For ‘scm_syserror’ the message is generated using
     ‘strerror’.

     Care should be taken that any code in between the failing operation
     and the call to these routines doesn't change ‘errno’.

 -- C Function: void scm_num_overflow (char *SUBR)
 -- C Function: void scm_out_of_range (char *SUBR, SCM BAD_VALUE)
 -- C Function: void scm_wrong_num_args (SCM PROC)
 -- C Function: void scm_wrong_type_arg (char *SUBR, int ARGNUM, SCM
          BAD_VALUE)
 -- C Function: void scm_memory_error (char *SUBR)
     Throw an error with the various keys described above.

     For ‘scm_wrong_num_args’, PROC should be a Scheme symbol which is
     the name of the procedure incorrectly invoked.


File: guile.info,  Node: Input and Output,  Next: Read/Load/Eval,  Prev: Control Mechanisms,  Up: API Reference

5.12 Input and Output
=====================

* Menu:

* Ports::                       The idea of the port abstraction.
* Reading::                     Procedures for reading from a port.
* Writing::                     Procedures for writing to a port.
* Closing::                     Procedures to close a port.
* Random Access::               Moving around a random access port.
* Line/Delimited::              Read and write lines or delimited text.
* Block Reading and Writing::   Reading and writing blocks of text.
* Default Ports::               Defaults for input, output and errors.
* Port Types::                  Types of port and how to make them.
* I/O Extensions::              Using and extending ports in C.


File: guile.info,  Node: Ports,  Next: Reading,  Up: Input and Output

5.12.1 Ports
------------

Sequential input/output in Scheme is represented by operations on a
“port”.  This chapter explains the operations that Guile provides for
working with ports.

   Ports are created by opening, for instance ‘open-file’ for a file
(*note File Ports::).  Characters can be read from an input port and
written to an output port, or both on an input/output port.  A port can
be closed (*note Closing::) when no longer required, after which any
attempt to read or write is an error.

   The formal definition of a port is very generic: an input port is
simply "an object which can deliver characters on demand," and an output
port is "an object which can accept characters."  Because this
definition is so loose, it is easy to write functions that simulate
ports in software.  “Soft ports” and “string ports” are two interesting
and powerful examples of this technique.  (*note Soft Ports::, and *note
String Ports::.)

   Ports are garbage collected in the usual way (*note Memory
Management::), and will be closed at that time if not already closed.
In this case any errors occuring in the close will not be reported.
Usually a program will want to explicitly close so as to be sure all its
operations have been successful.  Of course if a program has abandoned
something due to an error or other condition then closing problems are
probably not of interest.

   It is strongly recommended that file ports be closed explicitly when
no longer required.  Most systems have limits on how many files can be
open, both on a per-process and a system-wide basis.  A program that
uses many files should take care not to hit those limits.  The same
applies to similar system resources such as pipes and sockets.

   Note that automatic garbage collection is triggered only by memory
consumption, not by file or other resource usage, so a program cannot
rely on that to keep it away from system limits.  An explicit call to
‘gc’ can of course be relied on to pick up unreferenced ports.  If
program flow makes it hard to be certain when to close then this may be
an acceptable way to control resource usage.

   All file access uses the "LFS" large file support functions when
available, so files bigger than 2 Gbytes (2^31 bytes) can be read and
written on a 32-bit system.

 -- Scheme Procedure: input-port? x
 -- C Function: scm_input_port_p (x)
     Return ‘#t’ if X is an input port, otherwise return ‘#f’.  Any
     object satisfying this predicate also satisfies ‘port?’.

 -- Scheme Procedure: output-port? x
 -- C Function: scm_output_port_p (x)
     Return ‘#t’ if X is an output port, otherwise return ‘#f’.  Any
     object satisfying this predicate also satisfies ‘port?’.

 -- Scheme Procedure: port? x
 -- C Function: scm_port_p (x)
     Return a boolean indicating whether X is a port.  Equivalent to
     ‘(or (input-port? X) (output-port? X))’.


File: guile.info,  Node: Reading,  Next: Writing,  Prev: Ports,  Up: Input and Output

5.12.2 Reading
--------------

[Generic procedures for reading from ports.]

 -- Scheme Procedure: eof-object? x
 -- C Function: scm_eof_object_p (x)
     Return ‘#t’ if X is an end-of-file object; otherwise return ‘#f’.

 -- Scheme Procedure: char-ready? [port]
 -- C Function: scm_char_ready_p (port)
     Return ‘#t’ if a character is ready on input PORT and return ‘#f’
     otherwise.  If ‘char-ready?’ returns ‘#t’ then the next ‘read-char’
     operation on PORT is guaranteed not to hang.  If PORT is a file
     port at end of file then ‘char-ready?’ returns ‘#t’.

     ‘char-ready?’ exists to make it possible for a program to accept
     characters from interactive ports without getting stuck waiting for
     input.  Any input editors associated with such ports must make sure
     that characters whose existence has been asserted by ‘char-ready?’
     cannot be rubbed out.  If ‘char-ready?’ were to return ‘#f’ at end
     of file, a port at end of file would be indistinguishable from an
     interactive port that has no ready characters.

 -- Scheme Procedure: read-char [port]
 -- C Function: scm_read_char (port)
     Return the next character available from PORT, updating PORT to
     point to the following character.  If no more characters are
     available, the end-of-file object is returned.

 -- C Function: size_t scm_c_read (SCM port, void *buffer, size_t size)
     Read up to SIZE bytes from PORT and store them in BUFFER.  The
     return value is the number of bytes actually read, which can be
     less than SIZE if end-of-file has been reached.

     Note that this function does not update ‘port-line’ and
     ‘port-column’ below.

 -- Scheme Procedure: peek-char [port]
 -- C Function: scm_peek_char (port)
     Return the next character available from PORT, _without_ updating
     PORT to point to the following character.  If no more characters
     are available, the end-of-file object is returned.

     The value returned by a call to ‘peek-char’ is the same as the
     value that would have been returned by a call to ‘read-char’ on the
     same port.  The only difference is that the very next call to
     ‘read-char’ or ‘peek-char’ on that PORT will return the value
     returned by the preceding call to ‘peek-char’.  In particular, a
     call to ‘peek-char’ on an interactive port will hang waiting for
     input whenever a call to ‘read-char’ would have hung.

 -- Scheme Procedure: unread-char cobj [port]
 -- C Function: scm_unread_char (cobj, port)
     Place CHAR in PORT so that it will be read by the next read
     operation.  If called multiple times, the unread characters will be
     read again in last-in first-out order.  If PORT is not supplied,
     the current input port is used.

 -- Scheme Procedure: unread-string str port
 -- C Function: scm_unread_string (str, port)
     Place the string STR in PORT so that its characters will be read
     from left-to-right as the next characters from PORT during
     subsequent read operations.  If called multiple times, the unread
     characters will be read again in last-in first-out order.  If PORT
     is not supplied, the ‘current-input-port’ is used.

 -- Scheme Procedure: drain-input port
 -- C Function: scm_drain_input (port)
     This procedure clears a port's input buffers, similar to the way
     that force-output clears the output buffer.  The contents of the
     buffers are returned as a single string, e.g.,

          (define p (open-input-file ...))
          (drain-input p) => empty string, nothing buffered yet.
          (unread-char (read-char p) p)
          (drain-input p) => initial chars from p, up to the buffer size.

     Draining the buffers may be useful for cleanly finishing buffered
     I/O so that the file descriptor can be used directly for further
     input.

 -- Scheme Procedure: port-column port
 -- Scheme Procedure: port-line port
 -- C Function: scm_port_column (port)
 -- C Function: scm_port_line (port)
     Return the current column number or line number of PORT.  If the
     number is unknown, the result is #f.  Otherwise, the result is a
     0-origin integer - i.e. the first character of the first line is
     line 0, column 0.  (However, when you display a file position, for
     example in an error message, we recommend you add 1 to get 1-origin
     integers.  This is because lines and column numbers traditionally
     start with 1, and that is what non-programmers will find most
     natural.)

 -- Scheme Procedure: set-port-column! port column
 -- Scheme Procedure: set-port-line! port line
 -- C Function: scm_set_port_column_x (port, column)
 -- C Function: scm_set_port_line_x (port, line)
     Set the current column or line number of PORT.


File: guile.info,  Node: Writing,  Next: Closing,  Prev: Reading,  Up: Input and Output

5.12.3 Writing
--------------

[Generic procedures for writing to ports.]

 -- Scheme Procedure: get-print-state port
 -- C Function: scm_get_print_state (port)
     Return the print state of the port PORT.  If PORT has no associated
     print state, ‘#f’ is returned.

 -- Scheme Procedure: write obj [port]
     Send a representation of OBJ to PORT or to the current output port
     if not given.

     The output is designed to be machine readable, and can be read back
     with ‘read’ (*note Reading::).  Strings are printed in
     doublequotes, with escapes if necessary, and characters are printed
     in ‘#\’ notation.

 -- Scheme Procedure: display obj [port]
     Send a representation of OBJ to PORT or to the current output port
     if not given.

     The output is designed for human readability, it differs from
     ‘write’ in that strings are printed without doublequotes and
     escapes, and characters are printed as per ‘write-char’, not in
     ‘#\’ form.

 -- Scheme Procedure: newline [port]
 -- C Function: scm_newline (port)
     Send a newline to PORT.  If PORT is omitted, send to the current
     output port.

 -- Scheme Procedure: port-with-print-state port [pstate]
 -- C Function: scm_port_with_print_state (port, pstate)
     Create a new port which behaves like PORT, but with an included
     print state PSTATE.  PSTATE is optional.  If PSTATE isn't supplied
     and PORT already has a print state, the old print state is reused.

 -- Scheme Procedure: print-options-interface [setting]
 -- C Function: scm_print_options (setting)
     Option interface for the print options.  Instead of using this
     procedure directly, use the procedures ‘print-enable’,
     ‘print-disable’, ‘print-set!’ and ‘print-options’.

 -- Scheme Procedure: simple-format destination message . args
 -- C Function: scm_simple_format (destination, message, args)
     Write MESSAGE to DESTINATION, defaulting to the current output
     port.  MESSAGE can contain ‘~A’ (was ‘%s’) and ‘~S’ (was ‘%S’)
     escapes.  When printed, the escapes are replaced with corresponding
     members of ARGS: ‘~A’ formats using ‘display’ and ‘~S’ formats
     using ‘write’.  If DESTINATION is ‘#t’, then use the current output
     port, if DESTINATION is ‘#f’, then return a string containing the
     formatted text.  Does not add a trailing newline.

 -- Scheme Procedure: write-char chr [port]
 -- C Function: scm_write_char (chr, port)
     Send character CHR to PORT.

 -- C Function: void scm_c_write (SCM port, const void *buffer, size_t
          size)
     Write SIZE bytes at BUFFER to PORT.

     Note that this function does not update ‘port-line’ and
     ‘port-column’ (*note Reading::).

 -- Scheme Procedure: force-output [port]
 -- C Function: scm_force_output (port)
     Flush the specified output port, or the current output port if PORT
     is omitted.  The current output buffer contents are passed to the
     underlying port implementation (e.g., in the case of fports, the
     data will be written to the file and the output buffer will be
     cleared.)  It has no effect on an unbuffered port.

     The return value is unspecified.

 -- Scheme Procedure: flush-all-ports
 -- C Function: scm_flush_all_ports ()
     Equivalent to calling ‘force-output’ on all open output ports.  The
     return value is unspecified.


File: guile.info,  Node: Closing,  Next: Random Access,  Prev: Writing,  Up: Input and Output

5.12.4 Closing
--------------

 -- Scheme Procedure: close-port port
 -- C Function: scm_close_port (port)
     Close the specified port object.  Return ‘#t’ if it successfully
     closes a port or ‘#f’ if it was already closed.  An exception may
     be raised if an error occurs, for example when flushing buffered
     output.  See also *note close: Ports and File Descriptors, for a
     procedure which can close file descriptors.

 -- Scheme Procedure: close-input-port port
 -- Scheme Procedure: close-output-port port
 -- C Function: scm_close_input_port (port)
 -- C Function: scm_close_output_port (port)
     Close the specified input or output PORT.  An exception may be
     raised if an error occurs while closing.  If PORT is already
     closed, nothing is done.  The return value is unspecified.

     See also *note close: Ports and File Descriptors, for a procedure
     which can close file descriptors.

 -- Scheme Procedure: port-closed? port
 -- C Function: scm_port_closed_p (port)
     Return ‘#t’ if PORT is closed or ‘#f’ if it is open.


File: guile.info,  Node: Random Access,  Next: Line/Delimited,  Prev: Closing,  Up: Input and Output

5.12.5 Random Access
--------------------

 -- Scheme Procedure: seek fd_port offset whence
 -- C Function: scm_seek (fd_port, offset, whence)
     Sets the current position of FD/PORT to the integer OFFSET, which
     is interpreted according to the value of WHENCE.

     One of the following variables should be supplied for WHENCE:
      -- Variable: SEEK_SET
          Seek from the beginning of the file.
      -- Variable: SEEK_CUR
          Seek from the current position.
      -- Variable: SEEK_END
          Seek from the end of the file.
     If FD/PORT is a file descriptor, the underlying system call is
     ‘lseek’.  PORT may be a string port.

     The value returned is the new position in the file.  This means
     that the current position of a port can be obtained using:
          (seek port 0 SEEK_CUR)

 -- Scheme Procedure: ftell fd_port
 -- C Function: scm_ftell (fd_port)
     Return an integer representing the current position of FD/PORT,
     measured from the beginning.  Equivalent to:

          (seek port 0 SEEK_CUR)

 -- Scheme Procedure: truncate-file file [length]
 -- C Function: scm_truncate_file (file, length)
     Truncate FILE to LENGTH bytes.  FILE can be a filename string, a
     port object, or an integer file descriptor.  The return value is
     unspecified.

     For a port or file descriptor LENGTH can be omitted, in which case
     the file is truncated at the current position (per ‘ftell’ above).

     On most systems a file can be extended by giving a length greater
     than the current size, but this is not mandatory in the POSIX
     standard.


File: guile.info,  Node: Line/Delimited,  Next: Block Reading and Writing,  Prev: Random Access,  Up: Input and Output

5.12.6 Line Oriented and Delimited Text
---------------------------------------

The delimited-I/O module can be accessed with:

     (use-modules (ice-9 rdelim))

   It can be used to read or write lines of text, or read text delimited
by a specified set of characters.  It's similar to the ‘(scsh rdelim)’
module from guile-scsh, but does not use multiple values or character
sets and has an extra procedure ‘write-line’.

 -- Scheme Procedure: read-line [port] [handle-delim]
     Return a line of text from PORT if specified, otherwise from the
     value returned by ‘(current-input-port)’.  Under Unix, a line of
     text is terminated by the first end-of-line character or by
     end-of-file.

     If HANDLE-DELIM is specified, it should be one of the following
     symbols:
     ‘trim’
          Discard the terminating delimiter.  This is the default, but
          it will be impossible to tell whether the read terminated with
          a delimiter or end-of-file.
     ‘concat’
          Append the terminating delimiter (if any) to the returned
          string.
     ‘peek’
          Push the terminating delimiter (if any) back on to the port.
     ‘split’
          Return a pair containing the string read from the port and the
          terminating delimiter or end-of-file object.

 -- Scheme Procedure: read-line! buf [port]
     Read a line of text into the supplied string BUF and return the
     number of characters added to BUF.  If BUF is filled, then ‘#f’ is
     returned.  Read from PORT if specified, otherwise from the value
     returned by ‘(current-input-port)’.

 -- Scheme Procedure: read-delimited delims [port] [handle-delim]
     Read text until one of the characters in the string DELIMS is found
     or end-of-file is reached.  Read from PORT if supplied, otherwise
     from the value returned by ‘(current-input-port)’.  HANDLE-DELIM
     takes the same values as described for ‘read-line’.

 -- Scheme Procedure: read-delimited! delims buf [port] [handle-delim]
          [start] [end]
     Read text into the supplied string BUF and return the number of
     characters added to BUF (subject to HANDLE-DELIM, which takes the
     same values specified for ‘read-line’.  If BUF is filled, ‘#f’ is
     returned for both the number of characters read and the delimiter.
     Also terminates if one of the characters in the string DELIMS is
     found or end-of-file is reached.  Read from PORT if supplied,
     otherwise from the value returned by ‘(current-input-port)’.

 -- Scheme Procedure: write-line obj [port]
 -- C Function: scm_write_line (obj, port)
     Display OBJ and a newline character to PORT.  If PORT is not
     specified, ‘(current-output-port)’ is used.  This function is
     equivalent to:
          (display obj [port])
          (newline [port])

   Some of the abovementioned I/O functions rely on the following C
primitives.  These will mainly be of interest to people hacking Guile
internals.

 -- Scheme Procedure: %read-delimited! delims str gobble [port [start
          [end]]]
 -- C Function: scm_read_delimited_x (delims, str, gobble, port, start,
          end)
     Read characters from PORT into STR until one of the characters in
     the DELIMS string is encountered.  If GOBBLE is true, discard the
     delimiter character; otherwise, leave it in the input stream for
     the next read.  If PORT is not specified, use the value of
     ‘(current-input-port)’.  If START or END are specified, store data
     only into the substring of STR bounded by START and END (which
     default to the beginning and end of the string, respectively).

     Return a pair consisting of the delimiter that terminated the
     string and the number of characters read.  If reading stopped at
     the end of file, the delimiter returned is the EOF-OBJECT; if the
     string was filled without encountering a delimiter, this value is
     ‘#f’.

 -- Scheme Procedure: %read-line [port]
 -- C Function: scm_read_line (port)
     Read a newline-terminated line from PORT, allocating storage as
     necessary.  The newline terminator (if any) is removed from the
     string, and a pair consisting of the line and its delimiter is
     returned.  The delimiter may be either a newline or the EOF-OBJECT;
     if ‘%read-line’ is called at the end of file, it returns the pair
     ‘(#<eof> . #<eof>)’.


File: guile.info,  Node: Block Reading and Writing,  Next: Default Ports,  Prev: Line/Delimited,  Up: Input and Output

5.12.7 Block reading and writing
--------------------------------

The Block-string-I/O module can be accessed with:

     (use-modules (ice-9 rw))

   It currently contains procedures that help to implement the ‘(scsh
rw)’ module in guile-scsh.

 -- Scheme Procedure: read-string!/partial str [port_or_fdes [start
          [end]]]
 -- C Function: scm_read_string_x_partial (str, port_or_fdes, start,
          end)
     Read characters from a port or file descriptor into a string STR.
     A port must have an underlying file descriptor -- a so-called
     fport.  This procedure is scsh-compatible and can efficiently read
     large strings.  It will:

        • attempt to fill the entire string, unless the START and/or END
          arguments are supplied.  i.e., START defaults to 0 and END
          defaults to ‘(string-length str)’
        • use the current input port if PORT_OR_FDES is not supplied.
        • return fewer than the requested number of characters in some
          cases, e.g., on end of file, if interrupted by a signal, or if
          not all the characters are immediately available.
        • wait indefinitely for some input if no characters are
          currently available, unless the port is in non-blocking mode.
        • read characters from the port's input buffers if available,
          instead from the underlying file descriptor.
        • return ‘#f’ if end-of-file is encountered before reading any
          characters, otherwise return the number of characters read.
        • return 0 if the port is in non-blocking mode and no characters
          are immediately available.
        • return 0 if the request is for 0 bytes, with no end-of-file
          check.

 -- Scheme Procedure: write-string/partial str [port_or_fdes [start
          [end]]]
 -- C Function: scm_write_string_partial (str, port_or_fdes, start, end)
     Write characters from a string STR to a port or file descriptor.  A
     port must have an underlying file descriptor -- a so-called fport.
     This procedure is scsh-compatible and can efficiently write large
     strings.  It will:

        • attempt to write the entire string, unless the START and/or
          END arguments are supplied.  i.e., START defaults to 0 and END
          defaults to ‘(string-length str)’
        • use the current output port if PORT_OF_FDES is not supplied.
        • in the case of a buffered port, store the characters in the
          port's output buffer, if all will fit.  If they will not fit
          then any existing buffered characters will be flushed before
          attempting to write the new characters directly to the
          underlying file descriptor.  If the port is in non-blocking
          mode and buffered characters can not be flushed immediately,
          then an ‘EAGAIN’ system-error exception will be raised (Note:
          scsh does not support the use of non-blocking buffered ports.)
        • write fewer than the requested number of characters in some
          cases, e.g., if interrupted by a signal or if not all of the
          output can be accepted immediately.
        • wait indefinitely for at least one character from STR to be
          accepted by the port, unless the port is in non-blocking mode.
        • return the number of characters accepted by the port.
        • return 0 if the port is in non-blocking mode and can not
          accept at least one character from STR immediately
        • return 0 immediately if the request size is 0 bytes.


File: guile.info,  Node: Default Ports,  Next: Port Types,  Prev: Block Reading and Writing,  Up: Input and Output

5.12.8 Default Ports for Input, Output and Errors
-------------------------------------------------

 -- Scheme Procedure: current-input-port
 -- C Function: scm_current_input_port ()
     Return the current input port.  This is the default port used by
     many input procedures.

     Initially this is the “standard input” in Unix and C terminology.
     When the standard input is a tty the port is unbuffered, otherwise
     it's fully buffered.

     Unbuffered input is good if an application runs an interactive
     subprocess, since any type-ahead input won't go into Guile's buffer
     and be unavailable to the subprocess.

     Note that Guile buffering is completely separate from the tty "line
     discipline".  In the usual cooked mode on a tty Guile only sees a
     line of input once the user presses <Return>.

 -- Scheme Procedure: current-output-port
 -- C Function: scm_current_output_port ()
     Return the current output port.  This is the default port used by
     many output procedures.

     Initially this is the “standard output” in Unix and C terminology.
     When the standard output is a tty this port is unbuffered,
     otherwise it's fully buffered.

     Unbuffered output to a tty is good for ensuring progress output or
     a prompt is seen.  But an application which always prints whole
     lines could change to line buffered, or an application with a lot
     of output could go fully buffered and perhaps make explicit
     ‘force-output’ calls (*note Writing::) at selected points.

 -- Scheme Procedure: current-error-port
 -- C Function: scm_current_error_port ()
     Return the port to which errors and warnings should be sent.

     Initially this is the “standard error” in Unix and C terminology.
     When the standard error is a tty this port is unbuffered, otherwise
     it's fully buffered.

 -- Scheme Procedure: set-current-input-port port
 -- Scheme Procedure: set-current-output-port port
 -- Scheme Procedure: set-current-error-port port
 -- C Function: scm_set_current_input_port (port)
 -- C Function: scm_set_current_output_port (port)
 -- C Function: scm_set_current_error_port (port)
     Change the ports returned by ‘current-input-port’,
     ‘current-output-port’ and ‘current-error-port’, respectively, so
     that they use the supplied PORT for input or output.

 -- C Function: void scm_dynwind_current_input_port (SCM port)
 -- C Function: void scm_dynwind_current_output_port (SCM port)
 -- C Function: void scm_dynwind_current_error_port (SCM port)
     These functions must be used inside a pair of calls to
     ‘scm_dynwind_begin’ and ‘scm_dynwind_end’ (*note Dynamic Wind::).
     During the dynwind context, the indicated port is set to PORT.

     More precisely, the current port is swapped with a 'backup' value
     whenever the dynwind context is entered or left.  The backup value
     is initialized with the PORT argument.


File: guile.info,  Node: Port Types,  Next: I/O Extensions,  Prev: Default Ports,  Up: Input and Output

5.12.9 Types of Port
--------------------

[Types of port; how to make them.]

* Menu:

* File Ports:: Ports on an operating system file.
* String Ports:: Ports on a Scheme string.
* Soft Ports:: Ports on arbitrary Scheme procedures.
* Void Ports:: Ports on nothing at all.


File: guile.info,  Node: File Ports,  Next: String Ports,  Up: Port Types

5.12.9.1 File Ports
...................

The following procedures are used to open file ports.  See also *note
open: Ports and File Descriptors, for an interface to the Unix ‘open’
system call.

   Most systems have limits on how many files can be open, so it's
strongly recommended that file ports be closed explicitly when no longer
required (*note Ports::).

 -- Scheme Procedure: open-file filename mode
 -- C Function: scm_open_file (filename, mode)
     Open the file whose name is FILENAME, and return a port
     representing that file.  The attributes of the port are determined
     by the MODE string.  The way in which this is interpreted is
     similar to C stdio.  The first character must be one of the
     following:

     ‘r’
          Open an existing file for input.
     ‘w’
          Open a file for output, creating it if it doesn't already
          exist or removing its contents if it does.
     ‘a’
          Open a file for output, creating it if it doesn't already
          exist.  All writes to the port will go to the end of the file.
          The "append mode" can be turned off while the port is in use
          *note fcntl: Ports and File Descriptors.

     The following additional characters can be appended:

     ‘+’
          Open the port for both input and output.  E.g., ‘r+’: open an
          existing file for both input and output.
     ‘0’
          Create an "unbuffered" port.  In this case input and output
          operations are passed directly to the underlying port
          implementation without additional buffering.  This is likely
          to slow down I/O operations.  The buffering mode can be
          changed while a port is in use *note setvbuf: Ports and File
          Descriptors.
     ‘l’
          Add line-buffering to the port.  The port output buffer will
          be automatically flushed whenever a newline character is
          written.
     ‘b’
          Use binary mode.  On DOS systems the default text mode
          converts CR+LF in the file to newline for the program, whereas
          binary mode reads and writes all bytes unchanged.  On
          Unix-like systems there is no such distinction, text files
          already contain just newlines and no conversion is ever made.
          The ‘b’ flag is accepted on all systems, but has no effect on
          Unix-like systems.

          (For reference, Guile leaves text versus binary up to the C
          library, ‘b’ here just adds ‘O_BINARY’ to the underlying
          ‘open’ call, when that flag is available.)

     If a file cannot be opened with the access requested, ‘open-file’
     throws an exception.

     In theory we could create read/write ports which were buffered in
     one direction only.  However this isn't included in the current
     interfaces.

 -- Scheme Procedure: open-input-file filename
     Open FILENAME for input.  Equivalent to
          (open-file FILENAME "r")

 -- Scheme Procedure: open-output-file filename
     Open FILENAME for output.  Equivalent to
          (open-file FILENAME "w")

 -- Scheme Procedure: call-with-input-file filename proc
 -- Scheme Procedure: call-with-output-file filename proc
     Open FILENAME for input or output, and call ‘(PROC port)’ with the
     resulting port.  Return the value returned by PROC.  FILENAME is
     opened as per ‘open-input-file’ or ‘open-output-file’ respectively,
     and an error is signalled if it cannot be opened.

     When PROC returns, the port is closed.  If PROC does not return
     (eg. if it throws an error), then the port might not be closed
     automatically, though it will be garbage collected in the usual way
     if not otherwise referenced.

 -- Scheme Procedure: with-input-from-file filename thunk
 -- Scheme Procedure: with-output-to-file filename thunk
 -- Scheme Procedure: with-error-to-file filename thunk
     Open FILENAME and call ‘(THUNK)’ with the new port setup as
     respectively the ‘current-input-port’, ‘current-output-port’, or
     ‘current-error-port’.  Return the value returned by THUNK.
     FILENAME is opened as per ‘open-input-file’ or ‘open-output-file’
     respectively, and an error is signalled if it cannot be opened.

     When THUNK returns, the port is closed and the previous setting of
     the respective current port is restored.

     The current port setting is managed with ‘dynamic-wind’, so the
     previous value is restored no matter how THUNK exits (eg. an
     exception), and if THUNK is re-entered (via a captured
     continuation) then it's set again to the FILENAME port.

     The port is closed when THUNK returns normally, but not when exited
     via an exception or new continuation.  This ensures it's still
     ready for use if THUNK is re-entered by a captured continuation.
     Of course the port is always garbage collected and closed in the
     usual way when no longer referenced anywhere.

 -- Scheme Procedure: port-mode port
 -- C Function: scm_port_mode (port)
     Return the port modes associated with the open port PORT.  These
     will not necessarily be identical to the modes used when the port
     was opened, since modes such as "append" which are used only during
     port creation are not retained.

 -- Scheme Procedure: port-filename port
 -- C Function: scm_port_filename (port)
     Return the filename associated with PORT.  This function returns
     the strings "standard input", "standard output" and "standard
     error" when called on the current input, output and error ports
     respectively.

     PORT must be open, ‘port-filename’ cannot be used once the port is
     closed.

 -- Scheme Procedure: set-port-filename! port filename
 -- C Function: scm_set_port_filename_x (port, filename)
     Change the filename associated with PORT, using the current input
     port if none is specified.  Note that this does not change the
     port's source of data, but only the value that is returned by
     ‘port-filename’ and reported in diagnostic output.

 -- Scheme Procedure: file-port? obj
 -- C Function: scm_file_port_p (obj)
     Determine whether OBJ is a port that is related to a file.


File: guile.info,  Node: String Ports,  Next: Soft Ports,  Prev: File Ports,  Up: Port Types

5.12.9.2 String Ports
.....................

The following allow string ports to be opened by analogy to R4R* file
port facilities:

 -- Scheme Procedure: call-with-output-string proc
 -- C Function: scm_call_with_output_string (proc)
     Calls the one-argument procedure PROC with a newly created output
     port.  When the function returns, the string composed of the
     characters written into the port is returned.  PROC should not
     close the port.

 -- Scheme Procedure: call-with-input-string string proc
 -- C Function: scm_call_with_input_string (string, proc)
     Calls the one-argument procedure PROC with a newly created input
     port from which STRING's contents may be read.  The value yielded
     by the PROC is returned.

 -- Scheme Procedure: with-output-to-string thunk
     Calls the zero-argument procedure THUNK with the current output
     port set temporarily to a new string port.  It returns a string
     composed of the characters written to the current output.

 -- Scheme Procedure: with-input-from-string string thunk
     Calls the zero-argument procedure THUNK with the current input port
     set temporarily to a string port opened on the specified STRING.
     The value yielded by THUNK is returned.

 -- Scheme Procedure: open-input-string str
 -- C Function: scm_open_input_string (str)
     Take a string and return an input port that delivers characters
     from the string.  The port can be closed by ‘close-input-port’,
     though its storage will be reclaimed by the garbage collector if it
     becomes inaccessible.

 -- Scheme Procedure: open-output-string
 -- C Function: scm_open_output_string ()
     Return an output port that will accumulate characters for retrieval
     by ‘get-output-string’.  The port can be closed by the procedure
     ‘close-output-port’, though its storage will be reclaimed by the
     garbage collector if it becomes inaccessible.

 -- Scheme Procedure: get-output-string port
 -- C Function: scm_get_output_string (port)
     Given an output port created by ‘open-output-string’, return a
     string consisting of the characters that have been output to the
     port so far.

     ‘get-output-string’ must be used before closing PORT, once closed
     the string cannot be obtained.

   A string port can be used in many procedures which accept a port but
which are not dependent on implementation details of fports.  E.g.,
seeking and truncating will work on a string port, but trying to extract
the file descriptor number will fail.


File: guile.info,  Node: Soft Ports,  Next: Void Ports,  Prev: String Ports,  Up: Port Types

5.12.9.3 Soft Ports
...................

A “soft-port” is a port based on a vector of procedures capable of
accepting or delivering characters.  It allows emulation of I/O ports.

 -- Scheme Procedure: make-soft-port pv modes
 -- C Function: scm_make_soft_port (pv, modes)
     Return a port capable of receiving or delivering characters as
     specified by the MODES string (*note open-file: File Ports.).  PV
     must be a vector of length 5 or 6.  Its components are as follows:

       0. procedure accepting one character for output
       1. procedure accepting a string for output
       2. thunk for flushing output
       3. thunk for getting one character
       4. thunk for closing port (not by garbage collection)
       5. (if present and not ‘#f’) thunk for computing the number of
          characters that can be read from the port without blocking.

     For an output-only port only elements 0, 1, 2, and 4 need be
     procedures.  For an input-only port only elements 3 and 4 need be
     procedures.  Thunks 2 and 4 can instead be ‘#f’ if there is no
     useful operation for them to perform.

     If thunk 3 returns ‘#f’ or an ‘eof-object’ (*note eof-object?:
     (r5rs)Input.) it indicates that the port has reached end-of-file.
     For example:

          (define stdout (current-output-port))
          (define p (make-soft-port
                     (vector
                      (lambda (c) (write c stdout))
                      (lambda (s) (display s stdout))
                      (lambda () (display "." stdout))
                      (lambda () (char-upcase (read-char)))
                      (lambda () (display "@" stdout)))
                     "rw"))

          (write p p) ⇒ #<input-output: soft 8081e20>


File: guile.info,  Node: Void Ports,  Prev: Soft Ports,  Up: Port Types

5.12.9.4 Void Ports
...................

This kind of port causes any data to be discarded when written to, and
always returns the end-of-file object when read from.

 -- Scheme Procedure: %make-void-port mode
 -- C Function: scm_sys_make_void_port (mode)
     Create and return a new void port.  A void port acts like
     ‘/dev/null’.  The MODE argument specifies the input/output modes
     for this port: see the documentation for ‘open-file’ in *note File
     Ports::.


File: guile.info,  Node: I/O Extensions,  Prev: Port Types,  Up: Input and Output

5.12.10 Using and Extending Ports in C
--------------------------------------

* Menu:

* C Port Interface:: Using ports from C.
* Port Implementation:: How to implement a new port type in C.


File: guile.info,  Node: C Port Interface,  Next: Port Implementation,  Up: I/O Extensions

5.12.10.1 C Port Interface
..........................

This section describes how to use Scheme ports from C.

Port basics
...........

There are two main data structures.  A port type object (ptob) is of
type ‘scm_ptob_descriptor’.  A port instance is of type ‘scm_port’.
Given an ‘SCM’ variable which points to a port, the corresponding C port
object can be obtained using the ‘SCM_PTAB_ENTRY’ macro.  The ptob can
be obtained by using ‘SCM_PTOBNUM’ to give an index into the ‘scm_ptobs’
global array.

Port buffers
............

An input port always has a read buffer and an output port always has a
write buffer.  However the size of these buffers is not guaranteed to be
more than one byte (e.g., the ‘shortbuf’ field in ‘scm_port’ which is
used when no other buffer is allocated).  The way in which the buffers
are allocated depends on the implementation of the ptob.  For example in
the case of an fport, buffers may be allocated with malloc when the port
is created, but in the case of an strport the underlying string is used
as the buffer.

The ‘rw_random’ flag
....................

Special treatment is required for ports which can be seeked at random.
Before various operations, such as seeking the port or changing from
input to output on a bidirectional port or vice versa, the port
implementation must be given a chance to update its state.  The write
buffer is updated by calling the ‘flush’ ptob procedure and the input
buffer is updated by calling the ‘end_input’ ptob procedure.  In the
case of an fport, ‘flush’ causes buffered output to be written to the
file descriptor, while ‘end_input’ causes the descriptor position to be
adjusted to account for buffered input which was never read.

   The special treatment must be performed if the ‘rw_random’ flag in
the port is non-zero.

The ‘rw_active’ variable
........................

The ‘rw_active’ variable in the port is only used if ‘rw_random’ is set.
It's defined as an enum with the following values:

‘SCM_PORT_READ’
     the read buffer may have unread data.

‘SCM_PORT_WRITE’
     the write buffer may have unwritten data.

‘SCM_PORT_NEITHER’
     neither the write nor the read buffer has data.

Reading from a port.
....................

To read from a port, it's possible to either call existing libguile
procedures such as ‘scm_getc’ and ‘scm_read_line’ or to read data from
the read buffer directly.  Reading from the buffer involves the
following steps:

  1. Flush output on the port, if ‘rw_active’ is ‘SCM_PORT_WRITE’.

  2. Fill the read buffer, if it's empty, using ‘scm_fill_input’.

  3. Read the data from the buffer and update the read position in the
     buffer.  Steps 2) and 3) may be repeated as many times as required.

  4. Set rw_active to ‘SCM_PORT_READ’ if ‘rw_random’ is set.

  5. update the port's line and column counts.

Writing to a port.
..................

To write data to a port, calling ‘scm_lfwrite’ should be sufficient for
most purposes.  This takes care of the following steps:

  1. End input on the port, if ‘rw_active’ is ‘SCM_PORT_READ’.

  2. Pass the data to the ptob implementation using the ‘write’ ptob
     procedure.  The advantage of using the ptob ‘write’ instead of
     manipulating the write buffer directly is that it allows the data
     to be written in one operation even if the port is using the
     single-byte ‘shortbuf’.

  3. Set ‘rw_active’ to ‘SCM_PORT_WRITE’ if ‘rw_random’ is set.


File: guile.info,  Node: Port Implementation,  Prev: C Port Interface,  Up: I/O Extensions

5.12.10.2 Port Implementation
.............................

This section describes how to implement a new port type in C.

   As described in the previous section, a port type object (ptob) is a
structure of type ‘scm_ptob_descriptor’.  A ptob is created by calling
‘scm_make_port_type’.

 -- Function: scm_t_bits scm_make_port_type (char *name, int
          (*fill_input) (SCM port), void (*write) (SCM port, const void
          *data, size_t size))
     Return a new port type object.  The NAME, FILL_INPUT and WRITE
     parameters are initial values for those port type fields, as
     described below.  The other fields are initialized with default
     values and can be changed later.

   All of the elements of the ptob, apart from ‘name’, are procedures
which collectively implement the port behaviour.  Creating a new port
type mostly involves writing these procedures.

‘name’
     A pointer to a NUL terminated string: the name of the port type.
     This is the only element of ‘scm_ptob_descriptor’ which is not a
     procedure.  Set via the first argument to ‘scm_make_port_type’.

‘mark’
     Called during garbage collection to mark any SCM objects that a
     port object may contain.  It doesn't need to be set unless the port
     has ‘SCM’ components.  Set using

      -- Function: void scm_set_port_mark (scm_t_bits tc, SCM (*mark)
               (SCM port))

‘free’
     Called when the port is collected during gc.  It should free any
     resources used by the port.  Set using

      -- Function: void scm_set_port_free (scm_t_bits tc, size_t (*free)
               (SCM port))

‘print’
     Called when ‘write’ is called on the port object, to print a port
     description.  E.g., for an fport it may produce something like:
     ‘#<input: /etc/passwd 3>’.  Set using

      -- Function: void scm_set_port_print (scm_t_bits tc, int (*print)
               (SCM port, SCM dest_port, scm_print_state *pstate))
          The first argument PORT is the object being printed, the
          second argument DEST_PORT is where its description should go.

‘equalp’
     Not used at present.  Set using

      -- Function: void scm_set_port_equalp (scm_t_bits tc, SCM
               (*equalp) (SCM, SCM))

‘close’
     Called when the port is closed, unless it was collected during gc.
     It should free any resources used by the port.  Set using

      -- Function: void scm_set_port_close (scm_t_bits tc, int (*close)
               (SCM port))

‘write’
     Accept data which is to be written using the port.  The port
     implementation may choose to buffer the data instead of processing
     it directly.  Set via the third argument to ‘scm_make_port_type’.

‘flush’
     Complete the processing of buffered output data.  Reset the value
     of ‘rw_active’ to ‘SCM_PORT_NEITHER’.  Set using

      -- Function: void scm_set_port_flush (scm_t_bits tc, void (*flush)
               (SCM port))

‘end_input’
     Perform any synchronization required when switching from input to
     output on the port.  Reset the value of ‘rw_active’ to
     ‘SCM_PORT_NEITHER’.  Set using

      -- Function: void scm_set_port_end_input (scm_t_bits tc, void
               (*end_input) (SCM port, int offset))

‘fill_input’
     Read new data into the read buffer and return the first character.
     It can be assumed that the read buffer is empty when this procedure
     is called.  Set via the second argument to ‘scm_make_port_type’.

‘input_waiting’
     Return a lower bound on the number of bytes that could be read from
     the port without blocking.  It can be assumed that the current
     state of ‘rw_active’ is ‘SCM_PORT_NEITHER’.  Set using

      -- Function: void scm_set_port_input_waiting (scm_t_bits tc, int
               (*input_waiting) (SCM port))

‘seek’
     Set the current position of the port.  The procedure can not make
     any assumptions about the value of ‘rw_active’ when it's called.
     It can reset the buffers first if desired by using something like:

          if (pt->rw_active == SCM_PORT_READ)
            scm_end_input (port);
          else if (pt->rw_active == SCM_PORT_WRITE)
            ptob->flush (port);

     However note that this will have the side effect of discarding any
     data in the unread-char buffer, in addition to any side effects
     from the ‘end_input’ and ‘flush’ ptob procedures.  This is
     undesirable when seek is called to measure the current position of
     the port, i.e., ‘(seek p 0 SEEK_CUR)’.  The libguile fport and
     string port implementations take care to avoid this problem.

     The procedure is set using

      -- Function: void scm_set_port_seek (scm_t_bits tc, off_t (*seek)
               (SCM port, off_t offset, int whence))

‘truncate’
     Truncate the port data to be specified length.  It can be assumed
     that the current state of ‘rw_active’ is ‘SCM_PORT_NEITHER’.  Set
     using

      -- Function: void scm_set_port_truncate (scm_t_bits tc, void
               (*truncate) (SCM port, off_t length))


File: guile.info,  Node: Read/Load/Eval,  Next: Memory Management,  Prev: Input and Output,  Up: API Reference

5.13 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.


File: guile.info,  Node: Scheme Syntax,  Next: Scheme Read,  Up: Read/Load/Eval

5.13.1 Scheme Syntax: Standard and Guile Extensions
---------------------------------------------------

* Menu:

* Expression Syntax::
* Comments::
* Block Comments::
* Case Sensitivity::
* Keyword Syntax::
* Reader Extensions::


File: guile.info,  Node: Expression Syntax,  Next: Comments,  Up: Scheme Syntax

5.13.1.1 Expression Syntax
..........................

An expression to be evaluated takes one of the following forms.

SYMBOL
     A symbol is evaluated by dereferencing.  A binding of that symbol
     is sought and the value there used.  For example,

          (define x 123)
          x ⇒ 123

(PROC ARGS...)
     A parenthesised expression is a function call.  PROC and each
     argument are evaluated, then the function (which PROC evaluated to)
     is called with those arguments.

     The order in which PROC and the arguments are evaluated is
     unspecified, so be careful when using expressions with side
     effects.

          (max 1 2 3) ⇒ 3

          (define (get-some-proc)  min)
          ((get-some-proc) 1 2 3) ⇒ 1

     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 (*note Macros::, and *note
     Syntax Rules::).

CONSTANT
     Number, string, character and boolean constants evaluate "to
     themselves", so can appear as literals.

          123     ⇒ 123
          99.9    ⇒ 99.9
          "hello" ⇒ "hello"
          #\z     ⇒ #\z
          #t      ⇒ #t

     Note that an application must not attempt to modify literal
     strings, since they may be in read-only memory.

(quote DATA)
'DATA
     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.  '  is simply a shorthand for a ‘quote’ form.  For
     example,

          'x                   ⇒ x
          '(1 2 3)             ⇒ (1 2 3)
          '#(1 (2 3) 4)        ⇒ #(1 (2 3) 4)
          (quote x)            ⇒ x
          (quote (1 2 3))      ⇒ (1 2 3)
          (quote #(1 (2 3) 4)) ⇒ #(1 (2 3) 4)

     Note that an application must not attempt to modify literal lists
     or vectors obtained from a ‘quote’ form, since they may be in
     read-only memory.

(quasiquote DATA)
'DATA
     Backquote quasi-quotation is like ‘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 ‘list’, ‘cons’ or
     ‘vector’ calls, but quasi-quoting is often easier.

     (unquote EXPR)
     ,EXPR
          Within the quasiquote DATA, ‘unquote’ or ‘,’ indicates an
          expression to be evaluated and inserted.  The comma syntax ‘,’
          is simply a shorthand for an ‘unquote’ form.  For example,

               `(1 2 ,(* 9 9) 3 4)      ⇒ (1 2 81 3 4)
               `(1 (unquote (+ 1 1)) 3) ⇒ (1 2 3)
               `#(1 ,(/ 12 2))          ⇒ #(1 6)

     (unquote-splicing EXPR)
     ,@EXPR
          Within the quasiquote DATA, ‘unquote-splicing’ or ‘,@’
          indicates an expression to be evaluated and the elements of
          the returned list inserted.  EXPR must evaluate to a list.
          The "comma-at" syntax ‘,@’ is simply a shorthand for an
          ‘unquote-splicing’ form.

               (define x '(2 3))
               `(1 ,@x 4)                         ⇒ (1 2 3 4)
               `(1 (unquote-splicing (map 1+ x))) ⇒ (1 3 4)
               `#(9 ,@x 9)                        ⇒ #(9 2 3 9)

          Notice ‘,@’ differs from plain ‘,’ in the way one level of
          nesting is stripped.  For ‘,@’ the elements of a returned list
          are inserted, whereas with ‘,’ it would be the list itself
          inserted.


File: guile.info,  Node: Comments,  Next: Block Comments,  Prev: Expression Syntax,  Up: Scheme Syntax

5.13.1.2 Comments
.................

Comments in Scheme source files are written by starting them with a
semicolon character (‘;’).  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.

     ; Comment
     ;; Comment too
     (define x 1)        ; Comment after expression
     (let ((y 1))
       ;; Display something.
       (display y)
     ;;; Comment at left margin.
       (display (+ y 1)))

   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.


File: guile.info,  Node: Block Comments,  Next: Case Sensitivity,  Prev: Comments,  Up: Scheme Syntax

5.13.1.3 Block Comments
.......................

In addition to the standard line comments defined by R5RS, Guile has
another comment type for multiline comments, called “block comments”.
This type of comment begins with the character sequence ‘#!’ and ends
with the characters ‘!#’, which must appear on a line of their own.
These comments are compatible with the block comments in the Scheme
Shell ‘scsh’ (*note The Scheme shell (scsh)::).  The characters ‘#!’
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.

     #! /usr/local/bin/guile -s
     !#

   More details on Guile scripting can be found in the scripting section
(*note Guile Scripting::).


File: guile.info,  Node: Case Sensitivity,  Next: Keyword Syntax,  Prev: Block Comments,  Up: Scheme Syntax

5.13.1.4 Case Sensitivity
.........................

Scheme as defined in R5RS is not case sensitive when reading symbols.
Guile, on the contrary is case sensitive by default, so the identifiers

     guile-whuzzy
     Guile-Whuzzy

   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 ‘case-insensitive’.  More on reader options can be found
at (*note Reader options::).

     (read-enable 'case-insensitive)

   Note that this is seldom a problem, because Scheme programmers tend
not to use uppercase letters in their identifiers anyway.


File: guile.info,  Node: Keyword Syntax,  Next: Reader Extensions,  Prev: Case Sensitivity,  Up: Scheme Syntax

5.13.1.5 Keyword Syntax
.......................


File: guile.info,  Node: Reader Extensions,  Prev: Keyword Syntax,  Up: Scheme Syntax

5.13.1.6 Reader Extensions
..........................

 -- Scheme Procedure: read-hash-extend chr proc
 -- C Function: scm_read_hash_extend (chr, proc)
     Install the procedure PROC for reading expressions starting with
     the character sequence ‘#’ and CHR.  PROC will be called with two
     arguments: the character CHR and the port to read further data
     from.  The object returned will be the return value of ‘read’.


File: guile.info,  Node: Scheme Read,  Next: Fly Evaluation,  Prev: Scheme Syntax,  Up: Read/Load/Eval

5.13.2 Reading Scheme Code
--------------------------

 -- Scheme Procedure: read [port]
 -- C Function: scm_read (port)
     Read an s-expression from the input port PORT, or from the current
     input port if PORT is not specified.  Any whitespace before the
     next token is discarded.

   The behaviour of Guile's Scheme reader can be modified by
manipulating its read options.  For more information about options,
*Note User level options interfaces::.  If you want to know which reader
options are available, *Note Reader options::.

 -- Scheme Procedure: read-options [setting]
     Display the current settings of the read options.  If SETTING is
     omitted, only a short form of the current read options is printed.
     Otherwise, SETTING should be one of the following symbols:
     ‘help’
          Display the complete option settings.
     ‘full’
          Like ‘help’, but also print programmer options.

 -- Scheme Procedure: read-enable option-name
 -- Scheme Procedure: read-disable option-name
 -- Scheme Procedure: read-set! option-name value
     Modify the read options.  ‘read-enable’ should be used with boolean
     options and switches them on, ‘read-disable’ switches them off.
     ‘read-set!’ can be used to set an option to a specific value.

 -- Scheme Procedure: read-options-interface [setting]
 -- C Function: scm_read_options (setting)
     Option interface for the read options.  Instead of using this
     procedure directly, use the procedures ‘read-enable’,
     ‘read-disable’, ‘read-set!’ and ‘read-options’.


File: guile.info,  Node: Fly Evaluation,  Next: Loading,  Prev: Scheme Read,  Up: Read/Load/Eval

5.13.3 Procedures for On the Fly Evaluation
-------------------------------------------

*Note Environments::.

 -- Scheme Procedure: eval exp module_or_state
 -- C Function: scm_eval (exp, module_or_state)
     Evaluate EXP, a list representing a Scheme expression, in the
     top-level environment specified by MODULE.  While EXP is evaluated
     (using ‘primitive-eval’), MODULE is made the current module.  The
     current module is reset to its previous value when EVAL returns.
     XXX - dynamic states.  Example: (eval '(+ 1 2)
     (interaction-environment))

 -- Scheme Procedure: interaction-environment
 -- 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.

 -- Scheme Procedure: eval-string string [module]
 -- C Function: scm_eval_string (string)
 -- C Function: scm_eval_string_in_module (string, module)
     Evaluate 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.

 -- C Function: SCM scm_c_eval_string (const char *string)
     ‘scm_eval_string’, but taking a C string instead of an ‘SCM’.

 -- Scheme Procedure: apply proc arg1 ... argN arglst
 -- C Function: scm_apply_0 (proc, arglst)
 -- C Function: scm_apply_1 (proc, arg1, arglst)
 -- C Function: scm_apply_2 (proc, arg1, arg2, arglst)
 -- C Function: scm_apply_3 (proc, arg1, arg2, arg3, arglst)
 -- C Function: scm_apply (proc, arg, rest)
     Call PROC with arguments ARG1 ... ARGN plus the elements of the
     ARGLST list.

     ‘scm_apply’ takes parameters corresponding to a Scheme level
     ‘(lambda (proc arg . rest) ...)’.  So ARG and all but the last
     element of the REST list make up ARG1...ARGN and the last element
     of REST is the ARGLST list.  Or if REST is the empty list ‘SCM_EOL’
     then there's no ARG1...ARGN and ARG is the ARGLST.

     ARGLST is not modified, but the REST list passed to ‘scm_apply’ is
     modified.

 -- C Function: scm_call_0 (proc)
 -- C Function: scm_call_1 (proc, arg1)
 -- C Function: scm_call_2 (proc, arg1, arg2)
 -- C Function: scm_call_3 (proc, arg1, arg2, arg3)
 -- C Function: scm_call_4 (proc, arg1, arg2, arg3, arg4)
     Call PROC with the given arguments.

 -- Scheme Procedure: apply:nconc2last lst
 -- C Function: scm_nconc2last (lst)
     LST should be a list (ARG1 ... ARGN ARGLST), with ARGLST being a
     list.  This function returns a list comprising ARG1 to ARGN plus
     the elements of ARGLST.  LST is modified to form the return.
     ARGLST is not modified, though the return does share structure with
     it.

     This operation collects up the arguments from a list which is
     ‘apply’ style parameters.

 -- Scheme Procedure: primitive-eval exp
 -- C Function: scm_primitive_eval (exp)
     Evaluate EXP in the top-level environment specified by the current
     module.


File: guile.info,  Node: Loading,  Next: Delayed Evaluation,  Prev: Fly Evaluation,  Up: Read/Load/Eval

5.13.4 Loading Scheme Code from File
------------------------------------

 -- Scheme Procedure: load filename [reader]
     Load FILENAME and evaluate its contents in the top-level
     environment.  The load paths are not searched.

     READER if provided should be either ‘#f’, or a procedure with the
     signature ‘(lambda (port) ...)’ which reads the next expression
     from PORT.  If READER is ‘#f’ or absent, Guile's built-in ‘read’
     procedure is used (*note Scheme Read::).

     The READER argument takes effect by setting the value of the
     ‘current-reader’ fluid (see below) before loading the file, and
     restoring its previous value when loading is complete.  The Scheme
     code inside FILENAME can itself change the current reader procedure
     on the fly by setting ‘current-reader’ fluid.

     If the variable ‘%load-hook’ is defined, it should be bound to a
     procedure that will be called before any code is loaded.  See
     documentation for ‘%load-hook’ later in this section.

 -- Scheme Procedure: load-from-path filename
     Similar to ‘load’, but searches for FILENAME in the load paths.

 -- Scheme Procedure: primitive-load filename
 -- C Function: scm_primitive_load (filename)
     Load the file named FILENAME and evaluate its contents in the
     top-level environment.  The load paths are not searched; FILENAME
     must either be a full pathname or be a pathname relative to the
     current directory.  If the variable ‘%load-hook’ is defined, it
     should be bound to a procedure that will be called before any code
     is loaded.  See the documentation for ‘%load-hook’ later in this
     section.

 -- C Function: SCM scm_c_primitive_load (const char *filename)
     ‘scm_primitive_load’, but taking a C string instead of an ‘SCM’.

 -- Scheme Procedure: primitive-load-path filename
 -- C Function: scm_primitive_load_path (filename)
     Search ‘%load-path’ for the file named FILENAME and load it into
     the top-level environment.  If FILENAME is a relative pathname and
     is not found in the list of search paths, an error is signalled.

 -- Scheme Procedure: %search-load-path filename
 -- C Function: scm_sys_search_load_path (filename)
     Search ‘%load-path’ for the file named FILENAME, which must be
     readable by the current user.  If FILENAME is found in the list of
     paths to search or is an absolute pathname, return its full
     pathname.  Otherwise, return ‘#f’.  Filenames may have any of the
     optional extensions in the ‘%load-extensions’ list;
     ‘%search-load-path’ will try each extension automatically.

 -- Variable: current-reader
     ‘current-reader’ holds the read procedure that is currently being
     used by the above loading procedures to read expressions (from the
     file that they are loading).  ‘current-reader’ is a fluid, so it
     has an independent value in each dynamic root and should be read
     and set using ‘fluid-ref’ and ‘fluid-set!’ (*note Fluids and
     Dynamic States::).

 -- Variable: %load-hook
     A procedure to be called ‘(%load-hook FILENAME)’ whenever a file is
     loaded, or ‘#f’ for no such call.  ‘%load-hook’ is used by all of
     the above loading functions (‘load’, ‘load-path’, ‘primitive-load’
     and ‘primitive-load-path’).

     For example an application can set this to show what's loaded,

          (set! %load-hook (lambda (filename)
                             (format #t "Loading ~a ...\n" filename)))
          (load-from-path "foo.scm")
          ⊣ Loading /usr/local/share/guile/site/foo.scm ...

 -- Scheme Procedure: current-load-port
 -- C Function: scm_current_load_port ()
     Return the current-load-port.  The load port is used internally by
     ‘primitive-load’.

 -- Variable: %load-extensions
     A list of default file extensions for files containing Scheme code.
     ‘%search-load-path’ tries each of these extensions when looking for
     a file to load.  By default, ‘%load-extensions’ is bound to the
     list ‘("" ".scm")’.


File: guile.info,  Node: Delayed Evaluation,  Next: Local Evaluation,  Prev: Loading,  Up: Read/Load/Eval

5.13.5 Delayed Evaluation
-------------------------

Promises are a convenient way to defer a calculation until its result is
actually needed, and to run such a calculation only once.

 -- syntax: delay expr
     Return a promise object which holds the given EXPR expression,
     ready to be evaluated by a later ‘force’.

 -- Scheme Procedure: promise? obj
 -- C Function: scm_promise_p (obj)
     Return true if OBJ is a promise.

 -- Scheme Procedure: force p
 -- C Function: scm_force (p)
     Return the value obtained from evaluating the EXPR in the given
     promise P.  If P has previously been forced then its EXPR is not
     evaluated again, instead the value obtained at that time is simply
     returned.

     During a ‘force’, an EXPR can call ‘force’ again on its own
     promise, resulting in a recursive evaluation of that 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, ‘force’ always returns the first value.


File: guile.info,  Node: Local Evaluation,  Next: Evaluator Behaviour,  Prev: Delayed Evaluation,  Up: Read/Load/Eval

5.13.6 Local Evaluation
-----------------------

[the-environment]

 -- Scheme Procedure: local-eval exp [env]
 -- C Function: scm_local_eval (exp, env)
     Evaluate EXP in its environment.  If ENV is supplied, it is the
     environment in which to evaluate EXP.  Otherwise, EXP must be a
     memoized code object (in which case, its environment is implicit).


File: guile.info,  Node: Evaluator Behaviour,  Prev: Local Evaluation,  Up: Read/Load/Eval

5.13.7 Evaluator Behaviour
--------------------------

The behaviour of Guile's evaluator can be modified by manipulating the
evaluator options.  For more information about options, *Note User level
options interfaces::.  If you want to know which evaluator options are
available, *Note Evaluator options::.

 -- Scheme Procedure: eval-options [setting]
     Display the current settings of the evaluator options.  If SETTING
     is omitted, only a short form of the current evaluator options is
     printed.  Otherwise, SETTING should be one of the following
     symbols:
     ‘help’
          Display the complete option settings.
     ‘full’
          Like ‘help’, but also print programmer options.

 -- Scheme Procedure: eval-enable option-name
 -- Scheme Procedure: eval-disable option-name
 -- Scheme Procedure: eval-set! option-name value
     Modify the evaluator options.  ‘eval-enable’ should be used with
     boolean options and switches them on, ‘eval-disable’ switches them
     off.  ‘eval-set!’ can be used to set an option to a specific value.

 -- Scheme Procedure: eval-options-interface [setting]
 -- C Function: scm_eval_options_interface (setting)
     Option interface for the evaluation options.  Instead of using this
     procedure directly, use the procedures ‘eval-enable’,
     ‘eval-disable’, ‘eval-set!’ and ‘eval-options’.

 -- Scheme Procedure: traps [setting]
     Display the current settings of the evaluator traps options.  If
     SETTING is omitted, only a short form of the current evaluator
     traps options is printed.  Otherwise, SETTING should be one of the
     following symbols:
     ‘help’
          Display the complete option settings.
     ‘full’
          Like ‘help’, but also print programmer options.

 -- Scheme Procedure: trap-enable option-name
 -- Scheme Procedure: trap-disable option-name
 -- Scheme Procedure: trap-set! option-name value
     Modify the evaluator options.  ‘trap-enable’ should be used with
     boolean options and switches them on, ‘trap-disable’ switches them
     off.  ‘trap-set!’ can be used to set an option to a specific value.

     See *note Evaluator trap options:: for more information on the
     available trap handlers.

 -- Scheme Procedure: evaluator-traps-interface [setting]
 -- C Function: scm_evaluator_traps (setting)
     Option interface for the evaluator trap options.


File: guile.info,  Node: Memory Management,  Next: Objects,  Prev: Read/Load/Eval,  Up: API Reference

5.14 Memory Management and Garbage Collection
=============================================

Guile uses a _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 explicitly.

   See *note 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::


File: guile.info,  Node: Garbage Collection Functions,  Next: Memory Blocks,  Up: Memory Management

5.14.1 Function related to Garbage Collection
---------------------------------------------

 -- Scheme Procedure: gc
 -- 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.

 -- C Function: SCM scm_gc_protect_object (SCM OBJ)
     Protects OBJ from being freed by the garbage collector, when it
     otherwise might be.  When you are done with the object, call
     ‘scm_gc_unprotect_object’ on the object.  Calls to
     ‘scm_gc_protect’/‘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.

 -- C Function: SCM scm_gc_unprotect_object (SCM OBJ)

     Unprotects an object from the garbage collector which was protected
     by ‘scm_gc_unprotect_object’.  Returns the SCM object it was
     passed.

 -- C Function: SCM scm_permanent_object (SCM OBJ)

     Similar to ‘scm_gc_protect_object’ in that it causes the collector
     to always mark the object, except that it should not be nested
     (only call ‘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.

 -- C Macro: void scm_remember_upto_here_1 (SCM obj)
 -- 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.

 -- Scheme Procedure: gc-stats
 -- C Function: scm_gc_stats ()
     Return an association list of statistics about Guile's current use
     of storage.

 -- Scheme Procedure: gc-live-object-stats
 -- C Function: scm_gc_live_object_stats ()
     Return an alist of statistics of the current live objects.

 -- Function: void scm_gc_mark (SCM X)
     Mark the object X, and recurse on any objects X refers to.  If 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 _mark_ function.


File: guile.info,  Node: Memory Blocks,  Next: Weak References,  Prev: Garbage Collection Functions,  Up: Memory Management

5.14.2 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 ‘scm_gc_malloc’ and
‘scm_gc_free’.  The function ‘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 ‘scm_gc_malloc’ must be freed with
‘scm_gc_free’.

   For memory that is not associated with a Scheme object, you can use
‘scm_malloc’ instead of ‘malloc’.  Like ‘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 ‘free’.

   There is also ‘scm_gc_realloc’ and ‘scm_realloc’, to be used in place
of ‘realloc’ when appropriate, and ‘scm_gc_calloc’ and ‘scm_calloc’, to
be used in place of ‘calloc’ when appropriate.

   The function ‘scm_dynwind_free’ can be useful when memory should be
freed when a dynwind context, *Note Dynamic Wind::.

   For really specialized needs, take at look at
‘scm_gc_register_collectable_memory’ and
‘scm_gc_unregister_collectable_memory’.

 -- C Function: void * scm_malloc (size_t SIZE)
 -- C Function: void * scm_calloc (size_t SIZE)
     Allocate SIZE bytes of memory and return a pointer to it.  When
     SIZE is 0, return ‘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 ‘malloc’ function and can be
     freed with ‘free’.  There is no ‘scm_free’ function to go with
     ‘scm_malloc’ to make it easier to pass memory back and forth
     between different modules.

     The function ‘scm_calloc’ is similar to ‘scm_malloc’, but
     initializes the block of memory to zero as well.

 -- C Function: void * scm_realloc (void *MEM, size_t NEW_SIZE)
     Change the size of the memory block at MEM to NEW_SIZE and return
     its new location.  When NEW_SIZE is 0, this is the same as calling
     ‘free’ on MEM and ‘NULL’ is returned.  When MEM is ‘NULL’, this
     function behaves like ‘scm_malloc’ and allocates a new block of
     size 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.

 -- C Function: void scm_gc_register_collectable_memory (void *MEM,
          size_t SIZE, const char *WHAT)
     Informs the GC that the memory at MEM of size SIZE can potentially
     be freed during a GC. That is, announce that MEM is part of a GC
     controlled object and when the GC happens to free that object, SIZE
     bytes will be freed along with it.  The GC will *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.

     MEM does not need to come from ‘scm_malloc’.  You can only call
     this function once for every memory block.

     The 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.

 -- C Function: void scm_gc_unregister_collectable_memory (void *MEM,
          size_t SIZE)
     Informs the GC that the memory at MEM of size SIZE is no longer
     associated with a GC controlled object.  You must take care to
     match up every call to ‘scm_gc_register_collectable_memory’ with a
     call to ‘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.

 -- C Function: void * scm_gc_malloc (size_t SIZE, const char *WHAT)
 -- C Function: void * scm_gc_realloc (void *MEM, size_t OLD_SIZE,
          size_t NEW_SIZE, const char *WHAT);
 -- C Function: void * scm_gc_calloc (size_t SIZE, const char *WHAT)
     Like ‘scm_malloc’, ‘scm_realloc’ or ‘scm_calloc’, but also call
     ‘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.

 -- C Function: void scm_gc_free (void *MEM, size_t SIZE, const char
          *WHAT)
     Like ‘free’, but also call ‘scm_gc_unregister_collectable_memory’.

     Note that you need to explicitly pass the 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.

 -- C Function: void scm_frame_free (void *mem)
     Equivalent to ‘scm_frame_unwind_handler (free, MEM,
     SCM_F_WIND_EXPLICITLY)’.  That is, the memory block at MEM will be
     freed when the current frame is left.

 -- Scheme Procedure: malloc-stats
     Return an alist ((WHAT .  N) ...)  describing number of malloced
     objects.  WHAT is the second argument to ‘scm_gc_malloc’, N is the
     number of objects of that type currently allocated.

5.14.2.1 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
‘scm_must_malloc’, ‘scm_must_realloc’ and ‘scm_must_free’.  This section
explains why we want you to stop using them, and how to do this.

   The functions ‘scm_must_malloc’ and ‘scm_must_realloc’ behaved like
‘scm_gc_malloc’ and ‘scm_gc_realloc’ do now, respectively.  They would
inform the GC about the newly allocated memory via the internal
equivalent of ‘scm_gc_register_collectable_memory’.  However,
‘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 ‘scm_must_free’.  Additionally, there was no equivalent to
‘scm_malloc’, and it was tempting to just use ‘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.

   The functions ‘scm_done_malloc’ and ‘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 ‘scm_must_malloc’ you need to decide whether to use
‘scm_malloc’ or ‘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 ‘scm_malloc’ and
‘free’.  When it is part of a smob, use ‘scm_gc_malloc’ and change the
smob free function to use ‘scm_gc_free’ instead of ‘scm_must_free’ or
‘free’ and make it return zero.

   The important thing is to always pair ‘scm_malloc’ with ‘free’; and
to always pair ‘scm_gc_malloc’ with ‘scm_gc_free’.

   The same reasoning applies to ‘scm_must_realloc’ and ‘scm_realloc’
versus ‘scm_gc_realloc’.


File: guile.info,  Node: Weak References,  Next: Guardians,  Prev: Memory Blocks,  Up: Memory Management

5.14.3 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.  (*note 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 hash tables::
* Weak vectors::


File: guile.info,  Node: Weak hash tables,  Next: Weak vectors,  Up: Weak References

5.14.3.1 Weak hash tables
.........................

 -- Scheme Procedure: make-weak-key-hash-table size
 -- Scheme Procedure: make-weak-value-hash-table size
 -- Scheme Procedure: make-doubly-weak-hash-table size
 -- C Function: scm_make_weak_key_hash_table (size)
 -- C Function: scm_make_weak_value_hash_table (size)
 -- C Function: scm_make_doubly_weak_hash_table (size)
     Return a weak hash table with 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.  (*note Hash Tables::)

 -- Scheme Procedure: weak-key-hash-table? obj
 -- Scheme Procedure: weak-value-hash-table? obj
 -- Scheme Procedure: doubly-weak-hash-table? obj
 -- C Function: scm_weak_key_hash_table_p (obj)
 -- C Function: scm_weak_value_hash_table_p (obj)
 -- C Function: scm_doubly_weak_hash_table_p (obj)
     Return ‘#t’ if 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.


File: guile.info,  Node: Weak vectors,  Prev: Weak hash tables,  Up: Weak References

5.14.3.2 Weak vectors
.....................

Weak vectors are mainly useful in Guile's implementation of weak hash
tables.

 -- Scheme Procedure: make-weak-vector size [fill]
 -- C Function: scm_make_weak_vector (size, fill)
     Return a weak vector with SIZE elements.  If the optional argument
     FILL is given, all entries in the vector will be set to FILL.  The
     default value for FILL is the empty list.

 -- Scheme Procedure: weak-vector . l
 -- Scheme Procedure: list->weak-vector l
 -- C Function: scm_weak_vector (l)
     Construct a weak vector from a list: ‘weak-vector’ uses the list of
     its arguments while ‘list->weak-vector’ uses its only argument L (a
     list) to construct a weak vector the same way ‘list->vector’ would.

 -- Scheme Procedure: weak-vector? obj
 -- C Function: scm_weak_vector_p (obj)
     Return ‘#t’ if OBJ is a weak vector.  Note that all weak hashes are
     also weak vectors.


File: guile.info,  Node: Guardians,  Prev: Weak References,  Up: Memory Management

5.14.4 Guardians
----------------

Guardians provide a way to be notified about objects that would
otherwise be collected as garbage.  Guarding them prevents the objects
from being collected and cleanup actions can be performed on them, for
example.

   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.

 -- Scheme Procedure: make-guardian
 -- C Function: scm_make_guardian ()
     Create a new guardian.  A guardian protects a set of objects from
     garbage collection, allowing a program to apply cleanup or other
     actions.

     ‘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 ‘#f’ if no such object
     is available.  Objects which are returned in this way are removed
     from the guardian.

     You can put a single object into a guardian more than once and you
     can put a single object into more than one guardian.  The object
     will then be returned multiple times by the guardian procedures.

     An object is eligible to be returned from a guardian when it is no
     longer referenced from outside any guardian.

     There is no guarantee about the order in which objects are returned
     from a guardian.  If you want to impose an order on finalization
     actions, for example, you can do that by keeping objects alive in
     some global data structure until they are no longer needed for
     finalizing other objects.

     Being an element in a weak vector, a key in a hash table with weak
     keys, or a value in a hash table with weak values does not prevent
     an object from being returned by a guardian.  But as long as an
     object can be returned from a guardian it will not be removed from
     such a weak vector or hash table.  In other words, a weak link does
     not prevent an object from being considered collectable, but being
     inside a guardian prevents a weak link from being broken.

     A key in a weak key hash table can be thought of as having a strong
     reference to its associated value as long as the key is accessible.
     Consequently, when the key is only accessible from within a
     guardian, the reference from the key to the value is also
     considered to be coming from within a guardian.  Thus, if there is
     no other reference to the value, it is eligible to be returned from
     a guardian.


File: guile.info,  Node: Objects,  Next: Modules,  Prev: Memory Management,  Up: API Reference

5.15 Objects
============

 -- Scheme Procedure: entity? obj
 -- C Function: scm_entity_p (obj)
     Return ‘#t’ if OBJ is an entity.

 -- Scheme Procedure: operator? obj
 -- C Function: scm_operator_p (obj)
     Return ‘#t’ if OBJ is an operator.

 -- Scheme Procedure: set-object-procedure! obj proc
 -- C Function: scm_set_object_procedure_x (obj, proc)
     Set the object procedure of OBJ to PROC.  OBJ must be either an
     entity or an operator.

 -- Scheme Procedure: make-class-object metaclass layout
 -- C Function: scm_make_class_object (metaclass, layout)
     Create a new class object of class METACLASS, with the slot layout
     specified by LAYOUT.

 -- Scheme Procedure: make-subclass-object class layout
 -- C Function: scm_make_subclass_object (class, layout)
     Create a subclass object of CLASS, with the slot layout specified
     by LAYOUT.


File: guile.info,  Node: Modules,  Next: Scheduling,  Prev: Objects,  Up: API Reference

5.16 Modules
============

When programs become large, naming conflicts can occur when a function
or global variable defined in one file has the same name as a function
or global variable in another file.  Even just a _similarity_ between
function names can cause hard-to-find bugs, since a programmer might
type the wrong function name.

   The approach used to tackle this problem is called _information
encapsulation_, which consists of packaging functional units into a
given name space that is clearly separated from other name spaces.

   The language features that allow this are usually called _the module
system_ because programs are broken up into modules that are compiled
separately (or loaded separately in an interpreter).

   Older languages, like C, have limited support for name space
manipulation and protection.  In C a variable or function is public by
default, and can be made local to a module with the ‘static’ keyword.
But you cannot reference public variables and functions from another
module with different names.

   More advanced module systems have become a common feature in recently
designed languages: ML, Python, Perl, and Modula 3 all allow the
_renaming_ of objects from a foreign module, so they will not clutter
the global name space.

   In addition, Guile offers variables as first-class objects.  They can
be used for interacting with the module system.

* Menu:

* provide and require::         The SLIB feature mechanism.
* Environments::                R5RS top-level environments.
* The Guile module system::     How Guile does it.
* Dynamic Libraries::           Loading libraries of compiled code at run time.
* Variables::                   First-class variables.


File: guile.info,  Node: provide and require,  Next: Environments,  Up: Modules

5.16.1 provide and require
--------------------------

Aubrey Jaffer, mostly to support his portable Scheme library SLIB,
implemented a provide/require mechanism for many Scheme implementations.
Library files in SLIB _provide_ a feature, and when user programs
_require_ that feature, the library file is loaded in.

   For example, the file ‘random.scm’ in the SLIB package contains the
line

     (provide 'random)

   so to use its procedures, a user would type

     (require 'random)

   and they would magically become available, _but still have the same
names!_  So this method is nice, but not as good as a full-featured
module system.

   When SLIB is used with Guile, provide and require can be used to
access its facilities.


File: guile.info,  Node: Environments,  Next: The Guile module system,  Prev: provide and require,  Up: Modules

5.16.2 Environments
-------------------

Scheme, as defined in R5RS, does _not_ have a full module system.
However it does define the concept of a top-level “environment”.  Such
an environment maps identifiers (symbols) to Scheme objects such as
procedures and lists: *note About Closure::.  In other words, it
implements a set of “bindings”.

   Environments in R5RS can be passed as the second argument to ‘eval’
(*note Fly Evaluation::).  Three procedures are defined to return
environments: ‘scheme-report-environment’, ‘null-environment’ and
‘interaction-environment’ (*note Fly Evaluation::).

   In addition, in Guile any module can be used as an R5RS environment,
i.e., passed as the second argument to ‘eval’.

   Note: the following two procedures are available only when the
‘(ice-9 r5rs)’ module is loaded:

     (use-modules (ice-9 r5rs))

 -- Scheme Procedure: scheme-report-environment version
 -- Scheme Procedure: null-environment version
     VERSION must be the exact integer '5', corresponding to revision 5
     of the Scheme report (the Revised^5 Report on Scheme).
     ‘scheme-report-environment’ returns a specifier for an environment
     that is empty except for all bindings defined in the report that
     are either required or both optional and supported by the
     implementation.  ‘null-environment’ returns a specifier for an
     environment that is empty except for the (syntactic) bindings for
     all syntactic keywords defined in the report that are either
     required or both optional and supported by the implementation.

     Currently Guile does not support values of VERSION for other
     revisions of the report.

     The effect of assigning (through the use of ‘eval’) a variable
     bound in a ‘scheme-report-environment’ (for example ‘car’) is
     unspecified.  Currently the environments specified by
     ‘scheme-report-environment’ are not immutable in Guile.


File: guile.info,  Node: The Guile module system,  Next: Dynamic Libraries,  Prev: Environments,  Up: Modules

5.16.3 The Guile module system
------------------------------

The Guile module system extends the concept of environments, discussed
in the previous section, with mechanisms to define, use and customise
sets of bindings.

   In 1996 Tom Lord implemented a full-featured module system for Guile
which allows loading Scheme source files into a private name space.
This system has been available since at least Guile version 1.1.

   For Guile version 1.5.0 and later, the system has been improved to
have better integration from C code, more fine-grained user control over
interfaces, and documentation.

   Although it is anticipated that the module system implementation will
change in the future, the Scheme programming interface described in this
manual should be considered stable.  The C programming interface is
considered relatively stable, although at the time of this writing,
there is still some flux.

* Menu:

* General Information about Modules::  Guile module basics.
* Using Guile Modules::         How to use existing modules.
* Creating Guile Modules::      How to package your code into modules.
* Module System Reflection::    Accessing module objects at run-time.
* Module System Quirks::        Strange things to be aware of.
* Included Guile Modules::      Which modules come with Guile?
* Accessing Modules from C::    How to work with modules with C code.


File: guile.info,  Node: General Information about Modules,  Next: Using Guile Modules,  Up: The Guile module system

5.16.3.1 General Information about Modules
..........................................

A Guile module can be thought of as a collection of named procedures,
variables and macros.  More precisely, it is a set of “bindings” of
symbols (names) to Scheme objects.

   An environment is a mapping from identifiers (or symbols) to
locations, i.e., a set of bindings.  There are top-level environments
and lexical environments.  The environment in which a lambda is executed
is remembered as part of its definition.

   Within a module, all bindings are visible.  Certain bindings can be
declared “public”, in which case they are added to the module's
so-called “export list”; this set of public bindings is called the
module's “public interface” (*note Creating Guile Modules::).

   A client module “uses” a providing module's bindings by either
accessing the providing module's public interface, or by building a
custom interface (and then accessing that).  In a custom interface, the
client module can “select” which bindings to access and can also
algorithmically “rename” bindings.  In contrast, when using the
providing module's public interface, the entire export list is available
without renaming (*note Using Guile Modules::).

   To use a module, it must be found and loaded.  All Guile modules have
a unique “module name”, which is a list of one or more symbols.
Examples are ‘(ice-9 popen)’ or ‘(srfi srfi-11)’.  When Guile searches
for the code of a module, it constructs the name of the file to load by
concatenating the name elements with slashes between the elements and
appending a number of file name extensions from the list
‘%load-extensions’ (*note Loading::).  The resulting file name is then
searched in all directories in the variable ‘%load-path’ (*note Build
Config::).  For example, the ‘(ice-9 popen)’ module would result in the
filename ‘ice-9/popen.scm’ and searched in the installation directories
of Guile and in all other directories in the load path.

   Every module has a so-called syntax transformer associated with it.
This is a procedure which performs all syntax transformation for the
time the module is read in and evaluated.  When working with modules,
you can manipulate the current syntax transformer using the ‘use-syntax’
syntactic form or the ‘#:use-syntax’ module definition option (*note
Creating Guile Modules::).

   Please note that there are some problems with the current module
system you should keep in mind (*note Module System Quirks::).  We hope
to address these eventually.


File: guile.info,  Node: Using Guile Modules,  Next: Creating Guile Modules,  Prev: General Information about Modules,  Up: The Guile module system

5.16.3.2 Using Guile Modules
............................

To use a Guile module is to access either its public interface or a
custom interface (*note General Information about Modules::).  Both
types of access are handled by the syntactic form ‘use-modules’, which
accepts one or more interface specifications and, upon evaluation,
arranges for those interfaces to be available to the current module.
This process may include locating and loading code for a given module if
that code has not yet been loaded, following ‘%load-path’ (*note Build
Config::).

   An “interface specification” has one of two forms.  The first
variation is simply to name the module, in which case its public
interface is the one accessed.  For example:

     (use-modules (ice-9 popen))

   Here, the interface specification is ‘(ice-9 popen)’, and the result
is that the current module now has access to ‘open-pipe’, ‘close-pipe’,
‘open-input-pipe’, and so on (*note Included Guile Modules::).

   Note in the previous example that if the current module had already
defined ‘open-pipe’, that definition would be overwritten by the
definition in ‘(ice-9 popen)’.  For this reason (and others), there is a
second variation of interface specification that not only names a module
to be accessed, but also selects bindings from it and renames them to
suit the current module's needs.  For example:

     (use-modules ((ice-9 popen)
                   :select ((open-pipe . pipe-open) close-pipe)
                   :renamer (symbol-prefix-proc 'unixy:)))

   Here, the interface specification is more complex than before, and
the result is that a custom interface with only two bindings is created
and subsequently accessed by the current module.  The mapping of old to
new names is as follows:

     (ice-9 popen) sees:             current module sees:
     open-pipe                       unixy:pipe-open
     close-pipe                      unixy:close-pipe

   This example also shows how to use the convenience procedure
‘symbol-prefix-proc’.

   You can also directly refer to bindings in a module by using the ‘@’
syntax.  For example, instead of using the ‘use-modules’ statement from
above and writing ‘unixy:pipe-open’ to refer to the ‘pipe-open’ from the
‘(ice-9 popen)’, you could also write ‘(@ (ice-9 popen) open-pipe)’.
Thus an alternative to the complete ‘use-modules’ statement would be

     (define unixy:pipe-open (@ (ice-9 popen) open-pipe))
     (define unixy:close-pipe (@ (ice-9 popen) close-pipe))

   There is also ‘@@’, which can be used like ‘@’, but does not check
whether the variable that is being accessed is actually exported.  Thus,
‘@@’ can be thought of as the impolite version of ‘@’ and should only be
used as a last resort or for debugging, for example.

   Note that just as with a ‘use-modules’ statement, any module that has
not yet been loaded yet will be loaded when referenced by a ‘@’ or ‘@@’
form.

   You can also use the ‘@’ and ‘@@’ syntaxes as the target of a ‘set!’
when the binding refers to a variable.

 -- Scheme Procedure: symbol-prefix-proc prefix-sym
     Return a procedure that prefixes its arg (a symbol) with
     PREFIX-SYM.

 -- syntax: use-modules spec ...
     Resolve each interface specification SPEC into an interface and
     arrange for these to be accessible by the current module.  The
     return value is unspecified.

     SPEC can be a list of symbols, in which case it names a module
     whose public interface is found and used.

     SPEC can also be of the form:

           (MODULE-NAME [:select SELECTION] [:renamer RENAMER])

     in which case a custom interface is newly created and used.
     MODULE-NAME is a list of symbols, as above; SELECTION is a list of
     selection-specs; and RENAMER is a procedure that takes a symbol and
     returns its new name.  A selection-spec is either a symbol or a
     pair of symbols ‘(ORIG . SEEN)’, where ORIG is the name in the used
     module and SEEN is the name in the using module.  Note that SEEN is
     also passed through RENAMER.

     The ‘:select’ and ‘:renamer’ clauses are optional.  If both are
     omitted, the returned interface has no bindings.  If the ‘:select’
     clause is omitted, RENAMER operates on the used module's public
     interface.

     Signal error if module name is not resolvable.

 -- syntax: use-syntax module-name
     Load the module ‘module-name’ and use its syntax transformer as the
     syntax transformer for the currently defined module, as well as
     installing it as the current syntax transformer.

 -- syntax: @ module-name binding-name
     Refer to the binding named BINDING-NAME in module MODULE-NAME.  The
     binding must have been exported by the module.

 -- syntax: @@ module-name binding-name
     Refer to the binding named BINDING-NAME in module MODULE-NAME.  The
     binding must not have been exported by the module.  This syntax is
     only intended for debugging purposes or as a last resort.


File: guile.info,  Node: Creating Guile Modules,  Next: Module System Reflection,  Prev: Using Guile Modules,  Up: The Guile module system

5.16.3.3 Creating Guile Modules
...............................

When you want to create your own modules, you have to take the following
steps:

   • Create a Scheme source file and add all variables and procedures
     you wish to export, or which are required by the exported
     procedures.

   • Add a ‘define-module’ form at the beginning.

   • Export all bindings which should be in the public interface, either
     by using ‘define-public’ or ‘export’ (both documented below).

 -- syntax: define-module module-name [options ...]
     MODULE-NAME is of the form ‘(hierarchy file)’.  One example of this
     is

          (define-module (ice-9 popen))

     ‘define-module’ makes this module available to Guile programs under
     the given MODULE-NAME.

     The OPTIONS are keyword/value pairs which specify more about the
     defined module.  The recognized options and their meaning is shown
     in the following table.

     ‘#:use-module INTERFACE-SPECIFICATION’
          Equivalent to a ‘(use-modules INTERFACE-SPECIFICATION)’ (*note
          Using Guile Modules::).

     ‘#:use-syntax MODULE’
          Use MODULE when loading the currently defined module, and
          install it as the syntax transformer.

     ‘#:autoload MODULE SYMBOL-LIST’
          Load MODULE when any of SYMBOL-LIST are accessed.  For
          example,

               (define-module (my mod)
                 #:autoload (srfi srfi-1) (partition delete-duplicates))
               ...
               (if something
                   (set! foo (delete-duplicates ...)))

          When a module is autoloaded, all its bindings become
          available.  SYMBOL-LIST is just those that will first trigger
          the load.

          An autoload is a good way to put off loading a big module
          until it's really needed, for instance for faster startup or
          if it will only be needed in certain circumstances.

          ‘@’ can do a similar thing (*note Using Guile Modules::), but
          in that case an ‘@’ form must be written every time a binding
          from the module is used.

     ‘#:export LIST’
          Export all identifiers in LIST which must be a list of
          symbols.  This is equivalent to ‘(export LIST)’ in the module
          body.

     ‘#:re-export LIST’
          Re-export all identifiers in LIST which must be a list of
          symbols.  The symbols in LIST must be imported by the current
          module from other modules.  This is equivalent to ‘re-export’
          below.

     ‘#:export-syntax LIST’
          Export all identifiers in LIST which must be a list of
          symbols.  The identifiers in LIST must refer to macros (*note
          Macros::) defined in the current module.  This is equivalent
          to ‘(export-syntax LIST)’ in the module body.

     ‘#:re-export-syntax LIST’
          Re-export all identifiers in LIST which must be a list of
          symbols.  The symbols in LIST must refer to macros imported by
          the current module from other modules.  This is equivalent to
          ‘(re-export-syntax LIST)’ in the module body.

     ‘#:replace LIST’
          Export all identifiers in LIST (a list of symbols) and mark
          them as “replacing bindings”.  In the module user's name
          space, this will have the effect of replacing any binding with
          the same name that is not also "replacing".  Normally a
          replacement results in an "override" warning message,
          ‘#:replace’ avoids that.

          This is useful for modules that export bindings that have the
          same name as core bindings.  ‘#:replace’, in a sense, lets
          Guile know that the module _purposefully_ replaces a core
          binding.  It is important to note, however, that this binding
          replacement is confined to the name space of the module user.
          In other words, the value of the core binding in question
          remains unchanged for other modules.

          For instance, SRFI-39 exports a binding named
          ‘current-input-port’ (*note SRFI-39::) that is a function
          which is upwardly compatible with the core
          ‘current-input-port’ function.  Therefore, SRFI-39 exports its
          version with ‘#:replace’.

          SRFI-19, on the other hand, exports its own version of
          ‘current-time’ (*note SRFI-19 Time::) which is not compatible
          with the core ‘current-time’ function (*note Time::).
          Therefore, SRFI-19 does not use ‘#:replace’.

          The ‘#:replace’ option can also be used by a module which is
          intentionally producing a new special kind of environment and
          should override any core or other bindings already in scope.
          For example perhaps a logic processing environment where ‘<=’
          is an inference instead of a comparison.

          The ‘#:duplicates’ (see below) provides fine-grain control
          about duplicate binding handling on the module-user side.

     ‘#:duplicates LIST’
          Tell Guile to handle duplicate bindings for the bindings
          imported by the current module according to the policy defined
          by LIST, a list of symbols.  LIST must contain symbols
          representing a duplicate binding handling policy chosen among
          the following:

          ‘check’
               Raises an error when a binding is imported from more than
               one place.
          ‘warn’
               Issue a warning when a binding is imported from more than
               one place and leave the responsibility of actually
               handling the duplication to the next duplicate binding
               handler.
          ‘replace’
               When a new binding is imported that has the same name as
               a previously imported binding, then do the following:

                 1. If the old binding was said to be “replacing” (via
                    the ‘#:replace’ option above) and the new binding is
                    not replacing, the keep the old binding.
                 2. If the old binding was not said to be replacing and
                    the new binding is replacing, then replace the old
                    binding with the new one.
                 3. If neither the old nor the new binding is replacing,
                    then keep the old one.

          ‘warn-override-core’
               Issue a warning when a core binding is being overwritten
               and actually override the core binding with the new one.
          ‘first’
               In case of duplicate bindings, the firstly imported
               binding is always the one which is kept.
          ‘last’
               In case of duplicate bindings, the lastly imported
               binding is always the one which is kept.
          ‘noop’
               In case of duplicate bindings, leave the responsibility
               to the next duplicate handler.

          If LIST contains more than one symbol, then the duplicate
          binding handlers which appear first will be used first when
          resolving a duplicate binding situation.  As mentioned above,
          some resolution policies may explicitly leave the
          responsibility of handling the duplication to the next handler
          in LIST.

          The default duplicate binding resolution policy is given by
          the ‘default-duplicate-binding-handler’ procedure, and is

               (replace warn-override-core warn last)

     ‘#:no-backtrace’
          Tell Guile not to record information for procedure backtraces
          when executing the procedures in this module.

     ‘#:pure’
          Create a “pure” module, that is a module which does not
          contain any of the standard procedure bindings except for the
          syntax forms.  This is useful if you want to create “safe”
          modules, that is modules which do not know anything about
          dangerous procedures.

 -- syntax: export variable ...
     Add all VARIABLEs (which must be symbols) to the list of exported
     bindings of the current module.

 -- syntax: define-public ...
     Equivalent to ‘(begin (define foo ...) (export foo))’.

 -- syntax: re-export variable ...
     Add all VARIABLEs (which must be symbols) to the list of
     re-exported bindings of the current module.  Re-exported bindings
     must be imported by the current module from some other module.


File: guile.info,  Node: Module System Reflection,  Next: Module System Quirks,  Prev: Creating Guile Modules,  Up: The Guile module system

5.16.3.4 Module System Reflection
.................................

The previous sections have described a declarative view of the module
system.  You can also work with it programmatically by accessing and
modifying various parts of the Scheme objects that Guile uses to
implement the module system.

   At any time, there is a “current module”.  This module is the one
where a top-level ‘define’ and similar syntax will add new bindings.
You can find other module objects with ‘resolve-module’, for example.

   These module objects can be used as the second argument to ‘eval’.

 -- Scheme Procedure: current-module
     Return the current module object.

 -- Scheme Procedure: set-current-module module
     Set the current module to MODULE and return the previous current
     module.

 -- Scheme Procedure: save-module-excursion thunk
     Call THUNK within a ‘dynamic-wind’ such that the module that is
     current at invocation time is restored when THUNK's dynamic extent
     is left (*note Dynamic Wind::).

     More precisely, if THUNK escapes non-locally, the current module
     (at the time of escape) is saved, and the original current module
     (at the time THUNK's dynamic extent was last entered) is restored.
     If THUNK's dynamic extent is re-entered, then the current module is
     saved, and the previously saved inner module is set current again.

 -- Scheme Procedure: resolve-module name
     Find the module named NAME and return it.  When it has not already
     been defined, try to auto-load it.  When it can't be found that way
     either, create an empty module.  The name is a list of symbols.

 -- Scheme Procedure: resolve-interface name
     Find the module named NAME as with ‘resolve-module’ and return its
     interface.  The interface of a module is also a module object, but
     it contains only the exported bindings.

 -- Scheme Procedure: module-use! module interface
     Add INTERFACE to the front of the use-list of MODULE.  Both
     arguments should be module objects, and INTERFACE should very
     likely be a module returned by ‘resolve-interface’.


File: guile.info,  Node: Module System Quirks,  Next: Included Guile Modules,  Prev: Module System Reflection,  Up: The Guile module system

5.16.3.5 Module System Quirks
.............................

Although the programming interfaces are relatively stable, the Guile
module system itself is still evolving.  Here are some situations where
usage surpasses design.

   • When using a module which exports a macro definition, the other
     module must export all bindings the macro expansion uses, too,
     because the expanded code would otherwise not be able to see these
     definitions and issue a "variable unbound" error, or worse, would
     use another binding which might be present in the scope of the
     expansion.

   • When two or more used modules export bindings with the same names,
     the last accessed module wins, and the exported binding of that
     last module will silently be used.  This might lead to hard-to-find
     errors because wrong procedures or variables are used.  To avoid
     this kind of “name-clash” situation, use a custom interface
     specification (*note Using Guile Modules::).  (We include this
     entry for the possible benefit of users of Guile versions previous
     to 1.5.0, when custom interfaces were added to the module system.)

   • [Add other quirks here.]


File: guile.info,  Node: Included Guile Modules,  Next: Accessing Modules from C,  Prev: Module System Quirks,  Up: The Guile module system

5.16.3.6 Included Guile Modules
...............................

Some modules are included in the Guile distribution; here are references
to the entries in this manual which describe them in more detail:

*boot-9*
     boot-9 is Guile's initialization module, and it is always loaded
     when Guile starts up.

*(ice-9 debug)*
     Mikael Djurfeldt's source-level debugging support for Guile (*note
     Tracing::).

*(ice-9 expect)*
     Actions based on matching input from a port (*note Expect::).

*(ice-9 format)*
     Formatted output in the style of Common Lisp (*note Formatted
     Output::).

*(ice-9 ftw)*
     File tree walker (*note File Tree Walk::).

*(ice-9 getopt-long)*
     Command line option processing (*note getopt-long::).

*(ice-9 history)*
     Refer to previous interactive expressions (*note Value History::).

*(ice-9 popen)*
     Pipes to and from child processes (*note Pipes::).

*(ice-9 pretty-print)*
     Nicely formatted output of Scheme expressions and objects (*note
     Pretty Printing::).

*(ice-9 q)*
     First-in first-out queues (*note Queues::).

*(ice-9 rdelim)*
     Line- and character-delimited input (*note Line/Delimited::).

*(ice-9 readline)*
     ‘readline’ interactive command line editing (*note Readline
     Support::).

*(ice-9 receive)*
     Multiple-value handling with ‘receive’ (*note Multiple Values::).

*(ice-9 regex)*
     Regular expression matching (*note Regular Expressions::).

*(ice-9 rw)*
     Block string input/output (*note Block Reading and Writing::).

*(ice-9 streams)*
     Sequence of values calculated on-demand (*note Streams::).

*(ice-9 syncase)*
     R5RS ‘syntax-rules’ macro system (*note Syntax Rules::).

*(ice-9 threads)*
     Guile's support for multi threaded execution (*note Scheduling::).

*(ice-9 documentation)*
     Online documentation (REFFIXME).

*(srfi srfi-1)*
     A library providing a lot of useful list and pair processing
     procedures (*note SRFI-1::).

*(srfi srfi-2)*
     Support for ‘and-let*’ (*note SRFI-2::).

*(srfi srfi-4)*
     Support for homogeneous numeric vectors (*note SRFI-4::).

*(srfi srfi-6)*
     Support for some additional string port procedures (*note
     SRFI-6::).

*(srfi srfi-8)*
     Multiple-value handling with ‘receive’ (*note SRFI-8::).

*(srfi srfi-9)*
     Record definition with ‘define-record-type’ (*note SRFI-9::).

*(srfi srfi-10)*
     Read hash extension ‘#,()’ (*note SRFI-10::).

*(srfi srfi-11)*
     Multiple-value handling with ‘let-values’ and ‘let*-values’ (*note
     SRFI-11::).

*(srfi srfi-13)*
     String library (*note SRFI-13::).

*(srfi srfi-14)*
     Character-set library (*note SRFI-14::).

*(srfi srfi-16)*
     ‘case-lambda’ procedures of variable arity (*note SRFI-16::).

*(srfi srfi-17)*
     Getter-with-setter support (*note SRFI-17::).

*(srfi srfi-19)*
     Time/Date library (*note SRFI-19::).

*(srfi srfi-26)*
     Convenient syntax for partial application (*note SRFI-26::)

*(srfi srfi-31)*
     ‘rec’ convenient recursive expressions (*note SRFI-31::)

*(ice-9 slib)*
     This module contains hooks for using Aubrey Jaffer's portable
     Scheme library SLIB from Guile (*note SLIB::).


File: guile.info,  Node: Accessing Modules from C,  Prev: Included Guile Modules,  Up: The Guile module system

5.16.3.7 Accessing Modules from C
.................................

The last sections have described how modules are used in Scheme code,
which is the recommended way of creating and accessing modules.  You can
also work with modules from C, but it is more cumbersome.

   The following procedures are available.

 -- C Procedure: SCM scm_current_module ()
     Return the module that is the _current module_.

 -- C Procedure: SCM scm_set_current_module (SCM MODULE)
     Set the current module to MODULE and return the previous current
     module.

 -- C Procedure: SCM scm_c_call_with_current_module (SCM MODULE, SCM
          (*FUNC)(void *), void *DATA)
     Call FUNC and make MODULE the current module during the call.  The
     argument DATA is passed to FUNC.  The return value of
     ‘scm_c_call_with_current_module’ is the return value of FUNC.

 -- C Procedure: SCM scm_c_lookup (const char *NAME)
     Return the variable bound to the symbol indicated by NAME in the
     current module.  If there is no such binding or the symbol is not
     bound to a variable, signal an error.

 -- C Procedure: SCM scm_lookup (SCM NAME)
     Like ‘scm_c_lookup’, but the symbol is specified directly.

 -- C Procedure: SCM scm_c_module_lookup (SCM MODULE, const char *NAME)
 -- C Procedure: SCM scm_module_lookup (SCM MODULE, SCM NAME)
     Like ‘scm_c_lookup’ and ‘scm_lookup’, but the specified module is
     used instead of the current one.

 -- C Procedure: SCM scm_c_define (const char *NAME, SCM VAL)
     Bind the symbol indicated by NAME to a variable in the current
     module and set that variable to VAL.  When NAME is already bound to
     a variable, use that.  Else create a new variable.

 -- C Procedure: SCM scm_define (SCM NAME, SCM VAL)
     Like ‘scm_c_define’, but the symbol is specified directly.

 -- C Procedure: SCM scm_c_module_define (SCM MODULE, const char *NAME,
          SCM VAL)
 -- C Procedure: SCM scm_module_define (SCM MODULE, SCM NAME, SCM VAL)
     Like ‘scm_c_define’ and ‘scm_define’, but the specified module is
     used instead of the current one.

 -- C Procedure: SCM scm_module_reverse_lookup (SCM MODULE, SCM
          VARIABLE)
     Find the symbol that is bound to VARIABLE in MODULE.  When no such
     binding is found, return #F.

 -- C Procedure: SCM scm_c_define_module (const char *NAME, void
          (*INIT)(void *), void *DATA)
     Define a new module named NAME and make it current while INIT is
     called, passing it DATA.  Return the module.

     The parameter NAME is a string with the symbols that make up the
     module name, separated by spaces.  For example, ‘"foo bar"’ names
     the module ‘(foo bar)’.

     When there already exists a module named NAME, it is used
     unchanged, otherwise, an empty module is created.

 -- C Procedure: SCM scm_c_resolve_module (const char *NAME)
     Find the module name NAME and return it.  When it has not already
     been defined, try to auto-load it.  When it can't be found that way
     either, create an empty module.  The name is interpreted as for
     ‘scm_c_define_module’.

 -- C Procedure: SCM scm_resolve_module (SCM NAME)
     Like ‘scm_c_resolve_module’, but the name is given as a real list
     of symbols.

 -- C Procedure: SCM scm_c_use_module (const char *NAME)
     Add the module named NAME to the uses list of the current module,
     as with ‘(use-modules NAME)’.  The name is interpreted as for
     ‘scm_c_define_module’.

 -- C Procedure: SCM scm_c_export (const char *NAME, ...)
     Add the bindings designated by NAME, ...  to the public interface
     of the current module.  The list of names is terminated by ‘NULL’.


File: guile.info,  Node: Dynamic Libraries,  Next: Variables,  Prev: The Guile module system,  Up: Modules

5.16.4 Dynamic Libraries
------------------------

Most modern Unices have something called “shared libraries”.  This
ordinarily means that they have the capability to share the executable
image of a library between several running programs to save memory and
disk space.  But generally, shared libraries give a lot of additional
flexibility compared to the traditional static libraries.  In fact,
calling them 'dynamic' libraries is as correct as calling them 'shared'.

   Shared libraries really give you a lot of flexibility in addition to
the memory and disk space savings.  When you link a program against a
shared library, that library is not closely incorporated into the final
executable.  Instead, the executable of your program only contains
enough information to find the needed shared libraries when the program
is actually run.  Only then, when the program is starting, is the final
step of the linking process performed.  This means that you need not
recompile all programs when you install a new, only slightly modified
version of a shared library.  The programs will pick up the changes
automatically the next time they are run.

   Now, when all the necessary machinery is there to perform part of the
linking at run-time, why not take the next step and allow the programmer
to explicitly take advantage of it from within his program?  Of course,
many operating systems that support shared libraries do just that, and
chances are that Guile will allow you to access this feature from within
your Scheme programs.  As you might have guessed already, this feature
is called “dynamic linking”.(1)

   As with many aspects of Guile, there is a low-level way to access the
dynamic linking apparatus, and a more high-level interface that
integrates dynamically linked libraries into the module system.

* Menu:

* Low level dynamic linking::
* Compiled Code Modules::
* Dynamic Linking and Compiled Code Modules::
* Compiled Code Installation::

   ---------- Footnotes ----------

   (1) Some people also refer to the final linking stage at program
startup as 'dynamic linking', so if you want to make yourself perfectly
clear, it is probably best to use the more technical term “dlopening”,
as suggested by Gordon Matzigkeit in his libtool documentation.


File: guile.info,  Node: Low level dynamic linking,  Next: Compiled Code Modules,  Up: Dynamic Libraries

5.16.4.1 Low level dynamic linking
..................................

When using the low level procedures to do your dynamic linking, you have
complete control over which library is loaded when and what gets done
with it.

 -- Scheme Procedure: dynamic-link library
 -- C Function: scm_dynamic_link (library)
     Find the shared library denoted by LIBRARY (a string) and link it
     into the running Guile application.  When everything works out,
     return a Scheme object suitable for representing the linked object
     file.  Otherwise an error is thrown.  How object files are searched
     is system dependent.

     Normally, LIBRARY is just the name of some shared library file that
     will be searched for in the places where shared libraries usually
     reside, such as in ‘/usr/lib’ and ‘/usr/local/lib’.

 -- Scheme Procedure: dynamic-object? obj
 -- C Function: scm_dynamic_object_p (obj)
     Return ‘#t’ if OBJ is a dynamic library handle, or ‘#f’ otherwise.

 -- Scheme Procedure: dynamic-unlink dobj
 -- C Function: scm_dynamic_unlink (dobj)
     Unlink the indicated object file from the application.  The
     argument DOBJ must have been obtained by a call to ‘dynamic-link’.
     After ‘dynamic-unlink’ has been called on DOBJ, its content is no
     longer accessible.

 -- Scheme Procedure: dynamic-func name dobj
 -- C Function: scm_dynamic_func (name, dobj)
     Search the dynamic object DOBJ for the C function indicated by the
     string NAME and return some Scheme handle that can later be used
     with ‘dynamic-call’ to actually call the function.

     Regardless whether your C compiler prepends an underscore ‘_’ to
     the global names in a program, you should *not* include this
     underscore in FUNCTION.  Guile knows whether the underscore is
     needed or not and will add it when necessary.

 -- Scheme Procedure: dynamic-call func dobj
 -- C Function: scm_dynamic_call (func, dobj)
     Call the C function indicated by FUNC and DOBJ.  The function is
     passed no arguments and its return value is ignored.  When FUNCTION
     is something returned by ‘dynamic-func’, call that function and
     ignore DOBJ.  When FUNC is a string , look it up in DYNOBJ; this is
     equivalent to
          (dynamic-call (dynamic-func FUNC DOBJ) #f)

     Interrupts are deferred while the C function is executing (with
     ‘SCM_DEFER_INTS’/‘SCM_ALLOW_INTS’).

 -- Scheme Procedure: dynamic-args-call func dobj args
 -- C Function: scm_dynamic_args_call (func, dobj, args)
     Call the C function indicated by FUNC and DOBJ, just like
     ‘dynamic-call’, but pass it some arguments and return its return
     value.  The C function is expected to take two arguments and return
     an ‘int’, just like ‘main’:
          int c_func (int argc, char **argv);

     The parameter ARGS must be a list of strings and is converted into
     an array of ‘char *’.  The array is passed in ARGV and its size in
     ARGC.  The return value is converted to a Scheme number and
     returned from the call to ‘dynamic-args-call’.

   When dynamic linking is disabled or not supported on your system, the
above functions throw errors, but they are still available.

   Here is a small example that works on GNU/Linux:

     (define libc-obj (dynamic-link "libc.so"))
     libc-obj
     ⇒ #<dynamic-object "libc.so">
     (dynamic-args-call 'rand libc-obj '())
     ⇒ 269167349
     (dynamic-unlink libc-obj)
     libc-obj
     ⇒ #<dynamic-object "libc.so" (unlinked)>

   As you can see, after calling ‘dynamic-unlink’ on a dynamically
linked library, it is marked as ‘(unlinked)’ and you are no longer able
to use it with ‘dynamic-call’, etc.  Whether the library is really
removed from you program is system-dependent and will generally not
happen when some other parts of your program still use it.  In the
example above, ‘libc’ is almost certainly not removed from your program
because it is badly needed by almost everything.

   The functions to call a function from a dynamically linked library,
‘dynamic-call’ and ‘dynamic-args-call’, are not very powerful.  They are
mostly intended to be used for calling specially written initialization
functions that will then add new primitives to Guile.  For example, we
do not expect that you will dynamically link ‘libX11’ with
‘dynamic-link’ and then construct a beautiful graphical user interface
just by using ‘dynamic-call’ and ‘dynamic-args-call’.  Instead, the
usual way would be to write a special Guile<->X11 glue library that has
intimate knowledge about both Guile and X11 and does whatever is
necessary to make them inter-operate smoothly.  This glue library could
then be dynamically linked into a vanilla Guile interpreter and
activated by calling its initialization function.  That function would
add all the new types and primitives to the Guile interpreter that it
has to offer.

   From this setup the next logical step is to integrate these glue
libraries into the module system of Guile so that you can load new
primitives into a running system just as you can load new Scheme code.

   There is, however, another possibility to get a more thorough access
to the functions contained in a dynamically linked library.  Anthony
Green has written ‘libffi’, a library that implements a “foreign
function interface” for a number of different platforms.  With it, you
can extend the Spartan functionality of ‘dynamic-call’ and
‘dynamic-args-call’ considerably.  There is glue code available in the
Guile contrib archive to make ‘libffi’ accessible from Guile.


File: guile.info,  Node: Compiled Code Modules,  Next: Dynamic Linking and Compiled Code Modules,  Prev: Low level dynamic linking,  Up: Dynamic Libraries

5.16.4.2 Putting Compiled Code into Modules
...........................................

The new primitives that you add to Guile with ‘scm_c_define_gsubr’
(*note Primitive Procedures::) or with any of the other mechanisms are
placed into the ‘(guile-user)’ module by default.  However, it is also
possible to put new primitives into other modules.

   The mechanism for doing so is not very well thought out and is likely
to change when the module system of Guile itself is revised, but it is
simple and useful enough to document it as it stands.

   What ‘scm_c_define_gsubr’ and the functions used by the snarfer
really do is to add the new primitives to whatever module is the
_current module_ when they are called.  This is analogous to the way
Scheme code is put into modules: the ‘define-module’ expression at the
top of a Scheme source file creates a new module and makes it the
current module while the rest of the file is evaluated.  The ‘define’
expressions in that file then add their new definitions to this current
module.

   Therefore, all we need to do is to make sure that the right module is
current when calling ‘scm_c_define_gsubr’ for our new primitives.


File: guile.info,  Node: Dynamic Linking and Compiled Code Modules,  Next: Compiled Code Installation,  Prev: Compiled Code Modules,  Up: Dynamic Libraries

5.16.4.3 Dynamic Linking and Compiled Code Modules
..................................................

The most interesting application of dynamically linked libraries is
probably to use them for providing _compiled code modules_ to Scheme
programs.  As much fun as programming in Scheme is, every now and then
comes the need to write some low-level C stuff to make Scheme even more
fun.

   Not only can you put these new primitives into their own module (see
the previous section), you can even put them into a shared library that
is only then linked to your running Guile image when it is actually
needed.

   An example will hopefully make everything clear.  Suppose we want to
make the Bessel functions of the C library available to Scheme in the
module ‘(math bessel)’.  First we need to write the appropriate glue
code to convert the arguments and return values of the functions from
Scheme to C and back.  Additionally, we need a function that will add
them to the set of Guile primitives.  Because this is just an example,
we will only implement this for the ‘j0’ function.

     #include <math.h>
     #include <libguile.h>

     SCM
     j0_wrapper (SCM x)
     {
       return scm_double2num (j0 (scm_num2dbl (x, "j0")));
     }

     void
     init_math_bessel ()
     {
       scm_c_define_gsubr ("j0", 1, 0, 0, j0_wrapper);
     }

   We can already try to bring this into action by manually calling the
low level functions for performing dynamic linking.  The C source file
needs to be compiled into a shared library.  Here is how to do it on
GNU/Linux, please refer to the ‘libtool’ documentation for how to create
dynamically linkable libraries portably.

     gcc -shared -o libbessel.so -fPIC bessel.c

   Now fire up Guile:

     (define bessel-lib (dynamic-link "./libbessel.so"))
     (dynamic-call "init_math_bessel" bessel-lib)
     (j0 2)
     ⇒ 0.223890779141236

   The filename ‘./libbessel.so’ should be pointing to the shared
library produced with the ‘gcc’ command above, of course.  The second
line of the Guile interaction will call the ‘init_math_bessel’ function
which in turn will register the C function ‘j0_wrapper’ with the Guile
interpreter under the name ‘j0’.  This function becomes immediately
available and we can call it from Scheme.

   Fun, isn't it?  But we are only half way there.  This is what
‘apropos’ has to say about ‘j0’:

     (apropos "j0")
     ⊣ (guile-user): j0     #<primitive-procedure j0>

   As you can see, ‘j0’ is contained in the root module, where all the
other Guile primitives like ‘display’, etc live.  In general, a
primitive is put into whatever module is the “current module” at the
time ‘scm_c_define_gsubr’ is called.

   A compiled module should have a specially named “module init
function”.  Guile knows about this special name and will call that
function automatically after having linked in the shared library.  For
our example, we replace ‘init_math_bessel’ with the following code in
‘bessel.c’:

     void
     init_math_bessel (void *unused)
     {
       scm_c_define_gsubr ("j0", 1, 0, 0, j0_wrapper);
       scm_c_export ("j0", NULL);
     }

     void
     scm_init_math_bessel_module ()
     {
       scm_c_define_module ("math bessel", init_math_bessel, NULL);
     }

   The general pattern for the name of a module init function is:
‘scm_init_’, followed by the name of the module where the individual
hierarchical components are concatenated with underscores, followed by
‘_module’.

   After ‘libbessel.so’ has been rebuilt, we need to place the shared
library into the right place.

   Once the module has been correctly installed, it should be possible
to use it like this:

     guile> (load-extension "./libbessel.so" "scm_init_math_bessel_module")
     guile> (use-modules (math bessel))
     guile> (j0 2)
     0.223890779141236
     guile> (apropos "j0")
     ⊣ (math bessel): j0      #<primitive-procedure j0>

   That's it!

 -- Scheme Procedure: load-extension lib init
 -- C Function: scm_load_extension (lib, init)
     Load and initialize the extension designated by LIB and INIT. When
     there is no pre-registered function for LIB/INIT, this is
     equivalent to

          (dynamic-call INIT (dynamic-link LIB))

     When there is a pre-registered function, that function is called
     instead.

     Normally, there is no pre-registered function.  This option exists
     only for situations where dynamic linking is unavailable or
     unwanted.  In that case, you would statically link your program
     with the desired library, and register its init function right
     after Guile has been initialized.

     LIB should be a string denoting a shared library without any file
     type suffix such as ".so".  The suffix is provided automatically.
     It should also not contain any directory components.  Libraries
     that implement Guile Extensions should be put into the normal
     locations for shared libraries.  We recommend to use the naming
     convention libguile-bla-blum for a extension related to a module
     '(bla blum)'.

     The normal way for a extension to be used is to write a small
     Scheme file that defines a module, and to load the extension into
     this module.  When the module is auto-loaded, the extension is
     loaded as well.  For example,

          (define-module (bla blum))

          (load-extension "libguile-bla-blum" "bla_init_blum")


File: guile.info,  Node: Compiled Code Installation,  Prev: Dynamic Linking and Compiled Code Modules,  Up: Dynamic Libraries

5.16.4.4 Compiled Code Installation
...................................

The simplest way to write a module using compiled C code is

     (define-module (foo bar))
     (load-extension "foobar-c-code" "foo_bar_init")

   When loaded with ‘(use-modules (foo bar))’, the ‘load-extension’ call
looks for the ‘foobar-c-code.so’ (etc) object file in the standard
system locations, such as ‘/usr/lib’ or ‘/usr/local/lib’.

   If someone installs your module to a non-standard location then the
object file won't be found.  You can address this by inserting the
install location in the ‘foo/bar.scm’ file.  This is convenient for the
user and also guarantees the intended object is read, even if stray
older or newer versions are in the loader's path.

   The usual way to specify an install location is with a ‘prefix’ at
the configure stage, for instance ‘./configure prefix=/opt’ results in
library files as say ‘/opt/lib/foobar-c-code.so’.  When using Autoconf
(*note Introduction: (autoconf)Top.), the library location is in a
‘libdir’ variable.  Its value is intended to be expanded by ‘make’, and
can by substituted into a source file like ‘foo.scm.in’

     (define-module (foo bar))
     (load-extension "XXlibdirXX/foobar-c-code" "foo_bar_init")

with the following in a ‘Makefile’, using ‘sed’ (*note Introduction:
(sed)Top.),

     foo.scm: foo.scm.in
             sed 's|XXlibdirXX|$(libdir)|' <foo.scm.in >foo.scm

   The actual pattern ‘XXlibdirXX’ is arbitrary, it's only something
which doesn't otherwise occur.  If several modules need the value, it
can be easier to create one ‘foo/config.scm’ with a define of the
‘libdir’ location, and use that as required.

     (define-module (foo config))
     (define-public foo-config-libdir "XXlibdirXX"")

   Such a file might have other locations too, for instance a data
directory for auxiliary files, or ‘localedir’ if the module has its own
‘gettext’ message catalogue (*note Internationalization::).

   When installing multiple C code objects, it can be convenient to put
them in a subdirectory of ‘libdir’, thus giving for example
‘/usr/lib/foo/some-obj.so’.  If the objects are only meant to be used
through the module, then a subdirectory keeps them out of sight.

   It will be noted all of the above requires that the Scheme code to be
found in ‘%load-path’ (*note Build Config::).  Presently it's left up to
the system administrator or each user to augment that path when
installing Guile modules in non-default locations.  But having reached
the Scheme code, that code should take care of hitting any of its own
private files etc.

   Presently there's no convention for having a Guile version number in
module C code filenames or directories.  This is primarily because
there's no established principles for two versions of Guile to be
installed under the same prefix (eg.  two both under ‘/usr’).  Assuming
upward compatibility is maintained then this should be unnecessary, and
if compatibility is not maintained then it's highly likely a package
will need to be revisited anyway.

   The present suggestion is that modules should assume when they're
installed under a particular ‘prefix’ that there's a single version of
Guile there, and the ‘guile-config’ at build time has the necessary
information about it.  C code or Scheme code might adapt itself
accordingly (allowing for features not available in an older version for
instance).


File: guile.info,  Node: Variables,  Prev: Dynamic Libraries,  Up: Modules

5.16.5 Variables
----------------

Each module has its own hash table, sometimes known as an “obarray”,
that maps the names defined in that module to their corresponding
variable objects.

   A variable is a box-like object that can hold any Scheme value.  It
is said to be “undefined” if its box holds a special Scheme value that
denotes undefined-ness (which is different from all other Scheme values,
including for example ‘#f’); otherwise the variable is “defined”.

   On its own, a variable object is anonymous.  A variable is said to be
“bound” when it is associated with a name in some way, usually a symbol
in a module obarray.  When this happens, the relationship is mutual: the
variable is bound to the name (in that module), and the name (in that
module) is bound to the variable.

   (That's the theory, anyway.  In practice, defined-ness and bound-ness
sometimes get confused, because Lisp and Scheme implementations have
often conflated -- or deliberately drawn no distinction between -- a
name that is unbound and a name that is bound to a variable whose value
is undefined.  We will try to be clear about the difference and explain
any confusion where it is unavoidable.)

   Variables do not have a read syntax.  Most commonly they are created
and bound implicitly by ‘define’ expressions: a top-level ‘define’
expression of the form

     (define NAME VALUE)

creates a variable with initial value VALUE and binds it to the name
NAME in the current module.  But they can also be created dynamically by
calling one of the constructor procedures ‘make-variable’ and
‘make-undefined-variable’.

   First-class variables are especially useful for interacting with the
current module system (*note The Guile module system::).

 -- Scheme Procedure: make-undefined-variable
 -- C Function: scm_make_undefined_variable ()
     Return a variable that is initially unbound.

 -- Scheme Procedure: make-variable init
 -- C Function: scm_make_variable (init)
     Return a variable initialized to value INIT.

 -- Scheme Procedure: variable-bound? var
 -- C Function: scm_variable_bound_p (var)
     Return ‘#t’ iff VAR is bound to a value.  Throws an error if VAR is
     not a variable object.

 -- Scheme Procedure: variable-ref var
 -- C Function: scm_variable_ref (var)
     Dereference VAR and return its value.  VAR must be a variable
     object; see ‘make-variable’ and ‘make-undefined-variable’.

 -- Scheme Procedure: variable-set! var val
 -- C Function: scm_variable_set_x (var, val)
     Set the value of the variable VAR to VAL.  VAR must be a variable
     object, VAL can be any value.  Return an unspecified value.

 -- Scheme Procedure: variable? obj
 -- C Function: scm_variable_p (obj)
     Return ‘#t’ iff OBJ is a variable object, else return ‘#f’.


File: guile.info,  Node: Scheduling,  Next: Options and Config,  Prev: Modules,  Up: API Reference

5.17 Threads, Mutexes, Asyncs and Dynamic Roots
===============================================

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

* Menu:

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


File: guile.info,  Node: Arbiters,  Next: Asyncs,  Up: Scheduling

5.17.1 Arbiters
---------------

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

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

 -- Scheme Procedure: make-arbiter name
 -- C Function: scm_make_arbiter (name)
     Return an object of type arbiter and name NAME.  Its state is
     initially unlocked.  Arbiters are a way to achieve process
     synchronization.

 -- Scheme Procedure: try-arbiter arb
 -- C Function: scm_try_arbiter (arb)
 -- C Function: scm_try_arbiter (arb)
     If ARB is unlocked, then lock it and return ‘#t’.  If ARB is
     already locked, then do nothing and return ‘#f’.

 -- Scheme Procedure: release-arbiter arb
 -- C Function: scm_release_arbiter (arb)
     If ARB is locked, then unlock it and return ‘#t’.  If ARB is
     already unlocked, then do nothing and return ‘#f’.

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


File: guile.info,  Node: Asyncs,  Next: Continuation Barriers,  Prev: Arbiters,  Up: Scheduling

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


File: guile.info,  Node: System asyncs,  Next: User asyncs,  Up: Asyncs

5.17.2.1 System asyncs
......................

To cause the future asynchronous execution of a procedure in a given
thread, use ‘system-async-mark’.

   Automatic invocation of system asyncs can be temporarily disabled by
calling ‘call-with-blocked-asyncs’.  This function works by temporarily
increasing the _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 ‘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 ‘call-with-blocked-asyncs’ and
‘call-with-unblocked-asyncs’, C code can use ‘scm_dynwind_block_asyncs’
and ‘scm_dynwind_unblock_asyncs’ inside a “dynamic context” (*note
Dynamic Wind::) to block or unblock system asyncs temporarily.

 -- Scheme Procedure: system-async-mark proc [thread]
 -- C Function: scm_system_async_mark (proc)
 -- C Function: scm_system_async_mark_for_thread (proc, thread)
     Mark PROC (a procedure with zero arguments) for future execution in
     THREAD.  When PROC has already been marked for THREAD but has not
     been executed yet, this call has no effect.  When THREAD is
     omitted, the thread that called ‘system-async-mark’ is used.

     This procedure is not safe to be called from signal handlers.  Use
     ‘scm_sigaction’ or ‘scm_sigaction_for_thread’ to install signal
     handlers.

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

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

 -- C Function: void scm_dynwind_block_asyncs ()
     This function must be used inside a pair of calls to
     ‘scm_dynwind_begin’ and ‘scm_dynwind_end’ (*note Dynamic Wind::).
     During the dynwind context, asyncs are blocked by one level.

 -- C Function: void scm_dynwind_unblock_asyncs ()
     This function must be used inside a pair of calls to
     ‘scm_dynwind_begin’ and ‘scm_dynwind_end’ (*note Dynamic Wind::).
     During the dynwind context, asyncs are unblocked by one level.


File: guile.info,  Node: User asyncs,  Prev: System asyncs,  Up: Asyncs

5.17.2.2 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 ‘run-asyncs’.  Setting the
mark more than once is satisfied by one execution of the thunk.

   User asyncs are created with ‘async’.  They are marked with
‘async-mark’.

 -- Scheme Procedure: async thunk
 -- C Function: scm_async (thunk)
     Create a new user async for the procedure THUNK.

 -- Scheme Procedure: async-mark a
 -- C Function: scm_async_mark (a)
     Mark the user async A for future execution.

 -- Scheme Procedure: run-asyncs list_of_a
 -- C Function: scm_run_asyncs (list_of_a)
     Execute all thunks from the marked asyncs of the list LIST_OF_A.


File: guile.info,  Node: Continuation Barriers,  Next: Threads,  Prev: Asyncs,  Up: Scheduling

5.17.3 Continuation Barriers
----------------------------

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

 -- Scheme Procedure: with-continuation-barrier proc
 -- C Function: scm_with_continuation_barrier (proc)
     Call PROC and return its result.  Do not allow the invocation of
     continuations that would leave or enter the dynamic extent of the
     call to ‘with-continuation-barrier’.  Such an attempt causes an
     error to be signaled.

     Throws (such as errors) that are not caught from within PROC are
     caught by ‘with-continuation-barrier’.  In that case, a short
     message is printed to the current error port and ‘#f’ is returned.

     Thus, ‘with-continuation-barrier’ returns exactly once.

 -- C Function: void * scm_c_with_continuation_barrier (void *(*func)
          (void *), void *data)
     Like ‘scm_with_continuation_barrier’ but call FUNC on DATA.  When
     an error is caught, ‘NULL’ is returned.


File: guile.info,  Node: Threads,  Next: Mutexes and Condition Variables,  Prev: Continuation Barriers,  Up: Scheduling

5.17.4 Threads
--------------

 -- Scheme Procedure: all-threads
 -- C Function: scm_all_threads ()
     Return a list of all threads.

 -- Scheme Procedure: current-thread
 -- C Function: scm_current_thread ()
     Return the thread that called this function.

 -- Scheme Procedure: call-with-new-thread thunk [handler]
     Call ‘thunk’ in a new thread and with a new dynamic state,
     returning the new thread.  The procedure THUNK is called via
     ‘with-continuation-barrier’.

     When HANDLER is specified, then THUNK is called from within a
     ‘catch’ with tag ‘#t’ that has HANDLER as its handler.  This catch
     is established inside the continuation barrier.

     Once THUNK or HANDLER returns, the return value is made the _exit
     value_ of the thread and the thread is terminated.

 -- C Function: SCM scm_spawn_thread (scm_t_catch_body body, void
          *body_data, scm_t_catch_handler handler, void *handler_data)
     Call BODY in a new thread, passing it BODY_DATA, returning the new
     thread.  The function BODY is called via
     ‘scm_c_with_continuation_barrier’.

     When HANDLER is non-‘NULL’, BODY is called via ‘scm_internal_catch’
     with tag ‘SCM_BOOL_T’ that has HANDLER and HANDLER_DATA as the
     handler and its data.  This catch is established inside the
     continuation barrier.

     Once BODY or HANDLER returns, the return value is made the _exit
     value_ of the thread and the thread is terminated.

 -- Scheme Procedure: join-thread thread
 -- C Function: scm_join_thread (thread)
     Wait for THREAD to terminate and return its exit value.  Threads
     that have not been created with ‘call-with-new-thread’ or
     ‘scm_spawn_thread’ have an exit value of ‘#f’.

 -- Scheme Procedure: thread-exited? thread
 -- C Function: scm_thread_exited_p (thread)
     Return ‘#t’ iff THREAD has exited.

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

   Higher level thread procedures are available by loading the ‘(ice-9
threads)’ module.  These provide standardized thread creation.

 -- macro: make-thread proc [args...]
     Apply PROC to ARGS in a new thread formed by ‘call-with-new-thread’
     using a default error handler that display the error to the current
     error port.  The ARGS... expressions are evaluated in the new
     thread.

 -- macro: begin-thread first [rest...]
     Evaluate forms FIRST and REST in a new thread formed by
     ‘call-with-new-thread’ using a default error handler that display
     the error to the current error port.


File: guile.info,  Node: Mutexes and Condition Variables,  Next: Blocking,  Prev: Threads,  Up: Scheduling

5.17.5 Mutexes and Condition Variables
--------------------------------------

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

   There are two types of mutexes in Guile, "standard" and "recursive".
They're created by ‘make-mutex’ and ‘make-recursive-mutex’ respectively,
the operation functions are then common to both.

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


 -- Scheme Procedure: make-mutex
 -- C Function: scm_make_mutex ()
     Return a new standard mutex.  It is initially unlocked.

 -- Scheme Procedure: make-recursive-mutex
 -- C Function: scm_make_recursive_mutex ()
     Create a new recursive mutex.  It is initialloy unlocked.

 -- Scheme Procedure: lock-mutex mutex
 -- C Function: scm_lock_mutex (mutex)
     Lock MUTEX.  If the mutex is already locked by another thread then
     block and return only when MUTEX has been acquired.

     For standard mutexes (‘make-mutex’), and error is signalled if the
     thread has itself already locked MUTEX.

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

     When a system async (*note System asyncs::) is activated for a
     thread blocked in ‘lock-mutex’, the wait is interrupted and the
     async is executed.  When the async returns, the wait resumes.

 -- C Function: void scm_dynwind_lock_mutex (SCM mutex)
     Arrange for MUTEX to be locked whenever the current dynwind context
     is entered and to be unlocked when it is exited.

 -- Scheme Procedure: try-mutex mx
 -- C Function: scm_try_mutex (mx)
     Try to lock MUTEX as per ‘lock-mutex’.  If MUTEX can be acquired
     immediately then this is done and the return is ‘#t’.  If MUTEX is
     locked by some other thread then nothing is done and the return is
     ‘#f’.

 -- Scheme Procedure: unlock-mutex mutex
 -- C Function: scm_unlock_mutex (mutex)
     Unlock MUTEX.  An error is signalled if MUTEX is not locked by the
     calling thread.

 -- Scheme Procedure: make-condition-variable
 -- C Function: scm_make_condition_variable ()
     Return a new condition variable.

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

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

 -- Scheme Procedure: signal-condition-variable condvar
 -- C Function: scm_signal_condition_variable (condvar)
     Wake up one thread that is waiting for CONDVAR.

 -- Scheme Procedure: broadcast-condition-variable condvar
 -- C Function: scm_broadcast_condition_variable (condvar)
     Wake up all threads that are waiting for CONDVAR.


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

     (use-modules (ice-9 threads))

 -- macro: with-mutex mutex [body...]
     Lock MUTEX, evaluate the BODY forms, then unlock MUTEX.  The return
     value is the return from the last BODY form.

     The lock, body and unlock form the branches of a ‘dynamic-wind’
     (*note Dynamic Wind::), so MUTEX is automatically unlocked if an
     error or new continuation exits BODY, and is re-locked if BODY is
     re-entered by a captured continuation.

 -- macro: monitor body...
     Evaluate the BODY forms, with a mutex locked so only one thread can
     execute that code at any one time.  The return value is the return
     from the last BODY form.

     Each ‘monitor’ form has its own private mutex and the locking and
     evaluation is as per ‘with-mutex’ above.  A standard mutex
     (‘make-mutex’) is used, which means BODY must not recursively
     re-enter the ‘monitor’ form.

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


File: guile.info,  Node: Blocking,  Next: Critical Sections,  Prev: Mutexes and Condition Variables,  Up: Scheduling

5.17.6 Blocking in Guile Mode
-----------------------------

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

 -- C Function: void * scm_without_guile (void *(*func) (void *), void
          *data)
     Leave guile mode, call FUNC on DATA, enter guile mode and return
     the result of calling FUNC.

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

     When used from non-guile mode, calling ‘scm_without_guile’ is still
     allowed: it simply calls FUNC.  In that way, you can leave guile
     mode without having to know whether the current thread is in guile
     mode or not.

 -- C Function: int scm_pthread_mutex_lock (pthread_mutex_t *mutex)
     Like ‘pthread_mutex_lock’, but leaves guile mode while waiting for
     the mutex.

 -- C Function: int scm_pthread_cond_wait (pthread_cond_t *cond,
          pthread_mutex_t *mutex)
 -- C Function: int scm_pthread_cond_timedwait (pthread_cond_t *cond,
          pthread_mutex_t *mutex, struct timespec *abstime)
     Like ‘pthread_cond_wait’ and ‘pthread_cond_timedwait’, but leaves
     guile mode while waiting for the condition variable.

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

 -- C Function: unsigned int scm_std_sleep (unsigned int seconds)
     Like ‘sleep’, but leaves guile mode while sleeping.  Also, the
     delivery of a system async causes this function to be interrupted.

 -- C Function: unsigned long scm_std_usleep (unsigned long usecs)
     Like ‘usleep’, but leaves guile mode while sleeping.  Also, the
     delivery of a system async causes this function to be interrupted.


File: guile.info,  Node: Critical Sections,  Next: Fluids and Dynamic States,  Prev: Blocking,  Up: Scheduling

5.17.7 Critical Sections
------------------------

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

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

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

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

 -- C Function: void scm_dynwind_critical_section (SCM mutex)
     Call ‘scm_dynwind_lock_mutex’ on MUTEX and call
     ‘scm_dynwind_block_asyncs’.  When MUTEX is false, a recursive mutex
     provided by Guile is used instead.

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

     When the current thread reenters the critical section anyway, the
     kind of MUTEX determines what happens: When MUTEX is recursive, the
     reentry is allowed.  When it is a normal mutex, an error is
     signalled.


File: guile.info,  Node: Fluids and Dynamic States,  Next: Parallel Forms,  Prev: Critical Sections,  Up: Scheduling

5.17.8 Fluids and Dynamic States
--------------------------------

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

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

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

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

 -- Scheme Procedure: fluid? obj
 -- C Function: scm_fluid_p (obj)
     Return ‘#t’ iff OBJ is a fluid; otherwise, return ‘#f’.

 -- Scheme Procedure: fluid-ref fluid
 -- C Function: scm_fluid_ref (fluid)
     Return the value associated with FLUID in the current dynamic root.
     If FLUID has not been set, then return ‘#f’.

 -- Scheme Procedure: fluid-set! fluid value
 -- C Function: scm_fluid_set_x (fluid, value)
     Set the value associated with FLUID in the current dynamic root.

   ‘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.

 -- Scheme Procedure: with-fluid* fluid value thunk
 -- C Function: scm_with_fluid (fluid, value, thunk)
     Set FLUID to VALUE temporarily, and call THUNK.  THUNK must be a
     procedure with no argument.

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

 -- Scheme Macro: with-fluids ((fluid value) ...) body...
     Execute BODY... while each FLUID is set to the corresponding VALUE.
     Both FLUID and VALUE are evaluated and FLUID must yield a fluid.
     BODY... is executed inside a ‘dynamic-wind’ and the fluids are
     set/restored when control enter or leaves the established dynamic
     extent.

 -- C Function: SCM scm_c_with_fluids (SCM fluids, SCM vals, SCM
          (*cproc)(void *), void *data)
 -- C Function: SCM scm_c_with_fluid (SCM fluid, SCM val, SCM
          (*cproc)(void *), void *data)
     The function ‘scm_c_with_fluids’ is like ‘scm_with_fluids’ except
     that it takes a C function to call instead of a Scheme thunk.

     The function ‘scm_c_with_fluid’ is similar but only allows one
     fluid to be set instead of a list.

 -- C Function: void scm_dynwind_fluid (SCM fluid, SCM val)
     This function must be used inside a pair of calls to
     ‘scm_dynwind_begin’ and ‘scm_dynwind_end’ (*note Dynamic Wind::).
     During the dynwind context, the fluid FLUID is set to VAL.

     More precisely, the value of the fluid is swapped with a 'backup'
     value whenever the dynwind context is entered or left.  The backup
     value is initialized with the VAL argument.

 -- Scheme Procedure: make-dynamic-state [parent]
 -- C Function: scm_make_dynamic_state (parent)
     Return a copy of the dynamic state object PARENT or of the current
     dynamic state when PARENT is omitted.

 -- Scheme Procedure: dynamic-state? obj
 -- C Function: scm_dynamic_state_p (obj)
     Return ‘#t’ if OBJ is a dynamic state object; return ‘#f’
     otherwise.

 -- C Procedure: int scm_is_dynamic_state (SCM obj)
     Return non-zero if OBJ is a dynamic state object; return zero
     otherwise.

 -- Scheme Procedure: current-dynamic-state
 -- C Function: scm_current_dynamic_state ()
     Return the current dynamic state object.

 -- Scheme Procedure: set-current-dynamic-state state
 -- C Function: scm_set_current_dynamic_state (state)
     Set the current dynamic state object to STATE and return the
     previous current dynamic state object.

 -- Scheme Procedure: with-dynamic-state state proc
 -- C Function: scm_with_dynamic_state (state, proc)
     Call PROC while STATE is the current dynamic state object.

 -- C Procedure: void scm_dynwind_current_dynamic_state (SCM state)
     Set the current dynamic state to STATE for the current dynwind
     context.

 -- C Procedure: void * scm_c_with_dynamic_state (SCM state, void
          *(*func)(void *), void *data)
     Like ‘scm_with_dynamic_state’, but call FUNC with DATA.

