   Guile Reference Manual Copyright (C) 1996 Free Software Foundation
Copyright (C) 1997 Free Software Foundation
Copyright (C) 2000 Free Software Foundation
Copyright (C) 2001 Free Software Foundation
Copyright (C) 2002 Free Software Foundation

   Permission is granted to make and distribute verbatim copies of this
manual provided the copyright notice and this permission notice are
preserved on all copies.

   Permission is granted to copy and distribute modified versions of
this manual under the conditions for verbatim copying, provided that
the entire resulting derived work is distributed under the terms of a
permission notice identical to this one.

   Permission is granted to copy and distribute translations of this
manual into another language, under the above conditions for modified
versions, except that this permission notice may be stated in a
translation approved by the Free Software Foundation.

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.

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

   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.

   `scm_make_port_type' initializes three elements of the structure
(`name', `fill_input' and `write') from its arguments.  The remaining
elements are initialized with default values and can be set later if
required.

`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 `scm_set_port_mark'.

`free'
     Called when the port is collected during gc.  It should free any
     resources used by the port.  Set using `scm_set_port_free'.

`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 `scm_set_port_print'.

`equalp'
     Not used at present.  Set using `scm_set_port_equalp'.

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

`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
     `scm_set_port_flush'.

`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 `scm_set_port_end_input'.

`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
     `scm_set_port_input_waiting'.

`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 (object);
                else if (pt->rw_active == SCM_PORT_WRITE)
          	ptob->flush (object);

     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 `scm_set_port_seek'.

`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 `scm_set_port_truncate'.

Reading and Evaluating Scheme Code
**********************************

   This chapter describes Guile functions that are concerned with
reading, loading and evaluating Scheme code at run time.

Scheme Syntax: Standard and Guile Extensions
============================================

Expression Syntax
-----------------

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.

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' (see 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
(see Guile Scripting).

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

Keyword Syntax
--------------

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

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,
see User level options interfaces.  If you want to know which
reader options are available, see 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'.

Procedures for On the Fly Evaluation
====================================

   See Environments.

 - Scheme Procedure: eval exp module
 - C Function: scm_eval (exp, module)
     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.

 - 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
 - C Function: scm_eval_string (string)
     Evaluate STRING as the text representation of a Scheme form or
     forms, and return whatever value they produce.  Evaluation takes
     place in the environment returned by the procedure
     `interaction-environment'.

 - Scheme Procedure: apply:nconc2last lst
 - C Function: scm_nconc2last (lst)
     Given a list (ARG1 ... ARGS), this function conses the ARG1 ...
     arguments onto the front of ARGS, and returns the resulting list.
     Note that ARGS is a list; thus, the argument to this function is a
     list whose last element is a list.  Note: Rather than do new
     consing, `apply:nconc2last' destroys its argument, so use with
     care.

 - Scheme Procedure: apply proc arg1 ... args
     PROC must be a procedure and ARGS must be a list.  Call PROC with
     the elements of the list `(append (list ARG1 ...) ARGS)' as the
     actual arguments.

 - Scheme Procedure: primitive-eval exp
 - C Function: scm_primitive_eval (exp)
     Evaluate EXP in the top-level environment specified by the current
     module.

Loading Scheme Code from File
=============================

 - Scheme Procedure: load filename
     Load FILENAME and evaluate its contents in the top-level
     environment.  The load paths are not searched.  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.

 - 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: %load-hook
     A procedure to be run whenever `primitive-load' is called.  If this
     procedure is defined, it will be called with the filename argument
     that was passed to `primitive-load'.

          (define %load-hook (lambda (file)
                               (display "Loading ")
                               (display file)
                               (write-line "...."))) => undefined
          (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")'.

Delayed Evaluation
==================

   [delay]

 - Scheme Procedure: promise? obj
 - C Function: scm_promise_p (obj)
     Return true if OBJ is a promise, i.e. a delayed computation (see
     Delayed evaluation (r5rs.info)).

 - Scheme Procedure: force x
 - C Function: scm_force (x)
     If the promise X has not been computed yet, compute and return X,
     otherwise just return the previously computed value.

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

Evaluator Behaviour
===================

   The behaviour of Guile's evaluator can be modified by manipulating
the evaluator options.  For more information about options, see User level options interfaces.
If you want to know which evaluator
options are available, see 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.

 - Scheme Procedure: evaluator-traps-interface [setting]
 - C Function: scm_evaluator_traps (setting)
     Option interface for the evaluator trap options.

Memory Management and Garbage Collection
****************************************

   Guile uses a _garbage collector_ to manage most of its objects.
This means that the memory used to store a Scheme string, say, is
automatically reclaimed when no one is using this string any longer.
This can work because Guile knows enough about its objects at run-time
to be able to trace all references between them.  Thus, it can find all
'live' objects (objects that are still in use) by starting from a known
set of 'root' objects and following the links that these objects have
to other objects, and so on.  The objects that are not reached by this
recursive process can be considered 'dead' and their memory can be
reused for new objects.

   When you are programming in Scheme, you don't need to worry about the
garbage collector.  When programming in C, there are a few rules that
you must follow so that the garbage collector can do its job.

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.

 - Scheme Procedure: gc-stats
 - C Function: scm_gc_stats ()
     Return an association list of statistics about Guile's current use
     of storage.

 - Scheme Procedure: object-address obj
 - C Function: scm_object_address (obj)
     Return an integer that for the lifetime of OBJ is uniquely
     returned by this function for OBJ

 - Scheme Procedure: unhash-name name
     Flushes the glocs for NAME, or all glocs if NAME is `#t'.

 - Scheme Procedure: malloc-stats
     Return an alist ((WHAT . N) ...) describing number of malloced
     objects.  WHAT is the second argument to `scm_must_malloc', N is
     the number of objects of that type currently allocated.

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

Weak key hashes
---------------

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

 - Scheme Procedure: make-weak-value-hash-table k

 - Scheme Procedure: weak-value-hash-table? x

 - Scheme Procedure: make-doubly-weak-hash-table k

 - Scheme Procedure: doubly-weak-hash-table? x

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.

Guardians
=========

 - Scheme Procedure: make-guardian [greedy?]
 - C Function: scm_make_guardian (greedy_p)
     Create a new guardian.  A guardian protects a set of objects from
     garbage collection, allowing a program to apply cleanup or other
     actions.

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

     `make-guardian' takes one optional argument that says whether the
     new guardian should be greedy or sharing.  If there is any chance
     that any object protected by the guardian may be resurrected, then
     you should make the guardian greedy (this is the default).

     See R. Kent Dybvig, Carl Bruggeman, and David Eby (1993)
     "Guardians in a Generation-Based Garbage Collector".  ACM SIGPLAN
     Conference on Programming Language Design and Implementation, June
     1993.

     (the semantics are slightly different at this point, but the paper
     still (mostly) accurately describes the interface).

 - Scheme Procedure: destroy-guardian! guardian
 - C Function: scm_destroy_guardian_x (guardian)
     Destroys GUARDIAN, by making it impossible to put any more objects
     in it or get any objects from it.  It also unguards any objects
     guarded by GUARDIAN.

 - Scheme Procedure: guardian-greedy? guardian
 - C Function: scm_guardian_greedy_p (guardian)
     Return `#t' if GUARDIAN is a greedy guardian, otherwise `#f'.

 - Scheme Procedure: guardian-destroyed? guardian
 - C Function: scm_guardian_destroyed_p (guardian)
     Return `#t' if GUARDIAN has been destroyed, otherwise `#f'.

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.

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.

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.

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: About Closure.  In other words, it
implements a set of "bindings".

   Environments in R5RS can be passed as the second argument to `eval'
(see Fly Evaluation).  Three procedures are defined to return
environments: `scheme-report-environment', `null-environment' and
`interaction-environment' (see Fly Evaluation).

   In addition, in Guile any module can be used as an R5RS environment,
i.e., passed as the second argument to `eval'.

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

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

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" (see 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 (see 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' (see Loading).  The resulting file name is then
searched in all directories in the variable `%load-path' (see 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 (see Creating Guile Modules).

   Please note that there are some problems with the current module
system you should keep in mind (see Module System Quirks).  We hope
to address these eventually.

Using Guile Modules
-------------------

   To use a Guile module is to access either its public interface or a
custom interface (see 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 (see 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 (see 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'.

 - 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 system transformer as
     the system transformer for the currently defined module, as well
     as installing it as the current system transformer.

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)'
          (see Using Guile Modules).

    `#:use-syntax MODULE'
          Use MODULE when loading the currently defined module, and
          install it as the syntax transformer.

    `#:autoload MODULE SYMBOL'
          Load MODULE whenever SYMBOL is accessed.

    `#:export LIST'
          Export all identifiers in LIST, which must be a list of
          symbols.  This is equivalent to `(export LIST)' in the module
          body.

    `#: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))'.

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 (see 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.]

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 (see
     Debugging Features).

*(ice-9 threads)*
     Guile's support for multi threaded execution (see Scheduling).

*(ice-9 rdelim)*
     Line- and character-delimited input (see Line/Delimited).

*(ice-9 rw)*
     Block string input/output (see Block Reading and Writing).

*(ice-9 documentation)*
     Online documentation (REFFIXME).

*(srfi srfi-1)*
     A library providing a lot of useful list and pair processing
     procedures (see SRFI-1).

*(srfi srfi-2)*
     Support for `and-let*' (see SRFI-2).

*(srfi srfi-4)*
     Support for homogeneous numeric vectors (see SRFI-4).

*(srfi srfi-6)*
     Support for some additional string port procedures (see
     SRFI-6).

*(srfi srfi-8)*
     Multiple-value handling with `receive' (see SRFI-8).

*(srfi srfi-9)*
     Record definition with `define-record-type' (see SRFI-9).

*(srfi srfi-10)*
     Read hash extension `#,()' (see SRFI-10).

*(srfi srfi-11)*
     Multiple-value handling with `let-values' and `let-values*' (see
     SRFI-11).

*(srfi srfi-13)*
     String library (see SRFI-13).

*(srfi srfi-14)*
     Character-set library (see SRFI-14).

*(srfi srfi-17)*
     Getter-with-setter support (see SRFI-17).

*(ice-9 slib)*
     This module contains hooks for using Aubrey Jaffer's portable
     Scheme library SLIB from Guile (see SLIB).

*(ice-9 jacal)*
     This module contains hooks for using Aubrey Jaffer's symbolic math
     package Jacal from Guile (see JACAL).