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

INFO-DIR-SECTION The Algorithmic Language Scheme
START-INFO-DIR-ENTRY
* Guile Reference: (guile).     The Guile reference manual.
END-INFO-DIR-ENTRY

   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 Copyright (C) 2004 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.


File: guile.info,  Node: Top,  Next: Guile License,  Prev: (dir),  Up: (dir)

The Guile Reference Manual
**************************

This reference manual documents Guile, GNU's Ubiquitous Intelligent
Language for Extensions.  It describes how to use Guile in many useful
and interesting ways.

   This Info file contains edition 1.0 of the reference manual,
corresponding to Guile version 1.6.5.

* Menu:

Preface

* Guile License::               Conditions for copying and using Guile.
* Manual Layout::               How to read the rest of this manual.
* Manual Conventions::          Conventional terminology.

Part I: Introduction to Guile

* What is Guile?::              And what does it do?
* Whirlwind Tour::              An introductory whirlwind tour.
* Obtaining and Installing Guile::
* Reporting Bugs::              Reporting bugs in Guile or this manual.

Part II: Writing and Running Guile Scheme

* Running Intro::               Introduction to this part.
* Guile Scheme::                Guile's implementation of Scheme.
* Guile Scripting::             How to write Guile scripts.
* Command Line Handling::       Command line options and arguments.
* Debugging Features::          Features for debugging errors.
* Autoconf Support::            Guile-specific configure.in macros.
* Miscellaneous Tools::         Snarfing, linting, etc.
* Basic Ideas::                 Basic ideas in Scheme.
* Further Reading::             Where to find out more about Scheme.

Part III: Guile as an Extension Language

* Programming Intro::           Introduction to this part.
* Libguile Intro::              Using Guile as an extension language.
* Programming Overview::        An overview of Guile programming.
* Data Representation::         Data representation in Guile.
* GH::                          The deprecated GH interface.

Part IV: Guile API Reference

* Reference Intro::             Introduction to the Guile API reference.
* API Overview::                Overview of the Guile API.
* Simple Data Types::           Numbers, strings, booleans and so on.
* Compound Data Types::         Data types for holding other data.
* Procedures and Macros::       Procedures and macros.
* Utility Functions::           General utility functions.
* Binding Constructs::          Definitions and variable bindings.
* Control Mechanisms::          Controlling the flow of program execution.
* Input and Output::            Ports, reading and writing.
* Read/Load/Eval::              Reading and evaluating Scheme code.
* Memory Management::           Memory management and garbage collection.
* Objects::                     Low level object orientation support.
* Modules::                     Designing reusable code libraries.
* Scheduling::                  Threads, mutexes, asyncs and dynamic roots.
* Options and Config::          Configuration, features and runtime options.
* Translation::                 Support for translating other languages.
* Debugging::                   Internal debugging interface.
* Deprecated::                  Features that are planned to disappear.

Part V: Guile Modules

* SLIB::                        Using the SLIB Scheme library.
* POSIX::                       POSIX system calls and networking.
* SRFI Support::                Support for various SRFIs.
* Readline Support::            Module for using the readline library.
* Value History::               Maintaining a value history in the REPL.
* Pretty Printing::             Nicely formatting Scheme objects for output.
* Formatted Output::            The `format' procedure.
* Rx Regexps::                  The Rx regular expression library.
* Expect::			Controlling interactive programs with Guile.
* The Scheme shell (scsh)::     Using scsh interfaces in Guile.

Indices

* Concept Index::
* Procedure Index::
* Variable Index::
* Type Index::
* R5RS Index::


File: guile.info,  Node: Guile License,  Next: Manual Layout,  Prev: Top,  Up: Top

1 The Guile License
*******************

   The license of Guile consists of the GNU GPL plus a special statement
giving blanket permission to link with non-free software.  This is the
license statement as found in any individual file that it applies to:

     This program is free software; you can redistribute it and/or
     modify it under the terms of the GNU General Public License as
     published by the Free Software Foundation; either version 2, or
     (at your option) any later version.

     This program is distributed in the hope that it will be useful, but
     WITHOUT ANY WARRANTY; without even the implied warranty of
     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
     General Public License for more details.

     You should have received a copy of the GNU General Public License
     along with this software; see the file COPYING.  If not, write to
     the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
     Boston, MA 02111-1307 USA

     As a special exception, the Free Software Foundation gives
     permission for additional uses of the text contained in its
     release of GUILE.

     The exception is that, if you link the GUILE library with other
     files to produce an executable, this does not by itself cause the
     resulting executable to be covered by the GNU General Public
     License.  Your use of that executable is in no way restricted on
     account of linking the GUILE library code into it.

     This exception does not however invalidate any other reasons why
     the executable file might be covered by the GNU General Public
     License.

     This exception applies only to the code released by the Free
     Software Foundation under the name GUILE.  If you copy code from
     other Free Software Foundation releases into a copy of GUILE, as
     the General Public License permits, the exception does not apply
     to the code that you add in this way.  To avoid misleading anyone
     as to the status of such modified files, you must delete this
     exception notice from them.

     If you write modifications of your own for GUILE, it is your choice
     whether to permit this exception to apply to your modifications.
     If you do not wish that, delete this exception notice.


File: guile.info,  Node: Manual Layout,  Next: Manual Conventions,  Prev: Guile License,  Up: Top

2 Layout of this Manual
***********************

   The manual is divided into five parts.

   *Part I: Introduction to Guile* provides an overview of what Guile
is and how you can use it.  A whirlwind tour shows how Guile can be
used interactively and as a script interpreter, how to link Guile into
your own applications, and how to write modules of interpreted and
compiled code for use with Guile.  Everything introduced here is
documented again and in full by the later parts of the manual.  This
part also explains how to obtain and install new versions of Guile, and
how to report bugs effectively.

   *Part II: Writing and Running Guile Scheme* and *Part III:
Programming with Guile* document all aspects of practical programming
using Guile.  This covers both the Scheme level -- where we provide an
introduction to the key ideas of the Scheme language -- and use of
Guile's `scm' interface to write new primitives and objects in C, and
to incorporate Guile into a C application.  It also covers the use of
Guile as a POSIX compliant script interpreter, and how to use the Guile
debugger.

   *Part IV: Guile API Reference* documents Guile's core API.  Most of
the variables and procedures in Guile's core programming interface are
available in both Scheme and C, and are related systematically such
that the C interface can be inferred from the Scheme interface and vice
versa.  Therefore this part of the manual documents the Guile API in
functionality-based groups with the Scheme and C interfaces presented
side by side.  Where the Scheme and C interfaces for a particular
functional area do differ -- which is sometimes inevitable, given the
differences in the structure of the two languages -- this is pointed
out and explained.  In all cases the overriding principle is that all
the reference documentation for a given functional area is grouped
together.

   *Part V: Guile Modules* describes some important modules,
distributed as part of the Guile distribution, that extend the
functionality provided by the Guile Scheme core.  Two important examples
are:

   * the POSIX module, which provides Scheme level procedures for
     system and network programming that conform to the POSIX standard

   * the SLIB module, which makes Aubrey Jaffer's portable Scheme
     library available for use in Guile.


File: guile.info,  Node: Manual Conventions,  Next: What is Guile?,  Prev: Manual Layout,  Up: Top

3 Conventions used in this Manual
*********************************

   We use some conventions in this manual.

   * For some procedures, notably type predicates, we use "iff" to mean
     `if and only if'.  The construct is usually something like:
     `Return VAL iff CONDITION', where VAL is usually ``#t'' or
     `non-`#f''.  This typically means that VAL is returned if
     CONDITION holds, and that `#f' is returned otherwise.  

   * In examples and procedure descriptions and all other places where
     the evaluation of Scheme expression is shown, we use some notation
     for denoting the output and evaluation results of expressions.

     The symbol `=>' is used to tell which value is returned by an
     evaluation:

          (+ 1 2)
          =>
          3

     Some procedures produce some output besides returning a value.
     This is denoted by the symbol `-|'.

          (begin (display 1) (newline) 'hooray)
          -| 1
          =>
          hooray



File: guile.info,  Node: What is Guile?,  Next: Whirlwind Tour,  Prev: Manual Conventions,  Up: Top

4 What is Guile?
****************

Guile is an interpreter for the Scheme programming language, packaged
for use in a wide variety of environments.  Guile implements Scheme as
described in the Revised^5 Report on the Algorithmic Language Scheme
(usually known as R5RS), providing clean and general data and control
structures.  Guile goes beyond the rather austere language presented in
R5RS, extending it with a module system, full access to POSIX system
calls, networking support, multiple threads, dynamic linking, a foreign
function call interface, powerful string processing, and many other
features needed for programming in the real world.

   Like a shell, Guile can run interactively, reading expressions from
the user, evaluating them, and displaying the results, or as a script
interpreter, reading and executing Scheme code from a file.  However,
Guile is also packaged as an object library, allowing other applications
to easily incorporate a complete Scheme interpreter.  An application can
use Guile as an extension language, a clean and powerful configuration
language, or as multi-purpose "glue", connecting primitives provided by
the application.  It is easy to call Scheme code from C code and vice
versa, giving the application designer full control of how and when to
invoke the interpreter.  Applications can add new functions, data types,
control structures, and even syntax to Guile, creating a domain-specific
language tailored to the task at hand, but based on a robust language
design.

   Guile's module system allows one to break up a large program into
manageable sections with well-defined interfaces between them.  Modules
may contain a mixture of interpreted and compiled code; Guile can use
either static or dynamic linking to incorporate compiled code.  Modules
also encourage developers to package up useful collections of routines
for general distribution; as of this writing, one can find Emacs
interfaces, database access routines, compilers, GUI toolkit interfaces,
and HTTP client functions, among others.

   In the future, we hope to expand Guile to support other languages
like Tcl and Perl by translating them to Scheme code.  This means that
users can program applications which use Guile in the language of their
choice, rather than having the tastes of the application's author
imposed on them.


File: guile.info,  Node: Whirlwind Tour,  Next: Obtaining and Installing Guile,  Prev: What is Guile?,  Up: Top

5 A Whirlwind Tour
******************

This chapter presents a quick tour of all the ways that Guile can be
used.  There are additional examples in the `examples/' directory in
the Guile source distribution.

* Menu:

* Running Guile Interactively::
* Guile Scripts::
* Linking Programs With Guile::
* Writing Extensions for Guile::
* Guile Modules::


File: guile.info,  Node: Running Guile Interactively,  Next: Guile Scripts,  Up: Whirlwind Tour

5.1 Running Guile Interactively
===============================

In its simplest form, Guile acts as an interactive interpreter for the
Scheme programming language, reading and evaluating Scheme expressions
the user enters from the terminal.  Here is a sample interaction between
Guile and a user; the user's input appears after the `$' and `guile>'
prompts:

     $ guile
     guile> (+ 1 2 3)                ; add some numbers
     6
     guile> (define (factorial n)    ; define a function
              (if (zero? n) 1 (* n (factorial (- n 1)))))
     guile> (factorial 20)
     2432902008176640000
     guile> (getpwnam "jimb")        ; find my entry in /etc/passwd
     #("jimb" ".0krIpK2VqNbU" 4008 10 "Jim Blandy" "/u/jimb"
       "/usr/local/bin/bash")
     guile> C-d
     $


File: guile.info,  Node: Guile Scripts,  Next: Linking Programs With Guile,  Prev: Running Guile Interactively,  Up: Whirlwind Tour

5.2 Guile Scripts
=================

Like AWK, Perl, or any shell, Guile can interpret script files.  A Guile
script is simply a file of Scheme code with some extra information at
the beginning which tells the operating system how to invoke Guile, and
then tells Guile how to handle the Scheme code.

   Before we present the details, here is a trivial Guile script:

     #!/usr/local/bin/guile -s
     !#
     (display "Hello, world!")
     (newline)

* Menu:

* The Top of a Script File::    How to start a Guile script.
* Scripting Examples::          Simple Guile scripts, explained.


File: guile.info,  Node: The Top of a Script File,  Next: Scripting Examples,  Up: Guile Scripts

5.2.1 The Top of a Script File
------------------------------

The first line of a Guile script must tell the operating system to use
Guile to evaluate the script, and then tell Guile how to go about doing
that.  Here is the simplest case:

   * The first two characters of the file must be `#!'.

     The operating system interprets this to mean that the rest of the
     line is the name of an executable that can interpret the script.
     Guile, however, interprets these characters as the beginning of a
     multi-line comment, terminated by the characters `!#' on a line by
     themselves.  (This is an extension to the syntax described in
     R5RS, added to support shell scripts.)

   * Immediately after those two characters must come the full pathname
     to the Guile interpreter.  On most systems, this would be
     `/usr/local/bin/guile'.

   * Then must come a space, followed by a command-line argument to
     pass to Guile; this should be `-s'.  This switch tells Guile to
     run a script, instead of soliciting the user for input from the
     terminal.  There are more elaborate things one can do here; see
     *Note The Meta Switch::.

   * Follow this with a newline.

   * The second line of the script should contain only the characters
     `!#' -- just like the top of the file, but reversed.  The
     operating system never reads this far, but Guile treats this as
     the end of the comment begun on the first line by the `#!'
     characters.

   * The rest of the file should be a Scheme program.


   Guile reads the program, evaluating expressions in the order that
they appear.  Upon reaching the end of the file, Guile exits.

   The function `command-line' returns the name of the script file and
any command-line arguments passed by the user, as a list of strings.

   For example, consider the following script file:
     #!/usr/local/bin/guile -s
     !#
     (write (command-line))
     (newline)

   If you put that text in a file called `foo' in the current
directory, then you could make it executable and try it out like this:
     $ chmod a+x foo
     $ ./foo
     ("./foo")
     $ ./foo bar baz
     ("./foo" "bar" "baz")
     $

   As another example, here is a simple replacement for the POSIX
`echo' command:
     #!/usr/local/bin/guile -s
     !#
     (for-each (lambda (s) (display s) (display " "))
       (cdr (command-line)))
     (newline)

 -- Scheme Procedure: command-line
 -- Scheme Procedure: program-arguments
     Return a list of the command-line arguments passed to the currently
     running program.  If the program invoked Guile with the `-s', `-c'
     or `--' switches, these procedures ignore everything up to and
     including those switches.


File: guile.info,  Node: Scripting Examples,  Prev: The Top of a Script File,  Up: Guile Scripts

5.2.2 Scripting Examples
------------------------

To start with, here are some examples of invoking Guile directly:

`guile -- a b c'
     Run Guile interactively; `(command-line)' will return
     `("/usr/local/bin/guile" "a" "b" "c")'.

`guile -s /u/jimb/ex2 a b c'
     Load the file `/u/jimb/ex2'; `(command-line)' will return
     `("/u/jimb/ex2" "a" "b" "c")'.

`guile -c '(write %load-path) (newline)''
     Write the value of the variable `%load-path', print a newline, and
     exit.

`guile -e main -s /u/jimb/ex4 foo'
     Load the file `/u/jimb/ex4', and then call the function `main',
     passing it the list `("/u/jimb/ex4" "foo")'.

`guile -l first -ds -l last -s script'
     Load the files `first', `script', and `last', in that order.  The
     `-ds' switch says when to process the `-s' switch.  For a more
     motivated example, see the scripts below.


   Here is a very simple Guile script:
     #!/usr/local/bin/guile -s
     !#
     (display "Hello, world!")
     (newline)
   The first line marks the file as a Guile script.  When the user
invokes it, the system runs `/usr/local/bin/guile' to interpret the
script, passing `-s', the script's filename, and any arguments given to
the script as command-line arguments.  When Guile sees `-s SCRIPT', it
loads SCRIPT.  Thus, running this program produces the output:
     Hello, world!

   Here is a script which prints the factorial of its argument:
     #!/usr/local/bin/guile -s
     !#
     (define (fact n)
       (if (zero? n) 1
         (* n (fact (- n 1)))))

     (display (fact (string->number (cadr (command-line)))))
     (newline)
   In action:
     $ fact 5
     120
     $

   However, suppose we want to use the definition of `fact' in this
file from another script.  We can't simply `load' the script file, and
then use `fact''s definition, because the script will try to compute
and display a factorial when we load it.  To avoid this problem, we
might write the script this way:

     #!/usr/local/bin/guile \
     -e main -s
     !#
     (define (fact n)
       (if (zero? n) 1
         (* n (fact (- n 1)))))

     (define (main args)
       (display (fact (string->number (cadr args))))
       (newline))
   This version packages the actions the script should perform in a
function, `main'.  This allows us to load the file purely for its
definitions, without any extraneous computation taking place.  Then we
used the meta switch `\' and the entry point switch `-e' to tell Guile
to call `main' after loading the script.
     $ fact 50
     30414093201713378043612608166064768844377641568960512000000000000

   Suppose that we now want to write a script which computes the
`choose' function: given a set of M distinct objects, `(choose N M)' is
the number of distinct subsets containing N objects each.  It's easy to
write `choose' given `fact', so we might write the script this way:
     #!/usr/local/bin/guile \
     -l fact -e main -s
     !#
     (define (choose n m)
       (/ (fact m) (* (fact (- m n)) (fact n))))

     (define (main args)
       (let ((n (string->number (cadr args)))
             (m (string->number (caddr args))))
         (display (choose n m))
         (newline)))

   The command-line arguments here tell Guile to first load the file
`fact', and then run the script, with `main' as the entry point.  In
other words, the `choose' script can use definitions made in the `fact'
script.  Here are some sample runs:
     $ choose 0 4
     1
     $ choose 1 4
     4
     $ choose 2 4
     6
     $ choose 3 4
     4
     $ choose 4 4
     1
     $ choose 50 100
     100891344545564193334812497256


File: guile.info,  Node: Linking Programs With Guile,  Next: Writing Extensions for Guile,  Prev: Guile Scripts,  Up: Whirlwind Tour

5.3 Linking Programs With Guile
===============================

The Guile interpreter is available as an object library, to be linked
into applications using Scheme as a configuration or extension
language.  This chapter covers the mechanics of linking your program
with Guile on a typical POSIX system.

   Parts III and IV of this manual describe the C functions Guile
provides.  Furthermore, any Scheme function described in this manual as
a "Primitive" is also callable from C; see *Note Primitives::.

   The header file `<libguile.h>' provides declarations for all of
Guile's functions and constants.  You should `#include' it at the head
of any C source file that uses identifiers described in this manual.
Once you've compiled your source files, you need to link them against
the Guile object code library, `libguile'.

   On most systems, you should not need to tell the compiler and linker
explicitly where they can find `libguile.h' and `libguile'.  When Guile
has been installed in a peculiar way, or when you are on a peculiar
system, things might not be so easy and you might need to pass
additional `-I' or `-L' options to the compiler.  Guile provides the
utility program `guile-config' to help you find the right values for
these options.  You would typically run `guile-config' during the
configuration phase of your program and use the obtained information in
the Makefile.

* Menu:

* Guile Initialization Functions::  What to call first.
* A Sample Guile Main Program::  Sources and makefiles.


File: guile.info,  Node: Guile Initialization Functions,  Next: A Sample Guile Main Program,  Up: Linking Programs With Guile

5.3.1 Guile Initialization Functions
------------------------------------

To initialize Guile, you can use one of two functions.  The first,
`scm_boot_guile', is the most portable way to initialize Guile.  It
should be used whenever you have control over the main function of your
program because it never returns.  The second function,
`scm_init_guile', does return and can thus be used in more situations.
However, `scm_init_guile' is not as widely available as
`scm_boot_guile' because it needs to rely on non-portable code to find
the stack bounds.  When Guile does not know how to find these bounds on
your system, it will not provide `scm_init_guile'.

   When you can tolerate the limits of `scm_boot_guile', you should use
it in favor of `scm_init_guile' since that will make your program more
portable.

 -- Functie: void scm_boot_guile (int ARGC, char **ARGV, void
          (*MAIN_FUNC) (), void *CLOSURE)
     Initialize the Guile Scheme interpreter.  Then call MAIN_FUNC,
     passing it CLOSURE, ARGC, and ARGV.  MAIN_FUNC should do all the
     work of the program (initializing other packages, defining
     application-specific functions, reading user input, and so on)
     before returning.  When MAIN_FUNC returns, call `exit (0)';
     `scm_boot_guile' never returns.  If you want some other exit value,
     have MAIN_FUNC call exit itself.

     `scm_boot_guile' arranges for the Scheme `command-line' function
     to return the strings given by ARGC and ARGV.  If MAIN_FUNC
     modifies ARGC or ARGV, it should call `scm_set_program_arguments'
     with the final list, so Scheme code will know which arguments have
     been processed.

     Why must the caller do all the real work from MAIN_FUNC?  Guile's
     garbage collector scans the stack to find all local variables that
     reference Scheme objects.  To do this, it needs to know the bounds
     of the stack that might contain such references.  Because there is
     no portable way in C to find the base of the stack,
     `scm_boot_guile' assumes that all references are above its own
     stack frame.  If you try to manipulate Scheme objects after this
     function returns, it's the luck of the draw whether Guile's
     storage manager will be able to find the objects you allocate.
     So, `scm_boot_guile' function exits, rather than returning, to
     discourage you from making that mistake.

     See `scm_init_guile', below, for a function that can find the real
     base of the stack, but not in a portable way.

 -- Functie: void scm_init_guile ()
     Initialize the Guile Scheme interpreter.

     In contrast to `scm_boot_guile', this function knows how to find
     the true base of the stack and thus does not need to usurp the
     control flow of your program.  However, since finding the stack
     base can not be done portably, this function might not be
     available in all installations of Guile.  If you can, you should
     use `scm_boot_guile' instead.

     Note that `scm_init_guile' does not inform Guile about the command
     line arguments that should be returned by the Scheme function
     `command-line'.  You can use `scm_set_program_arguments' to do
     this.

   One common way to use Guile is to write a set of C functions which
perform some useful task, make them callable from Scheme, and then link
the program with Guile.  This yields a Scheme interpreter just like
`guile', but augmented with extra functions for some specific
application -- a special-purpose scripting language.

   In this situation, the application should probably process its
command-line arguments in the same manner as the stock Guile
interpreter.  To make that straightforward, Guile provides this
function:

 -- Functie: void scm_shell (int ARGC, char **ARGV)
     Process command-line arguments in the manner of the `guile'
     executable.  This includes loading the normal Guile initialization
     files, interacting with the user or running any scripts or
     expressions specified by `-s' or `-e' options, and then exiting.
     *Note Invoking Guile::, for more details.

     Since this function does not return, you must do all
     application-specific initialization before calling this function.


File: guile.info,  Node: A Sample Guile Main Program,  Prev: Guile Initialization Functions,  Up: Linking Programs With Guile

5.3.2 A Sample Guile Main Program
---------------------------------

Here is `simple-guile.c', source code for a `main' and an `inner_main'
function that will produce a complete Guile interpreter.

     /* simple-guile.c --- how to start up the Guile
        interpreter from C code.  */

     /* Get declarations for all the scm_ functions.  */
     #include <libguile.h>

     static void
     inner_main (void *closure, int argc, char **argv)
     {
       /* module initializations would go here */
       scm_shell (argc, argv);
     }

     int
     main (int argc, char **argv)
     {
       scm_boot_guile (argc, argv, inner_main, 0);
       return 0; /* never reached */
     }

   The `main' function calls `scm_boot_guile' to initialize Guile,
passing it `inner_main'.  Once `scm_boot_guile' is ready, it invokes
`inner_main', which calls `scm_shell' to process the command-line
arguments in the usual way.

   Here is a Makefile which you can use to compile the above program.
It uses `guile-config' to learn about the necessary compiler and linker
flags.
     # Use GCC, if you have it installed.
     CC=gcc

     # Tell the C compiler where to find <libguile.h>
     CFLAGS=`guile-config compile`

     # Tell the linker what libraries to use and where to find them.
     LIBS=`guile-config link`

     simple-guile: simple-guile.o
             ${CC} simple-guile.o ${LIBS} -o simple-guile

     simple-guile.o: simple-guile.c
             ${CC} -c ${CFLAGS} simple-guile.c

   If you are using the GNU Autoconf package to make your application
more portable, Autoconf will settle many of the details in the Makefile
above automatically, making it much simpler and more portable; we
recommend using Autoconf with Guile.  Guile also provides the
`GUILE_FLAGS' macro for autoconf that performs all necessary checks.
Here is a `configure.in' file for `simple-guile' that uses this macro.
Autoconf can use as this file as template to generate a `configure'
script.  In order for Autoconf to find the `GUILE_FLAGS' macro, you
will need to run `aclocal' first.  This is not really Guile specific,
so you should refer to the Autoconf documentation REFFIXME when in
doubt.
     AC_INIT(simple-guile.c)

     # Find a C compiler.
     AC_PROG_CC

     # Check for Guile
     GUILE_FLAGS

     # Generate a Makefile, based on the results.
     AC_OUTPUT(Makefile)

   Here is a `Makefile.in' template, from which the `configure' script
produces a Makefile customized for the host system:
     # The configure script fills in these values.
     CC=@CC@
     CFLAGS=@GUILE_CFLAGS@
     LIBS=@GUILE_LDFLAGS@

     simple-guile: simple-guile.o
             ${CC} simple-guile.o ${LIBS} -o simple-guile
     simple-guile.o: simple-guile.c
             ${CC} -c ${CFLAGS} simple-guile.c

   The developer should use Autoconf to generate the `configure' script
from the `configure.in' template, and distribute `configure' with the
application.  Here's how a user might go about building the application:

     $ ls
     Makefile.in     configure*      configure.in    simple-guile.c
     $ ./configure
     creating cache ./config.cache
     checking for gcc... (cached) gcc
     checking whether the C compiler (gcc  ) works... yes
     checking whether the C compiler (gcc  ) is a cross-compiler... no
     checking whether we are using GNU C... (cached) yes
     checking whether gcc accepts -g... (cached) yes
     checking for Guile... yes
     creating ./config.status
     creating Makefile
     $ make
     gcc -c -I/usr/local/include simple-guile.c
     gcc simple-guile.o -L/usr/local/lib -lguile -lqthreads -lpthread -lm -o simple-guile
     $ ./simple-guile
     guile> (+ 1 2 3)
     6
     guile> (getpwnam "jimb")
     #("jimb" "83Z7d75W2tyJQ" 4008 10 "Jim Blandy" "/u/jimb"
       "/usr/local/bin/bash")
     guile> (exit)
     $


File: guile.info,  Node: Writing Extensions for Guile,  Next: Guile Modules,  Prev: Linking Programs With Guile,  Up: Whirlwind Tour

5.4 Writing Extensions for Guile
================================

The previous sections have briefly explained how to write programs that
make use of an embedded Guile interpreter.  But sometimes, all you want
to do is make new primitive procedures and data types available to the
Scheme programmer.  Writing a new version of `guile' is inconvenient in
this case and it would in fact make the life of the users of your new
features needlessly hard.

   For example, suppose that there is a program `guile-db' that is a
version of Guile with additional features for accessing a database.
People who want to write Scheme programs that use these features would
have to use `guile-db' instead of the usual `guile' program.  Now
suppose that there is also a program `guile-gtk' that extends Guile
with access to the popular Gtk+ toolkit for graphical user interfaces.
People who want to write GUIs in Scheme would have to use `guile-gtk'.
Now, what happens when you want to write a Scheme application that uses
a GUI to let the user access a database?  You would have to write a
_third_ program that incorporates both the database stuff and the GUI
stuff.  This might not be easy (because `guile-gtk' might be a quite
obscure program, say) and taking this example further makes it easy to
see that this approach can not work in practice.

   It would have been much better if both the database features and the
GUI feature had been provided as libraries that can just be linked with
`guile'.  Guile makes it easy to do just this, and we encourage you to
make your extensions to Guile available as libraries whenever possible.

   You write the new primitive procedures and data types in the normal
fashion, and link them into a shared library instead of into a
stand-alone program.  The shared library can then be loaded dynamically
by Guile.

* Menu:

* A Sample Guile Extension::


File: guile.info,  Node: A Sample Guile Extension,  Up: Writing Extensions for Guile

5.4.1 A Sample Guile Extension
------------------------------

This section explains how to make the Bessel functions of the C library
available to Scheme.  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.

   Consider the following file `bessel.c'.

     #include <math.h>
     #include <libguile.h>

     SCM
     j0_wrapper (SCM x)
     {
       return scm_make_real (j0 (scm_num2dbl (x, "j0")));
     }

     void
     init_bessel ()
     {
       scm_c_define_gsubr ("j0", 1, 0, 0, j0_wrapper);
     }

   This C source file needs to be compiled into a shared library.  Here
is how to do it on GNU/Linux:

     gcc -shared -o libguile-bessel.so -fPIC bessel.c

   For creating shared libraries portably, we recommend the use of `GNU
Libtool'.

   A shared library can be loaded into a running Guile process with the
function `load-extension'.  In addition to the name of the library to
load, this function also expects the name of function from that library
that will be called to initialize it.  For our example, we are going to
call the function `init_bessel' which will make `j0_wrapper' available
to Scheme programs with the name `j0'.  Note that we do not specify a
filename extension such as `.so' when invoking `load-extension'.  The
right extension for the host platform will be provided automatically.

     (load-extension "libguile-bessel" "init_bessel")
     (j0 2)
     => 0.223890779141236

   For this to work, `load-extension' must be able to find
`libguile-bessel', of course.  It will look in the places that are
usual for your operating system, and it will additionally look into the
directories listed in the `LTDL_LIBRARY_PATH' environment variable.

   To see how these Guile extensions via shared libraries relate to the
module system, see below *Note Intro to Modules and Extensions::.


File: guile.info,  Node: Guile Modules,  Prev: Writing Extensions for Guile,  Up: Whirlwind Tour

5.5 Guile Modules
=================

Guile has support for dividing a program into "modules".  By using
modules, you can group related code together and manage the composition
of complete programs from largely independent parts.

   (Although the module system implementation is in flux, feel free to
use it anyway.  Guile will provide reasonable backwards compatibility.)

   Details on the module system beyond this introductory material can
be found in *Note Modules::.

* Menu:

* Intro to Using Guile Modules::
* Intro to Writing New Modules::
* Intro to Modules and Extensions::


File: guile.info,  Node: Intro to Using Guile Modules,  Next: Intro to Writing New Modules,  Up: Guile Modules

5.5.1 Intro to Using Existing Modules
-------------------------------------

Guile comes with a lot of useful modules, for example for string
processing or command line parsing.  Additionally, there exist many
Guile modules written by other Guile hackers, but which have to be
installed manually.

   Existing modules have to be placed in places where Guile looks for
them by default or in colon-separated directories in the environment
variable `GUILE_LOAD_PATH'.  When this variable is set, those
directories are searched first, then the the default.  The following
command shows the complete list of directories searched:

     guile -c '(write %load-path) (newline)'

   Suppose you want to use the procedures and variables exported by the
module `(ice-9 popen)', which provides the means for communicating with
other processes over pipes.  Add the following line to your currently
running Guile REPL or the top of your script file.

     (use-modules (ice-9 popen))

   This will load the module and make the procedures exported by
`(ice-9 popen)' automatically available.  The next step could be to
open a pipe to `ls' and read the contents of the current directory, one
line at a time.

     (define p (open-input-pipe "ls -l"))
     (read-line p)
     =>
     "total 30"
     (read-line p)
     =>
     "drwxr-sr-x    2 mgrabmue mgrabmue     1024 Mar 29 19:57 CVS"


File: guile.info,  Node: Intro to Writing New Modules,  Next: Intro to Modules and Extensions,  Prev: Intro to Using Guile Modules,  Up: Guile Modules

5.5.2 Intro to Writing New Modules
----------------------------------

Of course it is possible to write modules yourself.  Using modules for
structuring your programs makes them more readable and lets you
distribute them more easily.  Also, explicitly defining the procedures
and variables which are exported from a module adds documentation to the
source and specifies the interface a module provides.

   In Guile, you can create new modules and switch to existing modules
in order to add bindings to them using the syntactic form
`define-module'.

     (define-module (foo bar))

     (define (frob x) x)

   Will create the module `(foo bar)'.(1) All definitions following
this statement will add bindings to the module `(foo bar)', and these
bindings will not be visible outside of the module.  To make the
bindings accessible to other modules, you have to export them
explicitly using one of the following means:

   * Export them with the `export' form:
          (export frob)

   * Include them into the `define-module' form with the keyword
     `export':
          (define-module (foo bar)
            #:export (frob))

   * Change the definition of `frob' to use `define-public', which is a
     combination of `define' and `export'.
          (define-public (frob x) x)

   After exporting, other modules can access the exported items simply
by using `use-modules' to load the module `(foo bar)'.

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

   (1) It is only convention that the module names in this section have
two elements.  One or more than two elements are perfectly fine, such
as `(foo)' or `(foo bar braz)'


File: guile.info,  Node: Intro to Modules and Extensions,  Prev: Intro to Writing New Modules,  Up: Guile Modules

5.5.3 Intro to Modules and Extensions
-------------------------------------

In addition to Scheme code you can also put things that are defined in
C into a module.

   You do this by writing a small Scheme file that defines the module.
That Scheme file in turn invokes `load-extension' to make the features
defined in C available.  This works since all definitions made by
`scm_c_define_gsubr' etc. go into the _current module_ and
`define-module' causes the newly defined module to be current while the
code that follows it is executed.

   Suppose we want to put the Bessel function `j0' from the example
extension into a module called `(math bessel)'.  We would have to write
a Scheme file with this contents

     (define-module (math bessel))

     (export j0)

     (load-extension "libguile-bessel" "init_bessel")

   This file should of course be saved in the right place for
autoloading, for example as `/usr/local/share/guile/math/bessel.scm'.

   When `init_bessel' is called, the new `(math bessel)' module is the
current one.  Thus, the call to `scm_c_define_gsubr' will put the new
definition for `j0' into it, just as we want it.

   The definitions made in the C code are not automatically exported
from a module.  You need to explicitly list the ones you want to export
in `export' statements or with the `:export' option of `define-module'.

   There is also a way to manipulate the module system from C but only
Scheme files can be autoloaded.  Thus, we recommend that you define
your modules in Scheme.


File: guile.info,  Node: Obtaining and Installing Guile,  Next: Reporting Bugs,  Prev: Whirlwind Tour,  Up: Top

6 Obtaining and Installing Guile
********************************

Here is the information you will need to get and install Guile and extra
packages and documentation you might need or find interesting.

* Menu:

* The Basic Guile Package::
* Packages not shipped with Guile::


File: guile.info,  Node: The Basic Guile Package,  Next: Packages not shipped with Guile,  Up: Obtaining and Installing Guile

6.1 The Basic Guile Package
===========================

Guile can be obtained from the main GNU archive site
`ftp://ftp.gnu.org' or any of its mirrors.  The file will be named
guile-version.tar.gz.  The current version is 1.6.5, so the file you
should grab is:

   `ftp://ftp.gnu.org/pub/gnu/guile-1.6.5.tar.gz'

   To unbundle Guile use the instruction

     zcat guile-1.6.5.tar.gz | tar xvf -

   which will create a directory called `guile-1.6.5' with all the
sources.  You can look at the file `INSTALL' for detailed instructions
on how to build and install Guile, but you should be able to just do

     cd guile-1.6.5
     ./configure
     make
     make install

   This will install the Guile executable `guile', the Guile library
`-lguile' and various associated header files and support libraries. It
will also install the Guile tutorial and reference manual.

   Since this manual frequently refers to the Scheme "standard", also
known as R5RS, or the "Revised^5 Report on the Algorithmic Language
Scheme", we have included the report in the Guile distribution; *Note
Introduction: (r5rs)Top.  This will also be installed in your info
directory.


File: guile.info,  Node: Packages not shipped with Guile,  Prev: The Basic Guile Package,  Up: Obtaining and Installing Guile

6.2 Packages not shipped with Guile
===================================

We ship the Guile tutorial and reference manual with the Guile
distribution.  Since the Scheme standard (R5RS) is a stable document, we
ship that too.

   Here are references (usually World Wide Web URLs) to some other
freely redistributable documents and packages which you might find
useful if you are using Guile.

*SCSH*
     the Scheme Shell.  Gary Houston has ported SCSH to Guile.  The
     relevant chapter (*note The Scheme shell (scsh)::) has references
     to the SCSH web page with all its documentation.

*SLIB*
     a portable Scheme library maintained by Aubrey Jaffer.  SLIB can be
     obtained by ftp from `ftp://prep.ai.mit.edu/pub/gnu/jacal/'.

     The SLIB package should be unpacked somewhere in Guile's load
     path.  It will typically be unpacked in
     `/usr/local/share/guile/site', so that it will be
     `/usr/local/share/guile/site/slib'.

     Guile might have been installed with a different prefix, in which
     case the load path can be checked from inside the interpreter with:

          guile> %load-path
          ("/usr/local/share/guile/site" "/usr/local/share/guile/1.3a" "/usr/local/share/guile" ".")

     The relevant chapter (*note SLIB::) has details on how to use SLIB
     with Guile.

*JACAL*
     a symbolic math package by Aubrey Jaffer.  The latest version of
     Jacal can be obtained from `ftp://prep.ai.mit.edu/pub/gnu/jacal/',
     and should be unpacked in `/usr/local/share/guile/site/slib' so
     that it will be in `/usr/local/share/guile/site/slib/jacal'.

     The relevant section (*note JACAL::) has details on how to use
     Jacal.


File: guile.info,  Node: Reporting Bugs,  Next: Running Intro,  Prev: Obtaining and Installing Guile,  Up: Top

7 Reporting Bugs
****************

Any problems with the installation should be reported to
<bug-guile@gnu.org>.

   Whenever you have found a bug in Guile you are encouraged to report
it to the Guile developers, so they can fix it.  They may also be able
to suggest workarounds when it is not possible for you to apply the
bug-fix or install a new version of Guile yourself.

   Before sending in bug reports, please check with the following list
that you really have found a bug.

   * Whenever documentation and actual behavior differ, you have
     certainly found a bug, either in the documentation or in the
     program.

   * When Guile crashes, it is a bug.

   * When Guile hangs or takes forever to complete a task, it is a bug.

   * When calculations produce wrong results, it is a bug.

   * When Guile signals an error for valid Scheme programs, it is a bug.

   * When Guile does not signal an error for invalid Scheme programs,
     it may be a bug, unless this is explicitly documented.

   * When some part of the documentation is not clear and does not make
     sense to you even after re-reading the section, it is a bug.

   When you write a bug report, please make sure to include as much of
the information described below in the report.  If you can't figure out
some of the items, it is not a problem, but the more information we
get, the more likely we can diagnose and fix the bug.

   * The version number of Guile.  Without this, we won't know whether
     there is any point in looking for the bug in the current version
     of Guile.

     You can get the version number by invoking the command

          $ guile --version
          Guile 1.4.1
          Copyright (c) 1995, 1996, 1997, 2000 Free Software Foundation
          Guile may be distributed under the terms of the GNU General Public License;
          certain other uses are permitted as well.  For details, see the file
          `COPYING', which is included in the Guile distribution.
          There is no warranty, to the extent permitted by law.

   * The type of machine you are using, and the operating system name
     and version number.  On GNU systems, you can get it with `uname'.

          $ uname -a
          Linux tortoise 2.2.17 #1 Thu Dec 21 17:29:05 CET 2000 i586 unknown

   * The operands given to the `configure' command when Guile was
     installed.  It's often useful to augment this with the output of
     the command `guile-config info'.

   * A complete list of any modifications you have made to the Guile
     source.  (We may not have time to investigate the bug unless it
     happens in an unmodified Guile.  But if you've made modifications
     and you don't tell us, you are sending us on a wild goose chase.)

     Be precise about these changes.  A description in English is not
     enough--send a context diff for them.

     Adding files of your own, or porting to another machine, is a
     modification of the source.

   * Details of any other deviations from the standard procedure for
     installing Guile.

   * The complete text of any source files needed to reproduce the bug.

     If you can tell us a way to cause the problem without loading any
     source files, please do so.  This makes it much easier to debug.
     If you do need files, make sure you arrange for us to see their
     exact contents.

   * The precise Guile invocation command line we need to type to
     reproduce the bug.

   * A description of what behavior you observe that you believe is
     incorrect.  For example, "The Guile process gets a fatal signal,"
     or, "The resulting output is as follows, which I think is wrong."

     Of course, if the bug is that Guile gets a fatal signal, then one
     can't miss it.  But if the bug is incorrect results, the
     maintainer might fail to notice what is wrong.  Why leave it to
     chance?

     If the manifestation of the bug is a Guile error message, it is
     important to report the precise text of the error message, and a
     backtrace showing how the Scheme program arrived at the error.

     This can be done using the procedure `backtrace' in the REPL.

   * Check whether any programs you have loaded into Guile, including
     your `.guile' file, set any variables that may affect the
     functioning of Guile.  Also, see whether the problem happens in a
     freshly started Guile without loading your `.guile' file (start
     Guile with the `-q' switch to prevent loading the init file).  If
     the problem does _not_ occur then, you must report the precise
     contents of any programs that you must load into Guile in order to
     cause the problem to occur.

   * If the problem does depend on an init file or other Scheme
     programs that are not part of the standard Guile distribution,
     then you should make sure it is not a bug in those programs by
     complaining to their maintainers first.  After they verify that
     they are using Guile in a way that is supposed to work, they
     should report the bug.

   * If you wish to mention something in the Guile source, show the
     line of code with a few lines of context.  Don't just give a line
     number.

     The line numbers in the development sources might not match those
     in your sources.  It would take extra work for the maintainers to
     determine what code is in your version at a given line number, and
     we could not be certain.

   * Additional information from a C debugger such as GDB might enable
     someone to find a problem on a machine which he does not have
     available.  If you don't know how to use GDB, please read the GDB
     manual--it is not very long, and using GDB is easy.  You can find
     the GDB distribution, including the GDB manual in online form, in
     most of the same places you can find the Guile distribution.  To
     run Guile under GDB, you should switch to the `libguile'
     subdirectory in which Guile was compiled, then do `gdb guile' or
     `gdb .libs/guile' (if using GNU Libtool).

     However, you need to think when you collect the additional
     information if you want it to show what causes the bug.

     For example, many people send just a backtrace, but that is not
     very useful by itself.  A simple backtrace with arguments often
     conveys little about what is happening inside Guile, because most
     of the arguments listed in the backtrace are pointers to Scheme
     objects.  The numeric values of these pointers have no
     significance whatever; all that matters is the contents of the
     objects they point to (and most of the contents are themselves
     pointers).


File: guile.info,  Node: Running Intro,  Next: Guile Scheme,  Prev: Reporting Bugs,  Up: Top

Part II: Writing and Running Guile Scheme
*****************************************

Guile's core language is Scheme, and an awful lot can be achieved simply
by using Guile to write and run Scheme programs.  In this part of the
manual, we explain how to use Guile in this mode, and describe the tools
that Guile provides to help you with script writing, debugging and
packaging your programs for distribution.

   For readers who are not yet familiar with the Scheme language, this
part includes a chapter that presents the basic concepts of the
language, and gives references to freely available Scheme tutorial
material on the web.

   For detailed reference information on the variables, functions etc.
that make up Guile's application programming interface (API), please
refer to Part IV (*note Part IV -- Guile API Reference: Reference
Intro.).


File: guile.info,  Node: Guile Scheme,  Next: Guile Scripting,  Prev: Running Intro,  Up: Top

8 Guile's Implementation of Scheme
**********************************

Guile's core language is Scheme, which is specified and described in the
series of reports known as "RnRS".  "RnRS" is shorthand for the
"Revised^n Report on the Algorithmic Language Scheme".  The current
latest revision of RnRS is version 5 (*note R5RS: (r5rs)Top.), and
Guile 1.4 is fully compliant with the Scheme specification in this
revision.

   But Guile, like most Scheme implementations, also goes beyond R5RS in
many ways, because R5RS does not give specifications (or even
recommendations) regarding many issues that are important in practical
programming.  Some of the areas where Guile extends R5RS are:

   * Guile's interactive documentation system

   * Guile's support for POSIX-compliant network programming

   * GOOPS - Guile's framework for object oriented programming.


File: guile.info,  Node: Guile Scripting,  Next: Command Line Handling,  Prev: Guile Scheme,  Up: Top

9 Guile Scripting
*****************

Like AWK, Perl, or any shell, Guile can interpret script files.  A Guile
script is simply a file of Scheme code with some extra information at
the beginning which tells the operating system how to invoke Guile, and
then tells Guile how to handle the Scheme code.

* Menu:

* Invoking Guile::              How to start a Guile script.
* The Meta Switch::             Passing complex argument lists to Guile
                                from shell scripts.


File: guile.info,  Node: Invoking Guile,  Next: The Meta Switch,  Up: Guile Scripting

9.1 Invoking Guile
==================

Here we describe Guile's command-line processing in detail.  Guile
processes its arguments from left to right, recognizing the switches
described below.  For examples, see *Note Scripting Examples::.

`-s SCRIPT ARG...'
     Read and evaluate Scheme source code from the file SCRIPT, as the
     `load' function would.  After loading SCRIPT, exit.  Any
     command-line arguments ARG... following SCRIPT become the script's
     arguments; the `command-line' function returns a list of strings
     of the form `(SCRIPT ARG...)'.

`-c EXPR ARG...'
     Evaluate EXPR as Scheme code, and then exit.  Any command-line
     arguments ARG... following EXPR become command-line arguments; the
     `command-line' function returns a list of strings of the form
     `(GUILE ARG...)', where GUILE is the path of the Guile executable.

`-- ARG...'
     Run interactively, prompting the user for expressions and
     evaluating them.  Any command-line arguments ARG... following the
     `--' become command-line arguments for the interactive session; the
     `command-line' function returns a list of strings of the form
     `(GUILE ARG...)', where GUILE is the path of the Guile executable.

`-l FILE'
     Load Scheme source code from FILE, and continue processing the
     command line.

`-e FUNCTION'
     Make FUNCTION the "entry point" of the script.  After loading the
     script file (with `-s') or evaluating the expression (with `-c'),
     apply FUNCTION to a list containing the program name and the
     command-line arguments -- the list provided by the `command-line'
     function.

     A `-e' switch can appear anywhere in the argument list, but Guile
     always invokes the FUNCTION as the _last_ action it performs.
     This is weird, but because of the way script invocation works under
     POSIX, the `-s' option must always come last in the list.

     *Note Scripting Examples::.

`-ds'
     Treat a final `-s' option as if it occurred at this point in the
     command line; load the script here.

     This switch is necessary because, although the POSIX script
     invocation mechanism effectively requires the `-s' option to
     appear last, the programmer may well want to run the script before
     other actions requested on the command line.  For examples, see
     *Note Scripting Examples::.

`\'
     Read more command-line arguments, starting from the second line of
     the script file.  *Note The Meta Switch::.

`--emacs'
     Assume Guile is running as an inferior process of Emacs, and use a
     special protocol to communicate with Emacs's Guile interaction
     mode.  This switch sets the global variable use-emacs-interface to
     `#t'.

     This switch is still experimental.

`--use-srfi=LIST'
     The option `--use-srfi' expects a comma-separated list of numbers,
     each representing a SRFI number to be loaded into the interpreter
     before starting evaluating a script file or the REPL.
     Additionally, the feature identifier for the loaded SRFIs is
     recognized by `cond-expand' when using this option.

          guile --use-srfi=8,13

`--debug'
     Start with the debugging evaluator and enable backtraces.  Using
     the debugging evaluator will give you better error messages but it
     will slow down execution.  By default, the debugging evaluator is
     only used when entering an interactive session.  When executing a
     script with `-s' or `-c', the normal, faster evaluator is used by
     default.

`-h, --help'
     Display help on invoking Guile, and then exit.

`-v, --version'
     Display the current version of Guile, and then exit.



File: guile.info,  Node: The Meta Switch,  Prev: Invoking Guile,  Up: Guile Scripting

9.2 The Meta Switch
===================

Guile's command-line switches allow the programmer to describe
reasonably complicated actions in scripts.  Unfortunately, the POSIX
script invocation mechanism only allows one argument to appear on the
`#!' line after the path to the Guile executable, and imposes arbitrary
limits on that argument's length.  Suppose you wrote a script starting
like this:
     #!/usr/local/bin/guile -e main -s
     !#
     (define (main args)
       (map (lambda (arg) (display arg) (display " "))
            (cdr args))
       (newline))
   The intended meaning is clear: load the file, and then call `main'
on the command-line arguments.  However, the system will treat
everything after the Guile path as a single argument -- the string `"-e
main -s"' -- which is not what we want.

   As a workaround, the meta switch `\' allows the Guile programmer to
specify an arbitrary number of options without patching the kernel.  If
the first argument to Guile is `\', Guile will open the script file
whose name follows the `\', parse arguments starting from the file's
second line (according to rules described below), and substitute them
for the `\' switch.

   Working in concert with the meta switch, Guile treats the characters
`#!' as the beginning of a comment which extends through the next line
containing only the characters `!#'.  This sort of comment may appear
anywhere in a Guile program, but it is most useful at the top of a
file, meshing magically with the POSIX script invocation mechanism.

   Thus, consider a script named `/u/jimb/ekko' which starts like this:
     #!/usr/local/bin/guile \
     -e main -s
     !#
     (define (main args)
             (map (lambda (arg) (display arg) (display " "))
                  (cdr args))
             (newline))

   Suppose a user invokes this script as follows:
     $ /u/jimb/ekko a b c

   Here's what happens:
   * the operating system recognizes the `#!' token at the top of the
     file, and rewrites the command line to:
          /usr/local/bin/guile \ /u/jimb/ekko a b c
     This is the usual behavior, prescribed by POSIX.

   * When Guile sees the first two arguments, `\ /u/jimb/ekko', it opens
     `/u/jimb/ekko', parses the three arguments `-e', `main', and `-s'
     from it, and substitutes them for the `\' switch.  Thus, Guile's
     command line now reads:
          /usr/local/bin/guile -e main -s /u/jimb/ekko a b c

   * Guile then processes these switches: it loads `/u/jimb/ekko' as a
     file of Scheme code (treating the first three lines as a comment),
     and then performs the application `(main "/u/jimb/ekko" "a" "b"
     "c")'.


   When Guile sees the meta switch `\', it parses command-line argument
from the script file according to the following rules:
   * Each space character terminates an argument.  This means that two
     spaces in a row introduce an argument `""'.

   * The tab character is not permitted (unless you quote it with the
     backslash character, as described below), to avoid confusion.

   * The newline character terminates the sequence of arguments, and
     will also terminate a final non-empty argument.  (However, a
     newline following a space will not introduce a final empty-string
     argument; it only terminates the argument list.)

   * The backslash character is the escape character.  It escapes
     backslash, space, tab, and newline.  The ANSI C escape sequences
     like `\n' and `\t' are also supported.  These produce argument
     constituents; the two-character combination `\n' doesn't act like
     a terminating newline.  The escape sequence `\NNN' for exactly
     three octal digits reads as the character whose ASCII code is NNN.
     As above, characters produced this way are argument constituents.
     Backslash followed by other characters is not allowed.



File: guile.info,  Node: Command Line Handling,  Next: Debugging Features,  Prev: Guile Scripting,  Up: Top

10 Handling Command Line Options and Arguments
**********************************************

The ability to accept and handle command line arguments is very
important when writing Guile scripts to solve particular problems, such
as extracting information from text files or interfacing with existing
command line applications.  This chapter describes how Guile makes
command line arguments available to a Guile script, and the utilities
that Guile provides to help with the processing of command line
arguments.

* Menu:

* Command Line Args::           Using command line arguments.
* getopt-long::                 The (ice-9 getopt-long) module.


File: guile.info,  Node: Command Line Args,  Next: getopt-long,  Up: Command Line Handling

10.1 Using Command Line Arguments
=================================

When a Guile script is invoked, Guile makes the command line arguments
accessible via the procedure `command-line', which returns the
arguments as a list of strings.

   For example, if the script

     #! /usr/local/bin/guile -s
     !#
     (write (command-line))
     (newline)

is saved in a file `cmdline-test.scm' and invoked using the command
line `./cmdline-test.scm bar.txt -o foo -frumple grob', the output is

     ("./cmdline-test.scm" "bar.txt" "-o" "foo" "-frumple" "grob")

   If the script invocation includes a `-e' option, specifying a
procedure to call after loading the script, Guile will call that
procedure with `(command-line)' as its argument.  So a script that uses
`-e' doesn't need to refer explicitly to `command-line' in its code.
For example, the script above would have identical behaviour if it was
written instead like this:

     #! /usr/local/bin/guile \
     -e main -s
     !#
     (define (main args)
       (write args)
       (newline))

   (Note the use of the meta switch `\' so that the script invocation
can include more than one Guile option: *Note The Meta Switch::.)

   These scripts use the `#!' POSIX convention so that they can be
executed using their own file names directly, as in the example command
line `./cmdline-test.scm bar.txt -o foo -frumple grob'.  But they can
also be executed by typing out the implied Guile command line in full,
as in:

     $ guile -s ./cmdline-test.scm bar.txt -o foo -frumple grob

or

     $ guile -e main -s ./cmdline-test2.scm bar.txt -o foo -frumple grob

   Even when a script is invoked using this longer form, the arguments
that the script receives are the same as if it had been invoked using
the short form.  Guile ensures that the `(command-line)' or `-e'
arguments are independent of how the script is invoked, by stripping off
the arguments that Guile itself processes.


File: guile.info,  Node: getopt-long,  Prev: Command Line Args,  Up: Command Line Handling

10.2 The (ice-9 getopt-long) Module
===================================

A script is free to parse and handle its command line arguments in any
way that it chooses.  Where the set of possible options and arguments is
complex, however, it can get tricky to extract all the options, check
the validity of given arguments, and so on.  This task can be greatly
simplified by taking advantage of the module `(ice-9 getopt-long)',
which is distributed with Guile.

   The `(ice-9 getopt-long)' module exports two procedures:
`getopt-long' and `option-ref'.

   * `getopt-long' takes a list of strings -- the command line
     arguments -- and an "option specification".  It parses the command
     line arguments according to the option specification and returns a
     data structure that encapsulates the results of the parsing.

   * `option-ref' then takes the parsed data structure and a specific
     option's name, and returns information about that option in
     particular.

   To make these procedures available to your Guile script, include the
expression `(use-modules (ice-9 getopt-long))' somewhere near the top,
before the first usage of `getopt-long' or `option-ref'.

* Menu:

* getopt-long Example::         A short getopt-long example.
* Option Specification::        How to write an option specification.
* Command Line Format::         The expected command line format.
* getopt-long Reference::       Full documentation for `getopt-long'.
* option-ref Reference::        Full documentation for `option-ref'.


File: guile.info,  Node: getopt-long Example,  Next: Option Specification,  Up: getopt-long

10.2.1 A Short getopt-long Example
----------------------------------

This subsection illustrates how `getopt-long' is used by presenting and
dissecting a simple example.  The first thing that we need is an
"option specification" that tells `getopt-long' how to parse the
command line.  This specification is an association list with the long
option name as the key.  Here is how such a specification might look:

     (define option-spec
       '((version (single-char #\v) (value #f))
         (help    (single-char #\h) (value #f))))

   This alist tells `getopt-long' that it should accept two long
options, called _version_ and _help_, and that these options can also
be selected by the single-letter abbreviations _v_ and _h_,
respectively.  The `(value #f)' clauses indicate that neither of the
options accepts a value.

   With this specification we can use `getopt-long' to parse a given
command line:

     (define options (getopt-long (command-line) option-spec))

   After this call, `options' contains the parsed command line and is
ready to be examined by `option-ref'.  `option-ref' is called like this:

     (option-ref options 'help #f)

It expects the parsed command line, a symbol indicating the option to
examine, and a default value.  The default value is returned if the
option was not present in the command line, or if the option was present
but without a value; otherwise the value from the command line is
returned.  Usually `option-ref' is called once for each possible option
that a script supports.

   The following example shows a main program which puts all this
together to parse its command line and figure out what the user wanted.

     (define (main args)
       (let* ((option-spec '((version (single-char #\v) (value #f))
                             (help    (single-char #\h) (value #f))))
              (options (getopt-long args option-spec))
              (help-wanted (option-ref options 'help #f))
              (version-wanted (option-ref options 'version #f)))
         (if (or version-wanted help-wanted)
             (begin
               (if version-wanted
                   (display "getopt-long-example version 0.3\n"))
               (if help-wanted
                   (display "\
     getopt-long-example [options]
       -v, --version    Display version
       -h, --help       Display this help
     ")))
             (begin
               (display "Hello, World!") (newline)))))


File: guile.info,  Node: Option Specification,  Next: Command Line Format,  Prev: getopt-long Example,  Up: getopt-long

10.2.2 How to Write an Option Specification
-------------------------------------------

An option specification is an association list (*note Association
Lists::) with one list element for each supported option. The key of
each list element is a symbol that names the option, while the value is
a list of option properties:

     OPTION-SPEC ::=  '( (OPT-NAME1 (PROP-NAME PROP-VALUE) ...)
                         (OPT-NAME2 (PROP-NAME PROP-VALUE) ...)
                         (OPT-NAME3 (PROP-NAME PROP-VALUE) ...)
                         ...
                       )

   Each OPT-NAME specifies the long option name for that option.  For
example, a list element with OPT-NAME `background' specifies an option
that can be specified on the command line using the long option
`--background'.  Further information about the option -- whether it
takes a value, whether it is required to be present in the command
line, and so on -- is specified by the option properties.

   In the example of the preceding subsection, we already saw that a
long option name can have a equivalent "short option" character.  The
equivalent short option character can be set for an option by specifying
a `single-char' property in that option's property list.  For example,
a list element like `'(output (single-char #\o) ...)' specifies an
option with long name `--output' that can also be specified by the
equivalent short name `-o'.

   The `value' property specifies whether an option requires or accepts
a value.  If the `value' property is set to `#t', the option requires a
value: `getopt-long' will signal an error if the option name is present
without a corresponding value.  If set to `#f', the option does not
take a value; in this case, a non-option word that follows the option
name in the command line will be treated as a non-option argument.  If
set to the symbol `optional', the option accepts a value but does not
require one: a non-option word that follows the option name in the
command line will be interpreted as that option's value.  If the option
name for an option with `'(value optional)' is immediately followed in
the command line by _another_ option name, the value for the first
option is implicitly `#t'.

   The `required?' property indicates whether an option is required to
be present in the command line.  If the `required?'  property is set to
`#t', `getopt-long' will signal an error if the option is not specified.

   Finally, the `predicate' property can be used to constrain the
possible values of an option.  If used, the `predicate' property should
be set to a procedure that takes one argument -- the proposed option
value as a string -- and returns either `#t' or `#f' according as the
proposed value is or is not acceptable.  If the predicate procedure
returns `#f', `getopt-long' will signal an error.

   By default, options do not have single-character equivalents, are not
required, and do not take values.  Where the list element for an option
includes a `value' property but no `predicate' property, the option
values are unconstrained.


File: guile.info,  Node: Command Line Format,  Next: getopt-long Reference,  Prev: Option Specification,  Up: getopt-long

10.2.3 Expected Command Line Format
-----------------------------------

In order for `getopt-long' to correctly parse a command line, that
command line must conform to a standard set of rules for how command
line options are specified.  This subsection explains what those rules
are.

   `getopt-long' splits a given command line into several pieces.  All
elements of the argument list are classified to be either options or
normal arguments.  Options consist of two dashes and an option name
(so-called "long" options), or of one dash followed by a single letter
("short" options).

   Options can behave as switches, when they are given without a value,
or they can be used to pass a value to the program.  The value for an
option may be specified using an equals sign, or else is simply the next
word in the command line, so the following two invocations are
equivalent:

     $ ./foo.scm --output=bar.txt
     $ ./foo.scm --output bar.txt

   Short options can be used instead of their long equivalents and can
be grouped together after a single dash.  For example, the following
commands are equivalent.

     $ ./foo.scm --version --help
     $ ./foo.scm -v --help
     $ ./foo.scm -vh

   If an option requires a value, it can only be grouped together with
other short options if it is the last option in the group; the value is
the next argument.  So, for example, with the following option
specification --

     ((apples    (single-char #\a))
      (blimps    (single-char #\b) (value #t))
      (catalexis (single-char #\c) (value #t)))

-- the following command lines would all be acceptable:

     $ ./foo.scm -a -b bang -c couth
     $ ./foo.scm -ab bang -c couth
     $ ./foo.scm -ac couth -b bang

   But the next command line is an error, because `-b' is not the last
option in its combination, and because a group of short options cannot
include two options that both require values:

     $ ./foo.scm -abc couth bang

   If an option's value is optional, `getopt-long' decides whether the
option has a value by looking at what follows it in the argument list.
If the next element is a string, and it does not appear to be an option
itself, then that string is the option's value.

   If the option `--' appears in the argument list, argument parsing
stops there and subsequent arguments are returned as ordinary arguments,
even if they resemble options.  So, with the command line

     $ ./foo.scm --apples "Granny Smith" -- --blimp Goodyear

`getopt-long' will recognize the `--apples' option as having the value
"Granny Smith", but will not treat `--blimp' as an option.  The strings
`--blimp' and `Goodyear' will be returned as ordinary argument strings.


File: guile.info,  Node: getopt-long Reference,  Next: option-ref Reference,  Prev: Command Line Format,  Up: getopt-long

10.2.4 Reference Documentation for `getopt-long'
------------------------------------------------

 -- Scheme Procedure: getopt-long args grammar
     Parse the command line given in ARGS (which must be a list of
     strings) according to the option specification GRAMMAR.

     The GRAMMAR argument is expected to be a list of this form:

     `((OPTION (PROPERTY VALUE) ...) ...)'

     where each OPTION is a symbol denoting the long option, but
     without the two leading dashes (e.g. `version' if the option is
     called `--version').

     For each option, there may be list of arbitrarily many
     property/value pairs.  The order of the pairs is not important,
     but every property may only appear once in the property list.  The
     following table lists the possible properties:

    `(single-char CHAR)'
          Accept `-CHAR' as a single-character equivalent to
          `--OPTION'.  This is how to specify traditional Unix-style
          flags.

    `(required? BOOL)'
          If BOOL is true, the option is required.  `getopt-long' will
          raise an error if it is not found in ARGS.

    `(value BOOL)'
          If BOOL is `#t', the option accepts a value; if it is `#f',
          it does not; and if it is the symbol `optional', the option
          may appear in ARGS with or without a value.

    `(predicate FUNC)'
          If the option accepts a value (i.e. you specified `(value
          #t)' for this option), then `getopt-long' will apply FUNC to
          the value, and throw an exception if it returns `#f'.  FUNC
          should be a procedure which accepts a string and returns a
          boolean value; you may need to use quasiquotes to get it into
          GRAMMAR.

`getopt-long''s ARGS parameter is expected to be a list of strings like
the one returned by `command-line', with the first element being the
name of the command.  Therefore `getopt-long' ignores the first element
in ARGS and starts argument interpretation with the second element.

   `getopt-long' signals an error if any of the following conditions
hold.

   * The option grammar has an invalid syntax.

   * One of the options in the argument list was not specified by the
     grammar.

   * A required option is omitted.

   * An option which requires an argument did not get one.

   * An option that doesn't accept an argument does get one (this can
     only happen using the long option `--opt=VALUE' syntax).

   * An option predicate fails.


File: guile.info,  Node: option-ref Reference,  Prev: getopt-long Reference,  Up: getopt-long

10.2.5 Reference Documentation for `option-ref'
-----------------------------------------------

 -- Scheme Procedure: option-ref options key default
     Search OPTIONS for a command line option named KEY and return its
     value, if found.  If the option has no value, but was given,
     return `#t'.  If the option was not given, return DEFAULT.
     OPTIONS must be the result of a call to `getopt-long'.

   `option-ref' always succeeds, either by returning the requested
option value from the command line, or the default value.

   The special key `'()' can be used to get a list of all non-option
arguments.


File: guile.info,  Node: Debugging Features,  Next: Autoconf Support,  Prev: Command Line Handling,  Up: Top

11 Debugging Features
*********************

When debugging a program, programmers often find it helpful to examine
the program's internal status while it runs: the values of internal
variables, the choices made in `if' and `cond' statements, and so
forth.  Guile Scheme provides a debugging interface that programmers
can use to single-step through Scheme functions and examine symbol
bindings.  This is different from the *Note Debugging::, which permits
programmers to debug the Guile interpreter itself.  Most programmers
will be more interested in debugging their own Scheme programs than the
interpreter which evaluates them.

   [FIXME: should we include examples of traditional debuggers and
explain why they can't be used to debug interpreted Scheme or Lisp?]

* Menu:

* Single-Step::         Execute a program or function one step at a time.
* Trace::               Print a report each time a given function is called.
* Backtrace::           See a list of the statements that caused an error.


File: guile.info,  Node: Single-Step,  Next: Trace,  Up: Debugging Features

11.1 Single-Step
================


File: guile.info,  Node: Trace,  Next: Backtrace,  Prev: Single-Step,  Up: Debugging Features

11.2 Trace
==========

When a function is "traced", it means that every call to that function
is reported to the user during a program run.  This can help a
programmer determine whether a function is being called at the wrong
time or with the wrong set of arguments.

 -- Functie: trace function
     Enable debug tracing on `function'.  While a program is being run,
     Guile will print a brief report at each call to a traced function,
     advising the user which function was called and the arguments that
     were passed to it.

 -- Functie: untrace function
     Disable debug tracing for `function'.

   Example:

     (define (rev ls)
       (if (null? ls)
           '()
           (append (rev (cdr ls))
                   (cons (car ls) '())))) => rev

     (trace rev) => (rev)

     (rev '(a b c d e))
     => [rev (a b c d e)]
        |  [rev (b c d e)]
        |  |  [rev (c d e)]
        |  |  |  [rev (d e)]
        |  |  |  |  [rev (e)]
        |  |  |  |  |  [rev ()]
        |  |  |  |  |  ()
        |  |  |  |  (e)
        |  |  |  (e d)
        |  |  (e d c)
        |  (e d c b)
        (e d c b a)
        (e d c b a)

   Note the way Guile indents the output, illustrating the depth of
execution at each function call.  This can be used to demonstrate, for
example, that Guile implements self-tail-recursion properly:

     (define (rev ls sl)
       (if (null? ls)
           sl
           (rev (cdr ls)
                (cons (car ls) sl)))) => rev

     (trace rev) => (rev)

     (rev '(a b c d e) '())
     => [rev (a b c d e) ()]
        [rev (b c d e) (a)]
        [rev (c d e) (b a)]
        [rev (d e) (c b a)]
        [rev (e) (d c b a)]
        [rev () (e d c b a)]
        (e d c b a)
        (e d c b a)

   Since the tail call is effectively optimized to a `goto' statement,
there is no need for Guile to create a new stack frame for each
iteration.  Using `trace' here helps us see why this is so.


File: guile.info,  Node: Backtrace,  Prev: Trace,  Up: Debugging Features

11.3 Backtrace
==============

 -- Scheme Procedure: backtrace
 -- C Function: scm_backtrace ()
     Display a backtrace of the stack saved by the last error to the
     current output port.


File: guile.info,  Node: Autoconf Support,  Next: Miscellaneous Tools,  Prev: Debugging Features,  Up: Top

12 Autoconf Support
*******************

When Guile is installed, a set of autoconf macros is also installed as
PREFIX/share/aclocal/guile.m4.  This chapter documents the macros
provided in that file, as well as the high-level guile-tool Autofrisk.
*Note The GNU Autoconf Manual: (autoconf)Top, for more info.

* Menu:

* Autoconf Background::         Why use autoconf?
* Autoconf Macros::             The GUILE_* macros.
* Using Autoconf Macros::       How to use them, plus examples.
* Autofrisk::                   AUTOFRISK_CHECKS and AUTOFRISK_SUMMARY.
* Using Autofrisk::             Example modules.af files.


File: guile.info,  Node: Autoconf Background,  Next: Autoconf Macros,  Up: Autoconf Support

12.1 Autoconf Background
========================

As explained elsewhere (*note The GNU Autoconf Manual: (autoconf)Top.),
any package needs configuration at build-time.  If your package uses
Guile (or uses a package that in turn uses Guile), you probably need to
know what specific Guile features are available and details about them.

   The way to do this is to write feature tests and arrange for their
execution by the `configure' script, typically by adding the tests to
`configure.ac', and running `autoconf' to create `configure'.  Users of
your package then run `configure' in the normal way.

   Macros are a way to make common feature tests easy to express.
Autoconf provides a wide range of macros (*note Existing Tests:
(autoconf)Existing Tests.), and Guile installation provides
Guile-specific tests in the areas of: program detection, compilation
flags reporting, and Scheme module checks.


File: guile.info,  Node: Autoconf Macros,  Next: Using Autoconf Macros,  Prev: Autoconf Background,  Up: Autoconf Support

12.2 Autoconf Macros
====================

The macro names all begin with "GUILE_".


File: guile.info,  Node: Using Autoconf Macros,  Next: Autofrisk,  Prev: Autoconf Macros,  Up: Autoconf Support

12.3 Using Autoconf Macros
==========================

Using the autoconf macros is straightforward: Add the macro "calls"
(actually instantiations) to `configure.ac', run `aclocal', and finally,
run `autoconf'.  If your system doesn't have guile.m4 installed, place
the desired macro definitions (`AC_DEFUN' forms) in `acinclude.m4', and
`aclocal' will do the right thing.

   Some of the macros can be used inside normal shell constructs: `if
foo ; then GUILE_BAZ ; fi', but this is not guaranteed.  It's probably
a good idea to instantiate macros at top-level.

   We now include two examples, one simple and one complicated.

   The first example is for a package that uses libguile, and thus
needs to know how to compile and link against it.  So we use
`GUILE_FLAGS' to set the vars `GUILE_CFLAGS' and `GUILE_LDFLAGS', which
are automatically substituted in the Makefile.

     In configure.ac:

       GUILE_FLAGS

     In Makefile.in:

       GUILE_CFLAGS  = @GUILE_CFLAGS@
       GUILE_LDFLAGS = @GUILE_LDFLAGS@

       myprog.o: myprog.c
               $(CC) -o $ $(GUILE_CFLAGS) $<
       myprog: myprog.o
               $(CC) -o $ $< $(GUILE_LDFLAGS)

   The second example is for a package of Guile Scheme modules that
uses an external program and other Guile Scheme modules (some might
call this a "pure scheme" package).  So we use the `GUILE_SITE_DIR'
macro, a regular `AC_PATH_PROG' macro, and the `GUILE_MODULE_AVAILABLE'
macro.

     In configure.ac:

       GUILE_SITE_DIR

       probably_wont_work=""

       # pgtype pgtable
       GUILE_MODULE_AVAILABLE(have_guile_pg, (database postgres))
       test $have_guile_pg = no &&
           probably_wont_work="(my pgtype) (my pgtable) $probably_wont_work"

       # gpgutils
       AC_PATH_PROG(GNUPG,gpg)
       test x"$GNUPG" = x &&
           probably_wont_work="(my gpgutils) $probably_wont_work"

       if test ! "$probably_wont_work" = "" ; then
           p="         ***"
           echo
           echo "$p"
           echo "$p NOTE:"
           echo "$p The following modules probably won't work:"
           echo "$p   $probably_wont_work"
           echo "$p They can be installed anyway, and will work if their"
           echo "$p dependencies are installed later.  Please see README."
           echo "$p"
           echo
       fi

     In Makefile.in:

       instdir = @GUILE_SITE@/my

       install:
             $(INSTALL) my/*.scm $(instdir)


File: guile.info,  Node: Autofrisk,  Next: Using Autofrisk,  Prev: Using Autoconf Macros,  Up: Autoconf Support

12.4 Autofrisk
==============

The "guile-tools autofrisk" command looks for the file `modules.af' in
the current directory and writes out `modules.af.m4' containing
autoconf definitions for `AUTOFRISK_CHECKS' and `AUTOFRISK_SUMMARY'.
*Note Autoconf Background::, and *Note Using Autoconf Macros::, for
more info.

   The modules.af file consists of a series of configuration forms
(Scheme lists), which have one of the following formats:

       (files-glob PATTERN ...)                      ;; required
       (non-critical-external MODULE ...)            ;; optional
       (non-critical-internal MODULE ...)            ;; optional
       (programs (MODULE PROG ...) ...)              ;; optional
       (pww-varname VARNAME)                         ;; optional

   PATTERN is a string that may contain "*" and "?" characters to be
expanded into filenames.  MODULE is a list of symbols naming a module,
such as `(srfi srfi-1)'.  VARNAME is a shell-safe name to use instead of
`probably_wont_work', the default.  This var is passed to `AC_SUBST'.
PROG is a string that names a program, such as "gpg".

   Autofrisk expands the `files-glob' pattern(s) into a list of files,
scans each file's module definition form(s), and constructs a module
dependency graph wherein modules defined by `define-module' are
considered "internal" and the remaining, "external".  For each external
module that has an internal dependency, Autofrisk emits a
`GUILE_MODULE_REQUIRED' check (*note Autoconf Macros::), which
altogether form the body of `AUTOFRISK_CHECKS'.

   `GUILE_MODULE_REQUIRED' causes the `configure' script to exit with
an error message if the specified module is not available; it enforces a
strong dependency.  You can temper dependency strength by using the
`non-critical-external' and `non-critical-internal' configuration forms
in modules.af.  For graph edges that touch such non-critical modules,
Autofrisk uses `GUILE_MODULE_AVAILABLE', and arranges for
`AUTOFRISK_SUMMARY' to display a warning if they are not found.

   The shell code resulting from the expansion of `AUTOFRISK_CHECKS' and
`AUTOFRISK_SUMMARY' uses the shell variable `probably_wont_work' to
collect the names of unfound non-critical modules.  If this bothers
you, use configuration form `(pww-name foo)' in modules.af.

   Although Autofrisk does not detect when a module uses a program (for
example, in a `system' call), it can generate `AC_PATH_PROG' forms
anyway if you use the `programs' configuration form in modules.af.
These are collected into `AUTOCONF_CHECKS'.

   *Note Using Autofrisk::, for some modules.af examples.


File: guile.info,  Node: Using Autofrisk,  Prev: Autofrisk,  Up: Autoconf Support

12.5 Using Autofrisk
====================

Using Autofrisk (*note Autofrisk::) involves writing `modules.af' and
adding two macro calls to `configure.in'.  Here is an example of the
latter:

     AUTOFRISK_CHECKS
     AUTOFRISK_SUMMARY

   Here is an adaptation of the second "GUILE_*" example (*note Using
Autoconf Macros::) that does basically the same thing.

     (files-glob "my/*.scm")
     (non-critical-external (database postgres))
     (programs ((my gpgutils) "gpg"))        ;; (my gpgutils) uses "gpg"

   If the SRFI modules (*note SRFI Support::) were a separate package,
we could use `guile-tools frisk' to find out its dependencies:

     $ guile-tools frisk srfi/*.scm
     13 files, 18 modules (13 internal, 5 external), 9 edges

     x (ice-9 and-let-star)
     			 regular	(srfi srfi-2)
     x (ice-9 syncase)
     			 regular	(srfi srfi-11)
     x (ice-9 rdelim)
     			 regular	(srfi srfi-10)
     x (ice-9 receive)
     			 regular	(srfi srfi-8)
     			 regular	(srfi srfi-1)
     x (ice-9 session)
     			 regular	(srfi srfi-1)

   Then, we could use the following modules.af to help configure it:

     (files-glob "srfi/*.scm")
     (non-critical-external          ;; relatively recent
       (ice-9 rdelim)
       (ice-9 receive)
       (ice-9 and-let-star))
     (pww-varname not_fully_supported)


File: guile.info,  Node: Miscellaneous Tools,  Next: Basic Ideas,  Prev: Autoconf Support,  Up: Top

13 Miscellaneous Tools
**********************

Programming is more fun with a good tools.  This chapter describes
snarfing tools, and the `guile-tools' program which can be used to
invoke the rest of the tools (which are self-documenting).  Some of
these are used in Guile development, too.  Imagine that!

* Menu:

* Snarfing::                    Grepping the source in various ways.
* Executable Modules::          Modules callable via guile-tools.


File: guile.info,  Node: Snarfing,  Next: Executable Modules,  Up: Miscellaneous Tools

13.1 Snarfing
=============

Because it's easier to maintain documentation, code, and other metainfo
in one source file than in many files, there have evolved many methods
for grepping source to lift and separate these kinds of info, in the
process generating docs or fragments of source or what have you.  This
is known generally as "snarfing", which comes from the verb "to snarf",
here meaning "to unceremoniously extract information from a somewhat
unwilling source."

   This section documents the installed program `guile-snarf' which does
"init snarfing", and also touches upon guile's doc snarfing process
which is not yet finalized (i.e., doc snarfing programs are not
installed at this time).

* Menu:

* Init Snarfing with guile-snarf::      Exposing C subrs and friends to Scheme.
* Doc Snarfing::                        Generating GDFv2 or texi from source.


File: guile.info,  Node: Init Snarfing with guile-snarf,  Next: Doc Snarfing,  Up: Snarfing

13.1.1 Init Snarfing with guile-snarf
-------------------------------------

When writing C code for use with Guile, you typically define a set of C
functions, and then make some of them visible to the Scheme world by
calling the `scm_c_define_gsubr' function; a C function published in
this way is called a "subr".  If you have many subrs to publish, it can
sometimes be annoying to keep the list of calls to `scm_c_define_gsubr'
in sync with the list of function definitions.  Frequently, a
programmer will define a new subr in C, recompile the application, and
then discover that the Scheme interpreter cannot see the subr, because
of a missed call to `scm_c_define_gsubr'.

   Guile provides the `guile-snarf' command to manage this problem.
Using this tool, you can keep all the information needed to define the
subr alongside the function definition itself; `guile-snarf' will
extract this information from your source code, and automatically
generate a file of calls to `scm_c_define_gsubr' which you can
`#include' into an initialization function.

* Menu:

* How guile-snarf works::           Using `guile-snarf', with example.
* Macros guile-snarf recognizes::   How to mark up code for `guile-snarf'.
* Writing your own snarfing macros:: How to define new things to snarf.


File: guile.info,  Node: How guile-snarf works,  Next: Macros guile-snarf recognizes,  Up: Init Snarfing with guile-snarf

13.1.1.1 How guile-snarf works
..............................

Usage: guile-snarf [-o OUTFILE] [CPP-ARGS ...]

   The `guile-snarf' program will extract initialization actions to
OUTFILE or to standard output when no OUTFILE has been specified or
when OUTFILE is `-'.  The C preprocessor is called with CPP-ARGS (which
usually include an input file) and the output is filtered to extract
the initialization actions.

   If there are errors during processing, OUTFILE is deleted and the
program exits with non-zero status.

   During snarfing, the pre-processor macro `SCM_MAGIC_SNARFER' is
defined.  You could use this to avoid including snarfer output files
that don't yet exist by writing code like this:

     #ifndef SCM_MAGIC_SNARFER
     #include "foo.x"
     #endif

   If the environment variable `CPP' is set, use its value instead of
the C pre-processor determined at Guile configure-time.

   *Note Macros guile-snarf recognizes::, for a list of the special
(some would say magic) cpp macros you can use, including the list of
deprecated macros.

   For example, here is how you might define a new subr called
`clear-image', implemented by the C function `clear_image':

     #include <libguile.h>

     SCM_DEFINE (clear_image, "clear-image", 1, 0, 0,
                 (SCM image_smob),
                 "Clear the image.")
     #define FUNC_NAME s_clear_image
     {
       /* C code to clear the image in `image_smob'... */
     }
     #undef FUNC_NAME

     void
     init_image_type ()
     {
     #include "image-type.x"
     }

   The `SCM_DEFINE' declaration says that the C function `clear_image'
implements a Scheme subr called `clear-image', which takes one required
argument (of type `SCM' and named `image_smob'), no optional arguments,
and no rest argument.  *Note Doc Snarfing::, for info on the docstring.

   This works in concert with `FUNC_NAME' to also define a static array
of characters named `s_clear_image', initialized to the string
"clear-image".  The body of `clear_image' may use the array in error
messages, instead of writing out the literal string; this may save
string space on some systems.

   Assuming the text above lives in a file named `image-type.c', you
will need to execute the following command to prepare this file for
compilation:

     guile-snarf -o image-type.x image-type.c

   This scans `image-type.c' for `SCM_DEFINE' declarations, and writes
to `image-type.x' the output:

     scm_c_define_gsubr (s_clear_image, 1, 0, 0, (SCM (*)() ) clear_image);

   When compiled normally, `SCM_DEFINE' is a macro which expands to a
declaration of the `s_clear_image' string and the function header for
`clear_image'.

   Note that the output file name matches the `#include' from the input
file.  Also, you still need to provide all the same information you
would if you were using `scm_c_define_gsubr' yourself, but you can
place the information near the function definition itself, so it is
less likely to become incorrect or out-of-date.

   If you have many files that `guile-snarf' must process, you should
consider using a fragment like the following in your Makefile:

     snarfcppopts = $(DEFS) $(INCLUDES) $(CPPFLAGS) $(CFLAGS)
     .SUFFIXES: .x
     .c.x:
     	guile-snarf -o $ $< $(snarfcppopts)

   This tells make to run `guile-snarf' to produce each needed `.x'
file from the corresponding `.c' file.

   The program `guile-snarf' passes its command-line arguments directly
to the C preprocessor, which it uses to extract the information it
needs from the source code. this means you can pass normal compilation
flags to `guile-snarf' to define preprocessor symbols, add header file
directories, and so on.


File: guile.info,  Node: Macros guile-snarf recognizes,  Next: Writing your own snarfing macros,  Prev: How guile-snarf works,  Up: Init Snarfing with guile-snarf

13.1.1.2 Macros guile-snarf recognizes
......................................

Here are the macros you can use in your source code from which
`guile-snarf' can construct initialization code:

     /* procedures */
     SCM_DEFINE (FNAME, PRIMNAME, REQ, OPT, VAR, ARGLIST, DOCSTRING)

     SCM_PROC (RANAME, STR, REQ, OPT, VAR, CFN)
     SCM_REGISTER_PROC (RANAME, STR, REQ, OPT, VAR, CFN)

     SCM_GPROC (RANAME, STR, REQ, OPT, VAR, CFN, GF)

     /* everything else */
     SCM_SYMBOL (c_name, scheme_name)
     SCM_GLOBAL_SYMBOL (c_name, scheme_name)

     SCM_KEYWORD (c_name, scheme_name)
     SCM_GLOBAL_KEYWORD (c_name, scheme_name)

     SCM_VARIABLE (c_name, scheme_name)
     SCM_GLOBAL_VARIABLE (c_name, scheme_name)

     SCM_VARIABLE_INIT (c_name, scheme_name, init_val)
     SCM_GLOBAL_VARIABLE_INIT (c_name, scheme_name, init_val)

   REQ and OPT are numbers indicating required and optional argument
counts, respectively; VAR is a number that, if non-zero, means the
function will accept any remaining arguments as a list; DOCSTRING is a
string (use `\n\' at eol for multi-line); FNAME is a C-language
identifier, CFN and GF and C_NAME likewise; PRIMNAME is a string
denoting the name available to Scheme code, STR and SCHEME_NAME
likewise; RANAME is the name of the static string (must match that
declared by the associated definition of cpp macro FUNC_NAME); ARGLIST
is an argument list (in parentheses); and lastly, INIT_VAL is a
expression suitable for initializing a new variable.

   For procedures, you can use `SCM_DEFINE' for most purposes.  Use
`SCM_PROC' along with `SCM_REGISTER_PROC' when you don't want to be
bothered with docstrings.  Use `SCM_GPROC' for generic functions (*note
GOOPS: (goops)GOOPS.).  All procedures are declared with return type
`SCM'.

   For everything else, use the appropriate macro (`SCM_SYMBOL' for
symbols, and so on).  Without "_GLOBAL_", the declarations are `static'.

   All these macros should be used at top-level, outside function
bodies.  Also, it's a good idea to define FUNC_NAME immediately after
using `SCM_DEFINE' (and similar), and then the function body, and then
`#undef FUNC_NAME'.

   *Note How guile-snarf works::, and also libguile source, for
examples.  *Note Subrs::, for details on argument passing and how to
write C functions.


File: guile.info,  Node: Writing your own snarfing macros,  Prev: Macros guile-snarf recognizes,  Up: Init Snarfing with guile-snarf

13.1.1.3 Writing your own snarfing macros
.........................................

When you want to use the general snarfing machanism, but none of the
provided macros fits your need, you can use the macro `SCM_SNARF_INIT'.

   For example, the `SCM_SYMBOL' macro can be defined like this:

     #define SCM_SYMBOL(c_name, scheme_name) \
     static SCM c_name \
     SCM_SNARF_INIT(c_name = scm_permanent_object (scm_str2symbol (scheme_name)))

 -- Makro: SCM_SNARF_INIT (code)
     When processed normally, `SCM_SNARF_INIT' expands to nothing; when
     processed by the snarfer, it causes CODE to be included in the
     initialization action file, followed by a semicolon.


File: guile.info,  Node: Doc Snarfing,  Prev: Init Snarfing with guile-snarf,  Up: Snarfing

13.1.2 Doc Snarfing
-------------------

In addition to init snarfing (*note Init Snarfing with guile-snarf::),
the libguile sources are also subject to doc snarfing, by programs that
are included in the distribution (but not installed at this time).  The
output is the file `guile-procedures.txt' which is installed, and
subsequently used by module `(ice-9 documentation)'.

   Here is a list of what does what according to `libguile/Makefile.am':

   * guile-snarf-docs runs cpp defining SCM_MAGIC_SNARF_DOCS

   * guile_filter_doc_snarfage parses guile-snarf-docs output to
     produce .doc

   * ../scripts/snarf-check-and-output-texi makes guile.texi

   * ../scripts/snarf-check-and-output-texi makes guile-procedures.txt

   * guile-func-name-check checks source snarf-syntax integrity
     (optional?)

   * guile-doc-snarf calls guile-snarf-docs (to make .doc) and
     guile-snarf

   Note that for guile-1.4, a completely different approach was used!
All this is rather byzantine, so for now _NO_ doc snarfing programs are
installed.

   [fixme: Document further once doc snarfing is tamed somewhat. -ttn]


File: guile.info,  Node: Executable Modules,  Prev: Snarfing,  Up: Miscellaneous Tools

13.2 Executable Modules
=======================

When Guile is installed, in addition to the `(ice-9 FOO)' modules, a
set of "executable modules" `(scripts BAR)' is also installed.  Each is
a regular Scheme module that has some additional packaging so that it
can be called as a program in its own right, from the shell.  For this
reason, we sometimes use the term "script" in this context to mean the
same thing.

   As a convenience, the `guile-tools' wrapper program is installed
along w/ `guile'; it knows where a particular module is installed and
calls it passing its args to the program.  The result is that you need
not augment your PATH.  Usage is straightforward:

     guile-tools --help
     guile-tools --version
     guile-tools [OPTION] PROGRAM [ARGS ...]

     If PROGRAM is "list" or omitted, display contents of scripts dir, otherwise
     PROGRAM is run w/ ARGS.  Options (only one of which may be used at a time):
      --scriptsdir DIR    -- Look in DIR for scripts
      --guileversion VERS -- Look in $pkgdatadir/VERS/scripts for scripts
      --source            -- Display PROGRAM source (ignore ARGS) to stdout

   The modules are self-documenting.  For example, to see the
documentation for `lint', use one (or both) of the shell commands:

     guile-tools display-commentary '(scripts lint)'
     guile-tools --source lint

   The rest of this section describes the packaging that goes into
creating an executable module.  Feel free to skip to the next chapter.

13.2.1 Writing Executable Modules
---------------------------------

See template file `PROGRAM' for a quick start.

   Programs must follow the "executable module" convention, documented
here:

   * The file name must not end in ".scm".

   * The file must be executable (chmod +x).

   * The module name must be "(scripts PROGRAM)".  A procedure named
     PROGRAM w/ signature "(PROGRAM . args)" must be exported.
     Basically, use some variant of the form:

          (define-module (scripts PROGRAM)
            :export (PROGRAM))

     Feel free to export other definitions useful in the module context.

   * There must be the alias:

          (define main PROGRAM)

     However, `main' must NOT be exported.

   * The beginning of the file must use the following invocation
     sequence:

          #!/bin/sh
          main='(module-ref (resolve-module '\''(scripts PROGRAM)) '\'main')'
          exec ${GUILE-guile} -l $0 -c "(apply $main (cdr (command-line)))" "$@"
          !#


   Following these conventions allows the program file to be used as
module `(scripts PROGRAM)' in addition to as a standalone executable.
Please also include a helpful Commentary section w/ some usage info.


File: guile.info,  Node: Basic Ideas,  Next: Further Reading,  Prev: Miscellaneous Tools,  Up: Top

14 Basic Ideas in Scheme
************************

In this chapter, we introduce the basic concepts that underpin the
elegance and power of the Scheme language.

   Readers who already possess a background knowledge of Scheme may
happily skip this chapter.  For the reader who is new to the language,
however, the following discussions on data, procedures, expressions and
closure are designed to provide a minimum level of Scheme understanding
that is more or less assumed by the reference chapters that follow.

   The style of this introductory material aims about halfway between
the terse precision of R5RS and the discursive randomness of a Scheme
tutorial.

* Menu:

* About Data::                  Latent typing, types, values and variables.
* About Procedures::            The representation and use of procedures.
* About Expressions::           All kinds of expressions and their meaning.
* About Closure::               Closure, scoping and environments.


File: guile.info,  Node: About Data,  Next: About Procedures,  Up: Basic Ideas

14.1 Data Types, Values and Variables
=====================================

This section discusses the representation of data types and values, what
it means for Scheme to be a "latently typed" language, and the role of
variables.  We conclude by introducing the Scheme syntaxes for defining
a new variable, and for changing the value of an existing variable.

* Menu:

* Latent Typing::               Scheme as a "latently typed" language.
* Values and Variables::        About data types, values and variables.
* Definition::                  Defining variables and setting their values.


File: guile.info,  Node: Latent Typing,  Next: Values and Variables,  Up: About Data

14.1.1 Latent Typing
--------------------

The term "latent typing" is used to describe a computer language, such
as Scheme, for which you cannot, _in general_, simply look at a
program's source code and determine what type of data will be
associated with a particular variable, or with the result of a
particular expression.

   Sometimes, of course, you _can_ tell from the code what the type of
an expression will be.  If you have a line in your program that sets the
variable `x' to the numeric value 1, you can be certain that,
immediately after that line has executed (and in the absence of multiple
threads), `x' has the numeric value 1.  Or if you write a procedure
that is designed to concatenate two strings, it is likely that the rest
of your application will always invoke this procedure with two string
parameters, and quite probable that the procedure would go wrong in some
way if it was ever invoked with parameters that were not both strings.

   Nevertheless, the point is that there is nothing in Scheme which
requires the procedure parameters always to be strings, or `x' always
to hold a numeric value, and there is no way of declaring in your
program that such constraints should always be obeyed.  In the same
vein, there is no way to declare the expected type of a procedure's
return value.

   Instead, the types of variables and expressions are only known - in
general - at run time.  If you _need_ to check at some point that a
value has the expected type, Scheme provides run time procedures that
you can invoke to do so.  But equally, it can be perfectly valid for two
separate invocations of the same procedure to specify arguments with
different types, and to return values with different types.

   The next subsection explains what this means in practice, for the
ways that Scheme programs use data types, values and variables.


File: guile.info,  Node: Values and Variables,  Next: Definition,  Prev: Latent Typing,  Up: About Data

14.1.2 Values and Variables
---------------------------

Scheme provides many data types that you can use to represent your data.
Primitive types include characters, strings, numbers and procedures.
Compound types, which allow a group of primitive and compound values to
be stored together, include lists, pairs, vectors and multi-dimensional
arrays.  In addition, Guile allows applications to define their own data
types, with the same status as the built-in standard Scheme types.

   As a Scheme program runs, values of all types pop in and out of
existence.  Sometimes values are stored in variables, but more commonly
they pass seamlessly from being the result of one computation to being
one of the parameters for the next.

   Consider an example.  A string value is created because the
interpreter reads in a literal string from your program's source code.
Then a numeric value is created as the result of calculating the length
of the string.  A second numeric value is created by doubling the
calculated length.  Finally the program creates a list with two
elements - the doubled length and the original string itself - and
stores this list in a program variable.

   All of the values involved here - in fact, all values in Scheme -
carry their type with them.  In other words, every value "knows," at
runtime, what kind of value it is.  A number, a string, a list,
whatever.

   A variable, on the other hand, has no fixed type.  A variable - `x',
say - is simply the name of a location - a box - in which you can store
any kind of Scheme value.  So the same variable in a program may hold a
number at one moment, a list of procedures the next, and later a pair
of strings.  The "type" of a variable - insofar as the idea is
meaningful at all - is simply the type of whatever value the variable
happens to be storing at a particular moment.


File: guile.info,  Node: Definition,  Prev: Values and Variables,  Up: About Data

14.1.3 Defining and Setting Variables
-------------------------------------

To define a new variable, you use Scheme's `define' syntax like this:

     (define VARIABLE-NAME VALUE)

   This makes a new variable called VARIABLE-NAME and stores VALUE in
it as the variable's initial value.  For example:

     ;; Make a variable `x' with initial numeric value 1.
     (define x 1)

     ;; Make a variable `organization' with an initial string value.
     (define organization "Free Software Foundation")

   (In Scheme, a semicolon marks the beginning of a comment that
continues until the end of the line.  So the lines beginning `;;' are
comments.)

   Changing the value of an already existing variable is very similar,
except that `define' is replaced by the Scheme syntax `set!', like this:

     (set! VARIABLE-NAME NEW-VALUE)

   Remember that variables do not have fixed types, so NEW-VALUE may
have a completely different type from whatever was previously stored in
the location named by VARIABLE-NAME.  Both of the following examples
are therefore correct.

     ;; Change the value of `x' to 5.
     (set! x 5)

     ;; Change the value of `organization' to the FSF's street number.
     (set! organization 545)

   In these examples, VALUE and NEW-VALUE are literal numeric or string
values.  In general, however, VALUE and NEW-VALUE can be any Scheme
expression.  Even though we have not yet covered the forms that Scheme
expressions can take (*note About Expressions::), you can probably
guess what the following `set!' example does...

     (set! x (+ x 1))

   (Note: this is not a complete description of `define' and `set!',
because we need to introduce some other aspects of Scheme before the
missing pieces can be filled in.  If, however, you are already familiar
with the structure of Scheme, you may like to read about those missing
pieces immediately by jumping ahead to the following references.

   * *Note Lambda Alternatives::, to read about an alternative form of
     the `define' syntax that can be used when defining new procedures.

   * *Note Procedures with Setters::, to read about an alternative form
     of the `set!' syntax that helps with changing a single value in
     the depths of a compound data structure.)

   * *Note Internal Definitions::, to read about using `define' other
     than at top level in a Scheme program, including a discussion of
     when it works to use `define' rather than `set!' to change the
     value of an existing variable.


File: guile.info,  Node: About Procedures,  Next: About Expressions,  Prev: About Data,  Up: Basic Ideas

14.2 The Representation and Use of Procedures
=============================================

This section introduces the basics of using and creating Scheme
procedures.  It discusses the representation of procedures as just
another kind of Scheme value, and shows how procedure invocation
expressions are constructed.  We then explain how `lambda' is used to
create new procedures, and conclude by presenting the various shorthand
forms of `define' that can be used instead of writing an explicit
`lambda' expression.

* Menu:

* Procedures as Values::        Procedures are values like everything else.
* Simple Invocation::           How to write a simple procedure invocation.
* Creating a Procedure::        How to create your own procedures.
* Lambda Alternatives::         Other ways of writing procedure definitions.


File: guile.info,  Node: Procedures as Values,  Next: Simple Invocation,  Up: About Procedures

14.2.1 Procedures as Values
---------------------------

One of the great simplifications of Scheme is that a procedure is just
another type of value, and that procedure values can be passed around
and stored in variables in exactly the same way as, for example, strings
and lists.  When we talk about a built-in standard Scheme procedure such
as `open-input-file', what we actually mean is that there is a
pre-defined top level variable called `open-input-file', whose value is
a procedure that implements what R5RS says that `open-input-file'
should do.

   Note that this is quite different from many dialects of Lisp --
including Emacs Lisp -- in which a program can use the same name with
two quite separate meanings: one meaning identifies a Lisp function,
while the other meaning identifies a Lisp variable, whose value need
have nothing to do with the function that is associated with the first
meaning.  In these dialects, functions and variables are said to live in
different "namespaces".

   In Scheme, on the other hand, all names belong to a single unified
namespace, and the variables that these names identify can hold any kind
of Scheme value, including procedure values.

   One consequence of the "procedures as values" idea is that, if you
don't happen to like the standard name for a Scheme procedure, you can
change it.

   For example, `call-with-current-continuation' is a very important
standard Scheme procedure, but it also has a very long name!  So, many
programmers use the following definition to assign the same procedure
value to the more convenient name `call/cc'.

     (define call/cc call-with-current-continuation)

   Let's understand exactly how this works.  The definition creates a
new variable `call/cc', and then sets its value to the value of the
variable `call-with-current-continuation'; the latter value is a
procedure that implements the behaviour that R5RS specifies under the
name "call-with-current-continuation".  So `call/cc' ends up holding
this value as well.

   Now that `call/cc' holds the required procedure value, you could
choose to use `call-with-current-continuation' for a completely
different purpose, or just change its value so that you will get an
error if you accidentally use `call-with-current-continuation' as a
procedure in your program rather than `call/cc'.  For example:

     (set! call-with-current-continuation "Not a procedure any more!")

   Or you could just leave `call-with-current-continuation' as it was.
It's perfectly fine for more than one variable to hold the same
procedure value.


File: guile.info,  Node: Simple Invocation,  Next: Creating a Procedure,  Prev: Procedures as Values,  Up: About Procedures

14.2.2 Simple Procedure Invocation
----------------------------------

A procedure invocation in Scheme is written like this:

     (PROCEDURE [ARG1 [ARG2 ...]])

   In this expression, PROCEDURE can be any Scheme expression whose
value is a procedure.  Most commonly, however, PROCEDURE is simply the
name of a variable whose value is a procedure.

   For example, `string-append' is a standard Scheme procedure whose
behaviour is to concatenate together all the arguments, which are
expected to be strings, that it is given.  So the expression

     (string-append "/home" "/" "andrew")

is a procedure invocation whose result is the string value
`"/home/andrew"'.

   Similarly, `string-length' is a standard Scheme procedure that
returns the length of a single string argument, so

     (string-length "abc")

is a procedure invocation whose result is the numeric value 3.

   Each of the parameters in a procedure invocation can itself be any
Scheme expression.  Since a procedure invocation is itself a type of
expression, we can put these two examples together to get

     (string-length (string-append "/home" "/" "andrew"))

-- a procedure invocation whose result is the numeric value 12.

   (You may be wondering what happens if the two examples are combined
the other way round.  If we do this, we can make a procedure invocation
expression that is _syntactically_ correct:

     (string-append "/home" (string-length "abc"))

but when this expression is executed, it will cause an error, because
the result of `(string-length "abc")' is a numeric value, and
`string-append' is not designed to accept a numeric value as one of its
arguments.)


File: guile.info,  Node: Creating a Procedure,  Next: Lambda Alternatives,  Prev: Simple Invocation,  Up: About Procedures

14.2.3 Creating and Using a New Procedure
-----------------------------------------

Scheme has lots of standard procedures, and Guile provides all of these
via predefined top level variables.  All of these standard procedures
are documented in the later chapters of this reference manual.

   Before very long, though, you will want to create new procedures that
encapsulate aspects of your own applications' functionality.  To do
this, you can use the famous `lambda' syntax.

   For example, the value of the following Scheme expression

     (lambda (name address) EXPRESSION ...)

is a newly created procedure that takes two arguments: `name' and
`address'.  The behaviour of the new procedure is determined by the
sequence of EXPRESSIONs in the "body" of the procedure definition.
(Typically, these EXPRESSIONs would use the arguments in some way, or
else there wouldn't be any point in giving them to the procedure.)
When invoked, the new procedure returns a value that is the value of
the last EXPRESSION in the procedure body.

   To make things more concrete, let's suppose that the two arguments
are both strings, and that the purpose of this procedure is to form a
combined string that includes these arguments.  Then the full lambda
expression might look like this:

     (lambda (name address)
       (string-append "Name=" name ":Address=" address))

   We noted in the previous subsection that the PROCEDURE part of a
procedure invocation expression can be any Scheme expression whose value
is a procedure.  But that's exactly what a lambda expression is!  So we
can use a lambda expression directly in a procedure invocation, like
this:

     ((lambda (name address)
        (string-append "Name=" name ":Address=" address))
      "FSF"
      "Cambridge")

This is a valid procedure invocation expression, and its result is the
string `"Name=FSF:Address=Cambridge"'.

   It is more common, though, to store the procedure value in a
variable --

     (define make-combined-string
       (lambda (name address)
         (string-append "Name=" name ":Address=" address)))

-- and then to use the variable name in the procedure invocation:

     (make-combined-string "FSF" "Cambridge")

Which has exactly the same result.

   It's important to note that procedures created using `lambda' have
exactly the same status as the standard built in Scheme procedures, and
can be invoked, passed around, and stored in variables in exactly the
same ways.


File: guile.info,  Node: Lambda Alternatives,  Prev: Creating a Procedure,  Up: About Procedures

14.2.4 Lambda Alternatives
--------------------------

Since it is so common in Scheme programs to want to create a procedure
and then store it in a variable, there is an alternative form of the
`define' syntax that allows you to do just that.

   A `define' expression of the form

     (define (NAME [ARG1 [ARG2 ...]])
       EXPRESSION ...)

is exactly equivalent to the longer form

     (define NAME
       (lambda ([ARG1 [ARG2 ...]])
         EXPRESSION ...))

   So, for example, the definition of `make-combined-string' in the
previous subsection could equally be written:

     (define (make-combined-string name address)
       (string-append "Name=" name ":Address=" address))

   This kind of procedure definition creates a procedure that requires
exactly the expected number of arguments.  There are two further forms
of the `lambda' expression, which create a procedure that can accept a
variable number of arguments:

     (lambda (ARG1 ... . ARGS) EXPRESSION ...)

     (lambda ARGS EXPRESSION ...)

The corresponding forms of the alternative `define' syntax are:

     (define (NAME ARG1 ... . ARGS) EXPRESSION ...)

     (define (NAME . ARGS) EXPRESSION ...)

For details on how these forms work, see *Note Lambda::.

   (It could be argued that the alternative `define' forms are rather
confusing, especially for newcomers to the Scheme language, as they hide
both the role of `lambda' and the fact that procedures are values that
are stored in variables in the some way as any other kind of value.  On
the other hand, they are very convenient, and they are also a good
example of another of Scheme's powerful features: the ability to specify
arbitrary syntactic transformations at run time, which can be applied to
subsequently read input.)


File: guile.info,  Node: About Expressions,  Next: About Closure,  Prev: About Procedures,  Up: Basic Ideas

14.3 Expressions and Evaluation
===============================

So far, we have met expressions that _do_ things, such as the `define'
expressions that create and initialize new variables, and we have also
talked about expressions that have _values_, for example the value of
the procedure invocation expression:

     (string-append "/home" "/" "andrew")

but we haven't yet been precise about what causes an expression like
this procedure invocation to be reduced to its "value", or how the
processing of such expressions relates to the execution of a Scheme
program as a whole.

   This section clarifies what we mean by an expression's value, by
introducing the idea of "evaluation".  It discusses the side effects
that evaluation can have, explains how each of the various types of
Scheme expression is evaluated, and describes the behaviour and use of
the Guile REPL as a mechanism for exploring evaluation.  The section
concludes with a very brief summary of Scheme's common syntactic
expressions.

* Menu:

* Evaluating::                  How a Scheme program is executed.
* The REPL::                    Interacting with the Guile interpreter.
* Syntax Summary::              Common syntactic expressions -- in brief.


File: guile.info,  Node: Evaluating,  Next: The REPL,  Up: About Expressions

14.3.1 Evaluating Expressions and Executing Programs
----------------------------------------------------

In Scheme, the process of executing an expression is known as
"evaluation".  Evaluation has two kinds of result:

   * the "value" of the evaluated expression

   * the "side effects" of the evaluation, which consist of any effects
     of evaluating the expression that are not represented by the value.

   Of the expressions that we have met so far, `define' and `set!'
expressions have side effects -- the creation or modification of a
variable -- but no value; `lambda' expressions have values -- the newly
constructed procedures -- but no side effects; and procedure invocation
expressions, in general, have either values, or side effects, or both.

   It is tempting to try to define more intuitively what we mean by
"value" and "side effects", and what the difference between them is.
In general, though, this is extremely difficult.  It is also
unnecessary; instead, we can quite happily define the behaviour of a
Scheme program by specifying how Scheme executes a program as a whole,
and then by describing the value and side effects of evaluation for each
type of expression individually.

So, some(1) definitions...

   * A Scheme program consists of a sequence of expressions.

   * A Scheme interpreter executes the program by evaluating these
     expressions in order, one by one.

   * An expression can be

        * a piece of literal data, such as a number `2.3' or a string
          `"Hello world!"'

        * a variable name

        * a procedure invocation expression

        * one of Scheme's special syntactic expressions.

The following subsections describe how each of these types of expression
is evaluated.

* Menu:

* Eval Literal::                Evaluating literal data.
* Eval Variable::               Evaluating variable references.
* Eval Procedure::              Evaluating procedure invocation expressions.
* Eval Special::                Evaluating special syntactic expressions.

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

   (1) These definitions are approximate.  For the whole and detailed
truth, see *Note R5RS syntax: (r5rs)Formal syntax and semantics.


File: guile.info,  Node: Eval Literal,  Next: Eval Variable,  Up: Evaluating

14.3.1.1 Evaluating Literal Data
................................

When a literal data expression is evaluated, the value of the expression
is simply the value that the expression describes.  The evaluation of a
literal data expression has no side effects.

So, for example,

   * the value of the expression `"abc"' is the string value `"abc"'

   * the value of the expression `3+4i' is the complex number 3 + 4i

   * the value of the expression `#(1 2 3)' is a three-element vector
     containing the numeric values 1, 2 and 3.

   For any data type which can be expressed literally like this, the
syntax of the literal data expression for that data type -- in other
words, what you need to write in your code to indicate a literal value
of that type -- is known as the data type's "read syntax".  This manual
specifies the read syntax for each such data type in the section that
describes that data type.

   Some data types do not have a read syntax.  Procedures, for example,
cannot be expressed as literal data; they must be created using a
`lambda' expression (*note Creating a Procedure::) or implicitly using
the shorthand form of `define' (*note Lambda Alternatives::).


File: guile.info,  Node: Eval Variable,  Next: Eval Procedure,  Prev: Eval Literal,  Up: Evaluating

14.3.1.2 Evaluating a Variable Reference
........................................

When an expression that consists simply of a variable name is evaluated,
the value of the expression is the value of the named variable.  The
evaluation of a variable reference expression has no side effects.

   So, after

     (define key "Paul Evans")

the value of the expression `key' is the string value `"Paul Evans"'.
If KEY is then modified by

     (set! key 3.74)

the value of the expression `key' is the numeric value 3.74.

   If there is no variable with the specified name, evaluation of the
variable reference expression signals an error.


File: guile.info,  Node: Eval Procedure,  Next: Eval Special,  Prev: Eval Variable,  Up: Evaluating

14.3.1.3 Evaluating a Procedure Invocation Expression
.....................................................

This is where evaluation starts getting interesting!  As already noted,
a procedure invocation expression has the form

     (PROCEDURE [ARG1 [ARG2 ...]])

where PROCEDURE must be an expression whose value, when evaluated, is a
procedure.

   The evaluation of a procedure invocation expression like this
proceeds by

   * evaluating individually the expressions PROCEDURE, ARG1, ARG2, and
     so on

   * calling the procedure that is the value of the PROCEDURE
     expression with the list of values obtained from the evaluations of
     ARG1, ARG2 etc. as its parameters.

   For a procedure defined in Scheme, "calling the procedure with the
list of values as its parameters" means binding the values to the
procedure's formal parameters and then evaluating the sequence of
expressions that make up the body of the procedure definition.  The
value of the procedure invocation expression is the value of the last
evaluated expression in the procedure body.  The side effects of calling
the procedure are the combination of the side effects of the sequence of
evaluations of expressions in the procedure body.

   For a built-in procedure, the value and side-effects of calling the
procedure are best described by that procedure's documentation.

   Note that the complete side effects of evaluating a procedure
invocation expression consist not only of the side effects of the
procedure call, but also of any side effects of the preceding
evaluation of the expressions PROCEDURE, ARG1, ARG2, and so on.

   To illustrate this, let's look again at the procedure invocation
expression:

     (string-length (string-append "/home" "/" "andrew"))

   In the outermost expression, PROCEDURE is `string-length' and ARG1
is `(string-append "/home" "/" "andrew")'.

   * Evaluation of `string-length', which is a variable, gives a
     procedure value that implements the expected behaviour for
     "string-length".

   * Evaluation of `(string-append "/home" "/" "andrew")', which is
     another procedure invocation expression, means evaluating each of

        * `string-append', which gives a procedure value that
          implements the expected behaviour for "string-append"

        * `"/home"', which gives the string value `"/home"'

        * `"/"', which gives the string value `"/"'

        * `"andrew"', which gives the string value `"andrew"'

     and then invoking the procedure value with this list of string
     values as its arguments.  The resulting value is a single string
     value that is the concatenation of all the arguments, namely
     `"/home/andrew"'.

   In the evaluation of the outermost expression, the interpreter can
now invoke the procedure value obtained from PROCEDURE with the value
obtained from ARG1 as its arguments.  The resulting value is a numeric
value that is the length of the argument string, which is 12.


File: guile.info,  Node: Eval Special,  Prev: Eval Procedure,  Up: Evaluating

14.3.1.4 Evaluating Special Syntactic Expressions
.................................................

When a procedure invocation expression is evaluated, the procedure and
_all_ the argument expressions must be evaluated before the procedure
can be invoked.  Special syntactic expressions are special because they
are able to manipulate their arguments in an unevaluated form, and can
choose whether to evaluate any or all of the argument expressions.

   Why is this needed?  Consider a program fragment that asks the user
whether or not to delete a file, and then deletes the file if the user
answers yes.

     (if (string=? (read-answer "Should I delete this file?")
                   "yes")
         (delete-file file))

   If the outermost `(if ...)' expression here was a procedure
invocation expression, the expression `(delete-file file)', whose side
effect is to actually delete a file, would already have been evaluated
before the `if' procedure even got invoked!  Clearly this is no use --
the whole point of an `if' expression is that the "consequent"
expression is only evaluated if the condition of the `if' expression is
"true".

   Therefore `if' must be special syntax, not a procedure.  Other
special syntaxes that we have already met are `define', `set!' and
`lambda'.  `define' and `set!' are syntax because they need to know the
variable _name_ that is given as the first argument in a `define' or
`set!' expression, not that variable's value.  `lambda' is syntax
because it does not immediately evaluate the expressions that define
the procedure body; instead it creates a procedure object that
incorporates these expressions so that they can be evaluated in the
future, when that procedure is invoked.

   The rules for evaluating each special syntactic expression are
specified individually for each special syntax.  For a summary of
standard special syntax, see *Note Syntax Summary::.


File: guile.info,  Node: The REPL,  Next: Syntax Summary,  Prev: Evaluating,  Up: About Expressions

14.3.2 Using the Guile REPL
---------------------------

If you start Guile without specifying a particular program for it to
execute, Guile enters its standard Read Evaluate Print Loop -- or
"REPL" for short.  In this mode, Guile repeatedly reads in the next
Scheme expression that the user types, evaluates it, and prints the
resulting value.

   The REPL is a useful mechanism for exploring the evaluation behaviour
described in the previous subsection.  If you type `string-append', for
example, the REPL replies `#<primitive-procedure string-append>',
illustrating the relationship between the variable `string-append' and
the procedure value stored in that variable.

   In this manual, the notation => is used to mean "evaluates to".
Wherever you see an example of the form

     EXPRESSION
     =>
     RESULT

feel free to try it out yourself by typing EXPRESSION into the REPL and
checking that it gives the expected RESULT.


File: guile.info,  Node: Syntax Summary,  Prev: The REPL,  Up: About Expressions

14.3.3 Summary of Common Syntax
-------------------------------

This subsection lists the most commonly used Scheme syntactic
expressions, simply so that you will recognize common special syntax
when you see it.  For a full description of each of these syntaxes,
follow the appropriate reference.

   `lambda' (*note Lambda::) is used to construct procedure objects.

   `define' (*note Top Level::) is used to create a new variable and
set its initial value.

   `set!' (*note Top Level::) is used to modify an existing variable's
value.

   `let', `let*' and `letrec' (*note Local Bindings::) create an inner
lexical environment for the evaluation of a sequence of expressions, in
which a specified set of local variables is bound to the values of a
corresponding set of expressions.  For an introduction to environments,
see *Note About Closure::.

   `begin' (*note begin::) executes a sequence of expressions in order
and returns the value of the last expression.  Note that this is not the
same as a procedure which returns its last argument, because the
evaluation of a procedure invocation expression does not guarantee to
evaluate the arguments in order.

   `if' and `cond' (*note if cond case::) provide conditional
evaluation of argument expressions depending on whether one or more
conditions evaluate to "true" or "false".

   `case' (*note if cond case::) provides conditional evaluation of
argument expressions depending on whether a variable has one of a
specified group of values.

   `and' (*note and or::) executes a sequence of expressions in order
until either there are no expressions left, or one of them evaluates to
"false".

   `or' (*note and or::) executes a sequence of expressions in order
until either there are no expressions left, or one of them evaluates to
"true".


File: guile.info,  Node: About Closure,  Prev: About Expressions,  Up: Basic Ideas

14.4 The Concept of Closure
===========================

The concept of "closure" is the idea that a lambda expression
"captures" the variable bindings that are in lexical scope at the point
where the lambda expression occurs.  The procedure created by the
lambda expression can refer to and mutate the captured bindings, and the
values of those bindings persist between procedure calls.

   This section explains and explores the various parts of this idea in
more detail.

* Menu:

* About Environments::          Names, locations, values and environments.
* Local Variables::             Local variables and local environments.
* Chaining::                    Environment chaining.
* Lexical Scope::               The meaning of lexical scoping.
* Closure::                     Explaining the concept of closure.
* Serial Number::               Example 1: a serial number generator.
* Shared Variable::             Example 2: a shared persistent variable.
* Callback Closure::            Example 3: the callback closure problem.
* OO Closure::                  Example 4: object orientation.


File: guile.info,  Node: About Environments,  Next: Local Variables,  Up: About Closure

14.4.1 Names, Locations, Values and Environments
------------------------------------------------

We said earlier that a variable name in a Scheme program is associated
with a location in which any kind of Scheme value may be stored.
(Incidentally, the term "vcell" is often used in Lisp and Scheme
circles as an alternative to "location".)  Thus part of what we mean
when we talk about "creating a variable" is in fact establishing an
association between a name, or identifier, that is used by the Scheme
program code, and the variable location to which that name refers.
Although the value that is stored in that location may change, the
location to which a given name refers is always the same.

   We can illustrate this by breaking down the operation of the
`define' syntax into three parts: `define'

   * creates a new location

   * establishes an association between that location and the name
     specified as the first argument of the `define' expression

   * stores in that location the value obtained by evaluating the second
     argument of the `define' expression.

   A collection of associations between names and locations is called an
"environment".  When you create a top level variable in a program using
`define', the name-location association for that variable is added to
the "top level" environment.  The "top level" environment also includes
name-location associations for all the procedures that are supplied by
standard Scheme.

   It is also possible to create environments other than the top level
one, and to create variable bindings, or name-location associations, in
those environments.  This ability is a key ingredient in the concept of
closure; the next subsection shows how it is done.


File: guile.info,  Node: Local Variables,  Next: Chaining,  Prev: About Environments,  Up: About Closure

14.4.2 Local Variables and Environments
---------------------------------------

We have seen how to create top level variables using the `define'
syntax (*note Definition::).  It is often useful to create variables
that are more limited in their scope, typically as part of a procedure
body.  In Scheme, this is done using the `let' syntax, or one of its
modified forms `let*' and `letrec'.  These syntaxes are described in
full later in the manual (*note Local Bindings::).  Here our purpose is
to illustrate their use just enough that we can see how local variables
work.

   For example, the following code uses a local variable `s' to
simplify the computation of the area of a triangle given the lengths of
its three sides.

     (define a 5.3)
     (define b 4.7)
     (define c 2.8)

     (define area
       (let ((s (/ (+ a b c) 2)))
         (sqrt (* s (- s a) (- s b) (- s c)))))

   The effect of the `let' expression is to create a new environment
and, within this environment, an association between the name `s' and a
new location whose initial value is obtained by evaluating `(/ (+ a b
c) 2)'.  The expressions in the body of the `let', namely `(sqrt (* s
(- s a) (- s b) (- s c)))', are then evaluated in the context of the
new environment, and the value of the last expression evaluated becomes
the value of the whole `let' expression, and therefore the value of the
variable `area'.


File: guile.info,  Node: Chaining,  Next: Lexical Scope,  Prev: Local Variables,  Up: About Closure

14.4.3 Environment Chaining
---------------------------

In the example of the previous subsection, we glossed over an important
point.  The body of the `let' expression in that example refers not
only to the local variable `s', but also to the top level variables
`a', `b', `c' and `sqrt'.  (`sqrt' is the standard Scheme procedure for
calculating a square root.)  If the body of the `let' expression is
evaluated in the context of the _local_ `let' environment, how does the
evaluation get at the values of these top level variables?

   The answer is that the local environment created by a `let'
expression automatically has a reference to its containing environment
-- in this case the top level environment -- and that the Scheme
interpreter automatically looks for a variable binding in the containing
environment if it doesn't find one in the local environment.  More
generally, every environment except for the top level one has a
reference to its containing environment, and the interpreter keeps
searching back up the chain of environments -- from most local to top
level -- until it either finds a variable binding for the required
identifier or exhausts the chain.

   This description also determines what happens when there is more than
one variable binding with the same name.  Suppose, continuing the
example of the previous subsection, that there was also a pre-existing
top level variable `s' created by the expression:

     (define s "Some beans, my lord!")

   Then both the top level environment and the local `let' environment
would contain bindings for the name `s'.  When evaluating code within
the `let' body, the interpreter looks first in the local `let'
environment, and so finds the binding for `s' created by the `let'
syntax.  Even though this environment has a reference to the top level
environment, which also has a binding for `s', the interpreter doesn't
get as far as looking there.  When evaluating code outside the `let'
body, the interpreter looks up variable names in the top level
environment, so the name `s' refers to the top level variable.

   Within the `let' body, the binding for `s' in the local environment
is said to "shadow" the binding for `s' in the top level environment.


File: guile.info,  Node: Lexical Scope,  Next: Closure,  Prev: Chaining,  Up: About Closure

14.4.4 Lexical Scope
--------------------

The rules that we have just been describing are the details of how
Scheme implements "lexical scoping".  This subsection takes a brief
diversion to explain what lexical scope means in general and to present
an example of non-lexical scoping.

   "Lexical scope" in general is the idea that

   * an identifier at a particular place in a program always refers to
     the same variable location -- where "always" means "every time
     that the containing expression is executed", and that

   * the variable location to which it refers can be determined by
     static examination of the source code context in which that
     identifier appears, without having to consider the flow of
     execution through the program as a whole.

   In practice, lexical scoping is the norm for most programming
languages, and probably corresponds to what you would intuitively
consider to be "normal".  You may even be wondering how the situation
could possibly -- and usefully -- be otherwise.  To demonstrate that
another kind of scoping is possible, therefore, and to compare it
against lexical scoping, the following subsection presents an example
of non-lexical scoping and examines in detail how its behavior differs
from the corresponding lexically scoped code.

* Menu:

* Scoping Example::             An example of non-lexical scoping.


File: guile.info,  Node: Scoping Example,  Up: Lexical Scope

14.4.4.1 An Example of Non-Lexical Scoping
..........................................

To demonstrate that non-lexical scoping does exist and can be useful, we
present the following example from Emacs Lisp, which is a "dynamically
scoped" language.

     (defvar currency-abbreviation "USD")

     (defun currency-string (units hundredths)
       (concat currency-abbreviation
               (number-to-string units)
               "."
               (number-to-string hundredths)))

     (defun french-currency-string (units hundredths)
       (let ((currency-abbreviation "FRF"))
         (currency-string units hundredths)))

   The question to focus on here is: what does the identifier
`currency-abbreviation' refer to in the `currency-string' function?
The answer, in Emacs Lisp, is that all variable bindings go onto a
single stack, and that `currency-abbreviation' refers to the topmost
binding from that stack which has the name "currency-abbreviation".
The binding that is created by the `defvar' form, to the value `"USD"',
is only relevant if none of the code that calls `currency-string'
rebinds the name "currency-abbreviation" in the meanwhile.

   The second function `french-currency-string' works precisely by
taking advantage of this behaviour.  It creates a new binding for the
name "currency-abbreviation" which overrides the one established by the
`defvar' form.

     ;; Note!  This is Emacs Lisp evaluation, not Scheme!
     (french-currency-string 33 44)
     =>
     "FRF33.44"

   Now let's look at the corresponding, _lexically scoped_ Scheme code:

     (define currency-abbreviation "USD")

     (define (currency-string units hundredths)
       (string-append currency-abbreviation
                      (number->string units)
                      "."
                      (number->string hundredths)))

     (define (french-currency-string units hundredths)
       (let ((currency-abbreviation "FRF"))
         (currency-string units hundredths)))

   According to the rules of lexical scoping, the
`currency-abbreviation' in `currency-string' refers to the variable
location in the innermost environment at that point in the code which
has a binding for `currency-abbreviation', which is the variable
location in the top level environment created by the preceding `(define
currency-abbreviation ...)' expression.

   In Scheme, therefore, the `french-currency-string' procedure does
not work as intended.  The variable binding that it creates for
"currency-abbreviation" is purely local to the code that forms the body
of the `let' expression.  Since this code doesn't directly use the name
"currency-abbreviation" at all, the binding is pointless.

     (french-currency-string 33 44)
     =>
     "USD33.44"

   This begs the question of how the Emacs Lisp behaviour can be
implemented in Scheme.  In general, this is a design question whose
answer depends upon the problem that is being addressed.  In this case,
the best answer may be that `currency-string' should be redesigned so
that it can take an optional third argument.  This third argument, if
supplied, is interpreted as a currency abbreviation that overrides the
default.

   It is possible to change `french-currency-string' so that it mostly
works without changing `currency-string', but the fix is inelegant, and
susceptible to interrupts that could leave the `currency-abbreviation'
variable in the wrong state:

     (define (french-currency-string units hundredths)
       (set! currency-abbreviation "FRF")
       (let ((result (currency-string units hundredths)))
         (set! currency-abbreviation "USD")
         result))

   The key point here is that the code does not create any local binding
for the identifier `currency-abbreviation', so all occurrences of this
identifier refer to the top level variable.


File: guile.info,  Node: Closure,  Next: Serial Number,  Prev: Lexical Scope,  Up: About Closure

14.4.5 Closure
--------------

Consider a `let' expression that doesn't contain any `lambda's:

     (let ((s (/ (+ a b c) 2)))
       (sqrt (* s (- s a) (- s b) (- s c))))

When the Scheme interpreter evaluates this, it

   * creates a new environment with a reference to the environment that
     was current when it encountered the `let'

   * creates a variable binding for `s' in the new environment, with
     value given by `(/ (+ a b c) 2)'

   * evaluates the expression in the body of the `let' in the context of
     the new local environment, and remembers the value `V'

   * forgets the local environment

   * continues evaluating the expression that contained the `let', using
     the value `V' as the value of the `let' expression, in the context
     of the containing environment.

   After the `let' expression has been evaluated, the local environment
that was created is simply forgotten, and there is no longer any way to
access the binding that was created in this environment.  If the same
code is evaluated again, it will follow the same steps again, creating
a second new local environment that has no connection with the first,
and then forgetting this one as well.

   If the `let' body contains a `lambda' expression, however, the local
environment is _not_ forgotten.  Instead, it becomes associated with
the procedure that is created by the `lambda' expression, and is
reinstated every time that that procedure is called.  In detail, this
works as follows.

   * When the Scheme interpreter evaluates a `lambda' expression, to
     create a procedure object, it stores the current environment as
     part of the procedure definition.

   * Then, whenever that procedure is called, the interpreter
     reinstates the environment that is stored in the procedure
     definition and evaluates the procedure body within the context of
     that environment.

   The result is that the procedure body is always evaluated in the
context of the environment that was current when the procedure was
created.

   This is what is meant by "closure".  The next few subsections
present examples that explore the usefulness of this concept.


File: guile.info,  Node: Serial Number,  Next: Shared Variable,  Prev: Closure,  Up: About Closure

14.4.6 Example 1: A Serial Number Generator
-------------------------------------------

This example uses closure to create a procedure with a variable binding
that is private to the procedure, like a local variable, but whose value
persists between procedure calls.

     (define (make-serial-number-generator)
       (let ((current-serial-number 0))
         (lambda ()
           (set! current-serial-number (+ current-serial-number 1))
           current-serial-number)))

     (define entry-sn-generator (make-serial-number-generator))

     (entry-sn-generator)
     =>
     1

     (entry-sn-generator)
     =>
     2

   When `make-serial-number-generator' is called, it creates a local
environment with a binding for `current-serial-number' whose initial
value is 0, then, within this environment, creates a procedure.  The
local environment is stored within the created procedure object and so
persists for the lifetime of the created procedure.

   Every time the created procedure is invoked, it increments the value
of the `current-serial-number' binding in the captured environment and
then returns the current value.

   Note that `make-serial-number-generator' can be called again to
create a second serial number generator that is independent of the
first.  Every new invocation of `make-serial-number-generator' creates
a new local `let' environment and returns a new procedure object with
an association to this environment.


File: guile.info,  Node: Shared Variable,  Next: Callback Closure,  Prev: Serial Number,  Up: About Closure

14.4.7 Example 2: A Shared Persistent Variable
----------------------------------------------

This example uses closure to create two procedures, `get-balance' and
`deposit', that both refer to the same captured local environment so
that they can both access the `balance' variable binding inside that
environment.  The value of this variable binding persists between calls
to either procedure.

   Note that the captured `balance' variable binding is private to
these two procedures: it is not directly accessible to any other code.
It can only be accessed indirectly via `get-balance' or `deposit', as
illustrated by the `withdraw' procedure.

     (define get-balance #f)
     (define deposit #f)

     (let ((balance 0))
       (set! get-balance
             (lambda ()
               balance))
       (set! deposit
             (lambda (amount)
               (set! balance (+ balance amount))
               balance)))

     (define (withdraw amount)
       (deposit (- amount)))

     (get-balance)
     =>
     0

     (deposit 50)
     =>
     50

     (withdraw 75)
     =>
     -25

   An important detail here is that the `get-balance' and `deposit'
variables must be set up by `define'ing them at top level and then
`set!'ing their values inside the `let' body.  Using `define' within
the `let' body would not work: this would create variable bindings
within the local `let' environment that would not be accessible at top
level.


File: guile.info,  Node: Callback Closure,  Next: OO Closure,  Prev: Shared Variable,  Up: About Closure

14.4.8 Example 3: The Callback Closure Problem
----------------------------------------------

A frequently used programming model for library code is to allow an
application to register a callback function for the library to call when
some particular event occurs.  It is often useful for the application to
make several such registrations using the same callback function, for
example if several similar library events can be handled using the same
application code, but the need then arises to distinguish the callback
function calls that are associated with one callback registration from
those that are associated with different callback registrations.

   In languages without the ability to create functions dynamically,
this problem is usually solved by passing a `user_data' parameter on the
registration call, and including the value of this parameter as one of
the parameters on the callback function.  Here is an example of
declarations using this solution in C:

     typedef void (event_handler_t) (int event_type,
                                     void *user_data);

     void register_callback (int event_type,
                             event_handler_t *handler,
                             void *user_data);

   In Scheme, closure can be used to achieve the same functionality
without requiring the library code to store a `user-data' for each
callback registration.

     ;; In the library:

     (define (register-callback event-type handler-proc)
       ...)

     ;; In the application:

     (define (make-handler event-type user-data)
       (lambda ()
         ...
         <code referencing event-type and user-data>
         ...))

     (register-callback event-type
                        (make-handler event-type ...))

   As far as the library is concerned, `handler-proc' is a procedure
with no arguments, and all the library has to do is call it when the
appropriate event occurs.  From the application's point of view, though,
the handler procedure has used closure to capture an environment that
includes all the context that the handler code needs -- `event-type'
and `user-data' -- to handle the event correctly.


File: guile.info,  Node: OO Closure,  Prev: Callback Closure,  Up: About Closure

14.4.9 Example 4: Object Orientation
------------------------------------

Closure is the capture of an environment, containing persistent variable
bindings, within the definition of a procedure or a set of related
procedures.  This is rather similar to the idea in some object oriented
languages of encapsulating a set of related data variables inside an
"object", together with a set of "methods" that operate on the
encapsulated data.  The following example shows how closure can be used
to emulate the ideas of objects, methods and encapsulation in Scheme.

     (define (make-account)
       (let ((balance 0))
         (define (get-balance)
           balance)
         (define (deposit amount)
           (set! balance (+ balance amount))
           balance)
         (define (withdraw amount)
           (deposit (- amount)))

         (lambda args
           (apply
             (case (car args)
               ((get-balance) get-balance)
               ((deposit) deposit)
               ((withdraw) withdraw)
               (else (error "Invalid method!")))
             (cdr args)))))

   Each call to `make-account' creates and returns a new procedure,
created by the expression in the example code that begins "(lambda
args".

     (define my-account (make-account))

     my-account
     =>
     #<procedure args>

   This procedure acts as an account object with methods `get-balance',
`deposit' and `withdraw'.  To apply one of the methods to the account,
you call the procedure with a symbol indicating the required method as
the first parameter, followed by any other parameters that are required
by that method.

     (my-account 'get-balance)
     =>
     0

     (my-account 'withdraw 5)
     =>
     -5

     (my-account 'deposit 396)
     =>
     391

     (my-account 'get-balance)
     =>
     391

   Note how, in this example, both the current balance and the helper
procedures `get-balance', `deposit' and `withdraw', used to implement
the guts of the account object's methods, are all stored in variable
bindings within the private local environment captured by the `lambda'
expression that creates the account object procedure.


File: guile.info,  Node: Further Reading,  Next: Programming Intro,  Prev: Basic Ideas,  Up: Top

15 Further Reading
******************

   * The website `http://www.schemers.org' is a good starting point for
     all things Scheme.

   * Dorai Sitaram's online Scheme tutorial, "Teach Yourself Scheme in
     Fixnum Days", at
     `http://www.ccs.neu.edu/home/dorai/t-y-scheme/t-y-scheme.html'.
     Includes a nice explanation of continuations.

   * The complete text of "Structure and Interpretation of Computer
     Programs", the classic introduction to computer science and Scheme
     by Hal Abelson, Jerry Sussman and Julie Sussman, is now available
     online at `http://mitpress.mit.edu/sicp/sicp.html'.  This site
     also provides teaching materials related to the book, and all the
     source code used in the book, in a form suitable for loading and
     running.


File: guile.info,  Node: Programming Intro,  Next: Libguile Intro,  Prev: Further Reading,  Up: Top

Part III: Guile as an Extension Language
****************************************

In this part of the manual, we aim to present a wide ranging picture of
what it means to use Guile as an application extension language, to
provide guidance, practical guidelines and tips for _how_ to program in
Guile, and to document the tools that are available to help you with
your programming.  For detailed reference information on the variables,
functions etc. that make up Guile's application programming interface
(API), please refer to Part IV (*note Part IV -- Guile API Reference:
Reference Intro.).


File: guile.info,  Node: Libguile Intro,  Next: Programming Overview,  Prev: Programming Intro,  Up: Top

16 Using Guile as an Extension Language
***************************************

The chapters in this part of the manual explain how to use Guile as a
powerful application extension language.

   An important change for the 1.6.x series of Guile releases is that
the GH interface is now deprecated.  For the reasoning behind this
decision, see *Note GH deprecation::.  The GH interface will continue
to be supported for the 1.6.x and 1.8.x release series, but will be
dropped thereafter, so developers are encouraged to switch
progressively to the scm interface.  The last chapter in this part of
the manual (*note GH::) documents both how to use GH and how to switch
from GH to scm.

   The Guile developers believe that clarification of the GH vs. scm
debate, and the consequent deprecation of the GH interface, are in the
long term interests of the project.  However it does create an
unfortunate situation for developers who want to start a project using
Guile and so read the manual to find out how to proceed.  They will
discover that the GH interface, although quite well documented, is
deprecated, but that there is almost no adequate documentation for its
theoretical replacement, the scm interface.  Moreover, the scm interface
still has the odd few rough edges which need smoothing down.

   Therefore, although deprecated, it is quite OK to continue to use
the GH interface if you feel uncomfortable with the `scm_' interface as
it stands today.  By the time that support for GH is dropped, we plan to
have thoroughly documented the `scm_' interface, and to have enhanced it
such that conversion from GH to the `scm_' interface will be very
straightforward, and probably mostly automated.

   As far as documentation of the scm interface is concerned, the
current position is that it is a bit confused, but that the situation
should improve rapidly once the 1.6.0 release is out.  The plan is to
refocus the bulk of Part II, currently "Guile Scheme", as the "Guile API
Reference" so that it covers both Scheme and C interfaces.  (This makes
sense because almost all of Guile's primitive procedures on the Scheme
level -- e.g. `memq' -- are also available as C level primitives in the
scm interface -- e.g. `scm_memq'.)  There will then remain a certain
amount of Scheme-specific (such as the "Basic Ideas" chapter) and
C-specific documentation (such as SMOB usage and interaction with the
garbage collector) to collect into corresponding chapters.


File: guile.info,  Node: Programming Overview,  Next: Data Representation,  Prev: Libguile Intro,  Up: Top

17 An Overview of Guile Programming
***********************************

Guile is designed as an extension language interpreter that is
straightforward to integrate with applications written in C (and C++).
The big win here for the application developer is that Guile
integration, as the Guile web page says, "lowers your project's
hacktivation energy."  Lowering the hacktivation energy means that you,
as the application developer, _and your users_, reap the benefits that
flow from being able to extend the application in a high level
extension language rather than in plain old C.

   In abstract terms, it's difficult to explain what this really means
and what the integration process involves, so instead let's begin by
jumping straight into an example of how you might integrate Guile into
an existing program, and what you could expect to gain by so doing.
With that example under our belts, we'll then return to a more general
analysis of the arguments involved and the range of programming options
available.

* Menu:

* Extending Dia::               How one might extend Dia using Guile.
* Scheme vs C::                 Why Scheme is more hackable than C.
* Testbed Example::             Example: using Guile in a testbed.
* Programming Options::         Options for Guile programming.
* User Programming::            How about application users?


File: guile.info,  Node: Extending Dia,  Next: Scheme vs C,  Up: Programming Overview

17.1 How One Might Extend Dia Using Guile
=========================================

Dia is a free software program for drawing schematic diagrams like flow
charts and floor plans (REFFIXME).  This section conducts the thought
experiment of adding Guile to Dia.  In so doing, it aims to illustrate
several of the steps and considerations involved in adding Guile to
applications in general.

* Menu:

* Dia Objective::               Deciding why you want to add Guile.
* Dia Steps::                   Four steps required to add Guile.
* Dia Smobs::                   How to represent Dia data in Scheme.
* Dia Primitives::              Writing Guile primitives for Dia.
* Dia Hook::                    Providing a hook for Scheme evaluation.
* Dia Structure::               Overall structure for adding Guile.
* Dia Advanced::                Going further with Dia and Guile.


File: guile.info,  Node: Dia Objective,  Next: Dia Steps,  Up: Extending Dia

17.1.1 Deciding Why You Want to Add Guile
-----------------------------------------

First off, you should understand why you want to add Guile to Dia at
all, and that means forming a picture of what Dia does and how it does
it.  So, what are the constituents of the Dia application?

   * Most importantly, the "application domain objects" -- in other
     words, the concepts that differentiate Dia from another
     application such as a word processor or spreadsheet: shapes,
     templates, connectors, pages, plus the properties of all these
     things.

   * The code that manages the graphical face of the application,
     including the layout and display of the objects above.

   * The code that handles input events, which indicate that the
     application user is wanting to do something.

(In other words, a textbook example of the "model - view - controller"
paradigm.)

   Next question: how will Dia benefit once the Guile integration is
complete?  Several (positive!) answers are possible here, and the choice
is obviously up to the application developers.  Still, one answer is
that the main benefit will be the ability to manipulate Dia's
application domain objects from Scheme.

   Suppose that Dia made a set of procedures available in Scheme,
representing the most basic operations on objects such as shapes,
connectors, and so on.  Using Scheme, the application user could then
write code that builds upon these basic operations to create more
complex procedures.  For example, given basic procedures to enumerate
the objects on a page, to determine whether an object is a square, and
to change the fill pattern of a single shape, the user can write a
Scheme procedure to change the fill pattern of all squares on the
current page:

     (define (change-squares'-fill-pattern new-pattern)
       (for-each-shape current-page
         (lambda (shape)
           (if (square? shape)
               (change-fill-pattern shape new-pattern)))))


File: guile.info,  Node: Dia Steps,  Next: Dia Smobs,  Prev: Dia Objective,  Up: Extending Dia

17.1.2 Four Steps Required to Add Guile
---------------------------------------

Assuming this objective, four steps are needed to achieve it.

   First, you need a way of representing your application-specific
objects -- such as `shape' in the previous example -- when they are
passed into the Scheme world.  Unless your objects are so simple that
they map naturally into builtin Scheme data types like numbers and
strings, you will probably want to use Guile's "SMOB" interface to
create a new Scheme data type for your objects.

   Second, you need to write code for the basic operations like
`for-each-shape' and `square?' such that they access and manipulate
your existing data structures correctly, and then make these operations
available as "primitives" on the Scheme level.

   Third, you need to provide some mechanism within the Dia application
that a user can hook into to cause arbitrary Scheme code to be
evaluated.

   Finally, you need to restructure your top-level application C code a
little so that it initializes the Guile interpreter correctly and
declares your "SMOBs" and "primitives" to the Scheme world.

   The following subsections expand on these four points in turn.


File: guile.info,  Node: Dia Smobs,  Next: Dia Primitives,  Prev: Dia Steps,  Up: Extending Dia

17.1.3 How to Represent Dia Data in Scheme
------------------------------------------

For all but the most trivial applications, you will probably want to
allow some representation of your domain objects to exist on the Scheme
level.  This is where the idea of SMOBs comes in, and with it issues of
lifetime management and garbage collection.

   To get more concrete about this, let's look again at the example we
gave earlier of how application users can use Guile to build
higher-level functions from the primitives that Dia itself provides.

     (define (change-squares'-fill-pattern new-pattern)
       (for-each-shape current-page
         (lambda (shape)
           (if (square? shape)
               (change-fill-pattern shape new-pattern)))))

   Consider what is stored here in the variable `shape'.  For each
shape on the current page, the `for-each-shape' primitive calls
`(lambda (shape) ...)' with an argument representing that shape.
Question is: how is that argument represented on the Scheme level?  The
issues are as follows.

   * Whatever the representation, it has to be decodable again by the C
     code for the `square?' and `change-fill-pattern' primitives.  In
     other words, a primitive like `square?' has somehow to be able to
     turn the value that it receives back into something that points to
     the underlying C structure describing a shape.

   * The representation must also cope with Scheme code holding on to
     the value for later use.  What happens if the Scheme code stores
     `shape' in a global variable, but then that shape is deleted (in a
     way that the Scheme code is not aware of), and later on some other
     Scheme code uses that global variable again in a call to, say,
     `square?'?

   * The lifetime and memory allocation of objects that exist _only_ in
     the Scheme world is managed automatically by Guile's garbage
     collector using one simple rule: when there are no remaining
     references to an object, the object is considered dead and so its
     memory is freed.  But for objects that exist in both C and Scheme,
     the picture is more complicated; in the case of Dia, where the
     `shape' argument passes transiently in and out of the Scheme
     world, it would be quite wrong the *delete* the underlying C shape
     just because the Scheme code has finished evaluation.  How do we
     avoid this happening?

   One resolution of these issues is for the Scheme-level
representation of a shape to be a new, Scheme-specific C structure
wrapped up as a SMOB.  The SMOB is what is passed into and out of
Scheme code, and the Scheme-specific C structure inside the SMOB points
to Dia's underlying C structure so that the code for primitives like
`square?' can get at it.

   To cope with an underlying shape being deleted while Scheme code is
still holding onto a Scheme shape value, the underlying C structure
should have a new field that points to the Scheme-specific SMOB.  When a
shape is deleted, the relevant code chains through to the
Scheme-specific structure and sets its pointer back to the underlying
structure to NULL.  Thus the SMOB value for the shape continues to
exist, but any primitive code that tries to use it will detect that the
underlying shape has been deleted because the underlying structure
pointer is NULL.

   So, to summarize the steps involved in this resolution of the problem
(and assuming that the underlying C structure for a shape is `struct
dia_shape'):

   * Define a new Scheme-specific structure that _points_ to the
     underlying C structure:

          struct dia_guile_shape
          {
            struct dia_shape * c_shape;   /* NULL => deleted */
          }

   * Add a field to `struct dia_shape' that points to its `struct
     dia_guile_shape' if it has one --

          struct dia_shape
          {
            ...
            struct dia_guile_shape * guile_shape;
          }

     -- so that C code can set `guile_shape->c_shape' to NULL when the
     underlying shape is deleted.

   * Wrap `struct dia_guile_shape' as a SMOB type.

   * Whenever you need to represent a C shape onto the Scheme level,
     create a SMOB instance for it, and pass that.

   * In primitive code that receives a shape SMOB instance, check the
     `c_shape' field when decoding it, to find out whether the
     underlying C shape is still there.

   As far as memory management is concerned, the SMOB values and their
Scheme-specific structures are under the control of the garbage
collector, whereas the underlying C structures are explicitly managed in
exactly the same way that Dia managed them before we thought of adding
Guile.

   When the garbage collector decides to free a shape SMOB value, it
calls the "SMOB free" function that was specified when defining the
shape SMOB type.  To maintain the correctness of the `guile_shape' field
in the underlying C structure, this function should chain through to the
underlying C structure (if it still exists) and set its `guile_shape'
field to NULL.

   For full documentation on defining and using SMOB types, see *Note
Defining New Types (Smobs)::.


File: guile.info,  Node: Dia Primitives,  Next: Dia Hook,  Prev: Dia Smobs,  Up: Extending Dia

17.1.4 Writing Guile Primitives for Dia
---------------------------------------

Once the details of object representation are decided, writing the
primitive function code that you need is usually straightforward.

   A primitive is simply a C function whose arguments and return value
are all of type `SCM', and whose body does whatever you want it to do.
As an example, here is a possible implementation of the `square?'
primitive:

     #define FUNC_NAME "square?"
     static SCM square_p (SCM shape)
     {
       struct dia_guile_shape * guile_shape;

       /* Check that arg is really a shape SMOB. */
       SCM_VALIDATE_SHAPE (SCM_ARG1, shape);

       /* Access Scheme-specific shape structure. */
       guile_shape = SCM_SMOB_DATA (shape);

       /* Find out if underlying shape exists and is a
          square; return answer as a Scheme boolean. */
       return SCM_BOOL (guile_shape->c_shape &&
                        (guile_shape->c_shape->type == DIA_SQUARE));
     }
     #undef FUNC_NAME

   Notice how easy it is to chain through from the `SCM shape'
parameter that `square_p' receives -- which is a SMOB -- to the
Scheme-specific structure inside the SMOB, and thence to the underlying
C structure for the shape.

   In this code, `SCM_SMOB_DATA' and `SCM_BOOL' are macros from the
standard Guile API.  `SCM_VALIDATE_SHAPE' is a macro that you should
define as part of your SMOB definition: it checks that the passed
parameter is of the expected type.  This is needed to guard against
Scheme code using the `square?' procedure incorrectly, as in `(square?
"hello")'; Scheme's latent typing means that usage errors like this
must be caught at run time.

   Having written the C code for your primitives, you need to make them
available as Scheme procedures by calling the `scm_c_define_gsubr'
function.  `scm_c_define_gsubr' (REFFIXME) takes arguments that specify
the Scheme-level name for the primitive and how many required, optional
and rest arguments it can accept.  The `square?' primitive always
requires exactly one argument, so the call to make it available in
Scheme reads like this:

     scm_c_define_gsubr ("square?", 1, 0, 0, square_p);

   For where to put this call, see the subsection after next on the
structure of Guile-enabled code (*note Dia Structure::).


File: guile.info,  Node: Dia Hook,  Next: Dia Structure,  Prev: Dia Primitives,  Up: Extending Dia

17.1.5 Providing a Hook for the Evaluation of Scheme Code
---------------------------------------------------------

To make the Guile integration useful, you have to design some kind of
hook into your application that application users can use to cause their
Scheme code to be evaluated.

   Technically, this is straightforward; you just have to decide on a
mechanism that is appropriate for your application.  Think of Emacs, for
example: when you type `<ESC> :', you get a prompt where you can type
in any Elisp code, which Emacs will then evaluate.  Or, again like
Emacs, you could provide a mechanism (such as an init file) to allow
Scheme code to be associated with a particular key sequence, and
evaluate the code when that key sequence is entered.

   In either case, once you have the Scheme code that you want to
evaluate, as a null terminated string, you can tell Guile to evaluate
it by calling the `scm_c_eval_string' function.


File: guile.info,  Node: Dia Structure,  Next: Dia Advanced,  Prev: Dia Hook,  Up: Extending Dia

17.1.6 Top-level Structure of Guile-enabled Dia
-----------------------------------------------

Let's assume that the pre-Guile Dia code looks structurally like this:

   * `main ()'

        * do lots of initialization and setup stuff

        * enter Gtk main loop

   When you add Guile to a program, one (rather technical) requirement
is that Guile's garbage collector needs to know where the bottom of the
C stack is.  The easiest way to ensure this is to use `scm_boot_guile'
like this:

   * `main ()'

        * do lots of initialization and setup stuff

        * `scm_boot_guile (argc, argv, inner_main, NULL)'

   * `inner_main ()'

        * define all SMOB types

        * export primitives to Scheme using `scm_c_define_gsubr'

        * enter Gtk main loop

   In other words, you move the guts of what was previously in your
`main' function into a new function called `inner_main', and then add a
`scm_boot_guile' call, with `inner_main' as a parameter, to the end of
`main'.

   Assuming that you are using SMOBs and have written primitive code as
described in the preceding subsections, you also need to insert calls to
declare your new SMOBs and export the primitives to Scheme.  These
declarations must happen _inside_ the dynamic scope of the
`scm_boot_guile' call, but also _before_ any code is run that could
possibly use them -- the beginning of `inner_main' is an ideal place
for this.


File: guile.info,  Node: Dia Advanced,  Prev: Dia Structure,  Up: Extending Dia

17.1.7 Going Further with Dia and Guile
---------------------------------------

The steps described so far implement an initial Guile integration that
already gives a lot of additional power to Dia application users.  But
there are further steps that you could take, and it's interesting to
consider a few of these.

   In general, you could progressively move more of Dia's source code
from C into Scheme.  This might make the code more maintainable and
extensible, and it could open the door to new programming paradigms that
are tricky to effect in C but straightforward in Scheme.

   A specific example of this is that you could use the guile-gtk
package, which provides Scheme-level procedures for most of the Gtk+
library, to move the code that lays out and displays Dia objects from C
to Scheme.

   As you follow this path, it naturally becomes less useful to
maintain a distinction between Dia's original non-Guile-related source
code, and its later code implementing SMOBs and primitives for the
Scheme world.

   For example, suppose that the original source code had a
`dia_change_fill_pattern' function:

     void dia_change_fill_pattern (struct dia_shape * shape,
                                   struct dia_pattern * pattern)
     {
       /* real pattern change work */
     }

   During initial Guile integration, you add a `change_fill_pattern'
primitive for Scheme purposes, which accesses the underlying structures
from its SMOB values and uses `dia_change_fill_pattern' to do the real
work:

     SCM change_fill_pattern (SCM shape, SCM pattern)
     {
       struct dia_shape * d_shape;
       struct dia_pattern * d_pattern;

       ...

       dia_change_fill_pattern (d_shape, d_pattern);

       return SCM_UNSPECIFIED;
     }

   At this point, it makes sense to keep `dia_change_fill_pattern' and
`change_fill_pattern' separate, because `dia_change_fill_pattern' can
also be called without going through Scheme at all, say because the
user clicks a button which causes a C-registered Gtk+ callback to be
called.

   But, if the code for creating buttons and registering their
callbacks is moved into Scheme (using guile-gtk), it may become true
that `dia_change_fill_pattern' can no longer be called other than
through Scheme.  In which case, it makes sense to abolish it and move
its contents directly into `change_fill_pattern', like this:

     SCM change_fill_pattern (SCM shape, SCM pattern)
     {
       struct dia_shape * d_shape;
       struct dia_pattern * d_pattern;

       ...

       /* real pattern change work */

       return SCM_UNSPECIFIED;
     }

   So further Guile integration progressively _reduces_ the amount of
functional C code that you have to maintain over the long term.

   A similar argument applies to data representation.  In the
discussion of SMOBs earlier, issues arose because of the different
memory management and lifetime models that normally apply to data
structures in C and in Scheme.  However, with further Guile
integration, you can resolve this issue in a more radical way by
allowing all your data structures to be under the control of the
garbage collector, and kept alive by references from the Scheme world.
Instead of maintaining an array or linked list of shapes in C, you
would instead maintain a list in Scheme.

   Rather like the coalescing of `dia_change_fill_pattern' and
`change_fill_pattern', the practical upshot of such a change is that
you would no longer have to keep the `dia_shape' and `dia_guile_shape'
structures separate, and so wouldn't need to worry about the pointers
between them.  Instead, you could change the SMOB definition to wrap
the `dia_shape' structure directly, and send `dia_guile_shape' off to
the scrap yard.  Cut out the middle man!

   Finally, we come to the holy grail of Guile's free software /
extension language approach.  Once you have a Scheme representation for
interesting Dia data types like shapes, and a handy bunch of primitives
for manipulating them, it suddenly becomes clear that you have a bundle
of functionality that could have far-ranging use beyond Dia itself.  In
other words, the data types and primitives could now become a library,
and Dia becomes just one of the many possible applications using that
library -- albeit, at this early stage, a rather important one!

   In this model, Guile becomes just the glue that binds everything
together.  Imagine an application that usefully combined functionality
from Dia, Gnumeric and GnuCash -- it's tricky right now, because no
such application yet exists; but it'll happen some day ...


File: guile.info,  Node: Scheme vs C,  Next: Testbed Example,  Prev: Extending Dia,  Up: Programming Overview

17.2 Why Scheme is More Hackable Than C
=======================================

Underlying Guile's value proposition is the assumption that programming
in a high level language, specifically Guile's implementation of Scheme,
is necessarily better in some way than programming in C.  What do we
mean by this claim, and how can we be so sure?

   One class of advantages applies not only to Scheme, but more
generally to any interpretable, high level, scripting language, such as
Emacs Lisp, Python, Ruby, or TeX's macro language.  Common features of
all such languages, when compared to C, are that:

   * They lend themselves to rapid and experimental development cycles,
     owing usually to a combination of their interpretability and the
     integrated development environment in which they are used.

   * They free developers from some of the low level bookkeeping tasks
     associated with C programming, notably memory management.

   * They provide high level features such as container objects and
     exception handling that make common programming tasks easier.

   In the case of Scheme, particular features that make programming
easier -- and more fun! -- are its powerful mechanisms for abstracting
parts of programs (closures -- *note About Closure::) and for iteration
(*note while do::).

   The evidence in support of this argument is empirical: the huge
amount of code that has been written in extension languages for
applications that support this mechanism.  Most notable are extensions
written in Emacs Lisp for GNU Emacs, in TeX's macro language for TeX,
and in Script-Fu for the Gimp, but there is increasingly now a
significant code eco-system for Guile-based applications as well, such
as Lilypond and GnuCash.  It is close to inconceivable that similar
amounts of functionality could have been added to these applications
just by writing new code in their base implementation languages.


File: guile.info,  Node: Testbed Example,  Next: Programming Options,  Prev: Scheme vs C,  Up: Programming Overview

17.3 Example: Using Guile for an Application Testbed
====================================================

As an example of what this means in practice, imagine writing a testbed
for an application that is tested by submitting various requests (via a
C interface) and validating the output received.  Suppose further that
the application keeps an idea of its current state, and that the
"correct" output for a given request may depend on the current
application state.  A complete "white box"(1) test plan for this
application would aim to submit all possible requests in each
distinguishable state, and validate the output for all request/state
combinations.

   To write all this test code in C would be very tedious.  Suppose
instead that the testbed code adds a single new C function, to submit an
arbitrary request and return the response, and then uses Guile to export
this function as a Scheme procedure.  The rest of the testbed can then
be written in Scheme, and so benefits from all the advantages of
programming in Scheme that were described in the previous section.

   (In this particular example, there is an additional benefit of
writing most of the testbed in Scheme.  A common problem for white box
testing is that mistakes and mistaken assumptions in the application
under test can easily be reproduced in the testbed code.  It is more
difficult to copy mistakes like this when the testbed is written in a
different language from the application.)

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

   (1) A "white box" test plan is one that incorporates knowledge of
the internal design of the application under test.


File: guile.info,  Node: Programming Options,  Next: User Programming,  Prev: Testbed Example,  Up: Programming Overview

17.4 A Choice of Programming Options
====================================

The preceding arguments and example point to a model of Guile
programming that is applicable in many cases.  According to this model,
Guile programming involves a balance between C and Scheme programming,
with the aim being to extract the greatest possible Scheme level benefit
from the least amount of C level work.

   The C level work required in this model usually consists of packaging
and exporting functions and application objects such that they can be
seen and manipulated on the Scheme level.  To help with this, Guile's C
language interface includes utility features that aim to make this kind
of integration very easy for the application developer.  These features
are documented later in this part of the manual: see REFFIXME.

   This model, though, is really just one of a range of possible
programming options.  If all of the functionality that you need is
available from Scheme, you could choose instead to write your whole
application in Scheme (or one of the other high level languages that
Guile supports through translation), and simply use Guile as an
interpreter for Scheme.  (In the future, we hope that Guile will also be
able to compile Scheme code, so lessening the performance gap between C
and Scheme code.)  Or, at the other end of the C-Scheme scale, you
could write the majority of your application in C, and only call out to
Guile occasionally for specific actions such as reading a configuration
file or executing a user-specified extension.  The choices boil down to
two basic questions:

   * Which parts of the application do you write in C, and which in
     Scheme (or another high level translated language)?

   * How do you design the interface between the C and Scheme parts of
     your application?

   These are of course design questions, and the right design for any
given application will always depend upon the particular requirements
that you are trying to meet.  In the context of Guile, however, there
are some generally applicable considerations that can help you when
designing your answers.

* Menu:

* Available Functionality::     What functionality is already available?
* Basic Constraints::           Functional and performance constraints.
* Style Choices::               Your preferred programming style.
* Program Control::             What controls program execution?


File: guile.info,  Node: Available Functionality,  Next: Basic Constraints,  Up: Programming Options

17.4.1 What Functionality is Already Available?
-----------------------------------------------

Suppose, for the sake of argument, that you would prefer to write your
whole application in Scheme.  Then the API available to you consists of:

   * standard Scheme

   * plus the extensions to standard Scheme provided by Guile in its
     core distribution

   * plus any additional functionality that you or others have packaged
     so that it can be loaded as a Guile Scheme module.

   A module in the last category can either be a pure Scheme module --
in other words a collection of utility procedures coded in Scheme -- or
a module that provides a Scheme interface to an extension library coded
in C -- in other words a nice package where someone else has done the
work of wrapping up some useful C code for you.  The set of available
modules is growing quickly and already includes such useful examples as
`(gtk gtk)', which makes Gtk+ drawing functions available in Scheme,
and `(database postgres)', which provides SQL access to a Postgres
database.

   Given the growing collection of pre-existing modules, it is quite
feasible that your application could be implemented by combining a
selection of these modules together with new application code written in
Scheme.

   If this approach is not enough, because the functionality that your
application needs is not already available in this form, and it is
impossible to write the new functionality in Scheme, you will need to
write some C code.  If the required function is already available in C
(e.g. in a library), all you need is a little glue to connect it to the
world of Guile.  If not, you need both to write the basic code and to
plumb it into Guile.

   In either case, two general considerations are important.  Firstly,
what is the interface by which the functionality is presented to the
Scheme world?  Does the interface consist only of function calls (for
example, a simple drawing interface), or does it need to include
"objects" of some kind that can be passed between C and Scheme and
manipulated by both worlds.  Secondly, how does the lifetime and memory
management of objects in the C code relate to the garbage collection
governed approach of Scheme objects?  In the case where the basic C
code is not already written, most of the difficulties of memory
management can be avoided by using Guile's C interface features from
the start.

   For the full documentation on writing C code for Guile and connecting
existing C code to the Guile world, see REFFIXME.


File: guile.info,  Node: Basic Constraints,  Next: Style Choices,  Prev: Available Functionality,  Up: Programming Options

17.4.2 Functional and Performance Constraints
---------------------------------------------


File: guile.info,  Node: Style Choices,  Next: Program Control,  Prev: Basic Constraints,  Up: Programming Options

17.4.3 Your Preferred Programming Style
---------------------------------------


File: guile.info,  Node: Program Control,  Prev: Style Choices,  Up: Programming Options

17.4.4 What Controls Program Execution?
---------------------------------------


File: guile.info,  Node: User Programming,  Prev: Programming Options,  Up: Programming Overview

17.5 How About Application Users?
=================================

So far we have considered what Guile programming means for an
application developer.  But what if you are instead _using_ an existing
Guile-based application, and want to know what your options are for
programming and extending this application?

   The answer to this question varies from one application to another,
because the options available depend inevitably on whether the
application developer has provided any hooks for you to hang your own
code on and, if there are such hooks, what they allow you to do.(1)
For example...

   * If the application permits you to load and execute any Guile code,
     the world is your oyster.  You can extend the application in any
     way that you choose.

   * A more cautious application might allow you to load and execute
     Guile code, but only in a "safe" environment, where the interface
     available is restricted by the application from the standard Guile
     API.

   * Or a really fearful application might not provide a hook to really
     execute user code at all, but just use Scheme syntax as a
     convenient way for users to specify application data or
     configuration options.

   In the last two cases, what you can do is, by definition, restricted
by the application, and you should refer to the application's own
manual to find out your options.

   The most well known example of the first case is Emacs, with its
extension language Emacs Lisp: as well as being a text editor, Emacs
supports the loading and execution of arbitrary Emacs Lisp code.  The
result of such openness has been dramatic: Emacs now benefits from
user-contributed Emacs Lisp libraries that extend the basic editing
function to do everything from reading news to psychoanalysis and
playing adventure games.  The only limitation is that extensions are
restricted to the functionality provided by Emacs's built-in set of
primitive operations.  For example, you can interact and display data by
manipulating the contents of an Emacs buffer, but you can't pop-up and
draw a window with a layout that is totally different to the Emacs
standard.

   This situation with a Guile application that supports the loading of
arbitrary user code is similar, except perhaps even more so, because
Guile also supports the loading of extension libraries written in C.
This last point enables user code to add new primitive operations to
Guile, and so to bypass the limitation present in Emacs Lisp.

   At this point, the distinction between an application developer and
an application user becomes rather blurred.  Instead of seeing yourself
as a user extending an application, you could equally well say that you
are developing a new application of your own using some of the primitive
functionality provided by the original application.  As such, all the
discussions of the preceding sections of this chapter are relevant to
how you can proceed with developing your extension.

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

   (1) Of course, in the world of free software, you always have the
freedom to modify the application's source code to your own
requirements.  Here we are concerned with the extension options that the
application has provided for without your needing to modify its source
code.


File: guile.info,  Node: Data Representation,  Next: GH,  Prev: Programming Overview,  Up: Top

18 Data Representation in Guile
*******************************

*by Jim Blandy*

   [Due to the rather non-orthogonal and performance-oriented nature of
the SCM interface, you need to understand SCM internals *before* you
can use the SCM API.  That's why this chapter comes first.]

   [NOTE: this is Jim Blandy's essay almost entirely unmodified.  It
has to be adapted to fit this manual smoothly.]

   In order to make sense of Guile's SCM_ functions, or read libguile's
source code, it's essential to have a good grasp of how Guile actually
represents Scheme values.  Otherwise, a lot of the code, and the
conventions it follows, won't make very much sense.  This essay is meant
to provide the background necessary to read and write C code that
manipulates Scheme values in a way that is compatible with libguile.

   We assume you know both C and Scheme, but we do not assume you are
familiar with Guile's implementation.

* Menu:

* Data Representation in Scheme::       Why things aren't just totally
                                        straightforward, in general terms.
* How Guile does it::                   How to write C code that manipulates
                                        Guile values, with an explanation
                                        of Guile's garbage collector.
* Defining New Types (Smobs)::          How to extend Guile with your own
                                        application-specific datatypes.


File: guile.info,  Node: Data Representation in Scheme,  Next: How Guile does it,  Up: Data Representation

18.1 Data Representation in Scheme
==================================

Scheme is a latently-typed language; this means that the system cannot,
in general, determine the type of a given expression at compile time.
Types only become apparent at run time.  Variables do not have fixed
types; a variable may hold a pair at one point, an integer at the next,
and a thousand-element vector later.  Instead, values, not variables,
have fixed types.

   In order to implement standard Scheme functions like `pair?' and
`string?' and provide garbage collection, the representation of every
value must contain enough information to accurately determine its type
at run time.  Often, Scheme systems also use this information to
determine whether a program has attempted to apply an operation to an
inappropriately typed value (such as taking the `car' of a string).

   Because variables, pairs, and vectors may hold values of any type,
Scheme implementations use a uniform representation for values -- a
single type large enough to hold either a complete value or a pointer
to a complete value, along with the necessary typing information.

   The following sections will present a simple typing system, and then
make some refinements to correct its major weaknesses.  However, this is
not a description of the system Guile actually uses.  It is only an
illustration of the issues Guile's system must address.  We provide all
the information one needs to work with Guile's data in *Note How Guile
does it::.

* Menu:

* A Simple Representation::
* Faster Integers::
* Cheaper Pairs::
* Guile Is Hairier::


File: guile.info,  Node: A Simple Representation,  Next: Faster Integers,  Up: Data Representation in Scheme

18.1.1 A Simple Representation
------------------------------

The simplest way to meet the above requirements in C would be to
represent each value as a pointer to a structure containing a type
indicator, followed by a union carrying the real value.  Assuming that
`SCM' is the name of our universal type, we can write:

     enum type { integer, pair, string, vector, ... };

     typedef struct value *SCM;

     struct value {
       enum type type;
       union {
         int integer;
         struct { SCM car, cdr; } pair;
         struct { int length; char *elts; } string;
         struct { int length; SCM  *elts; } vector;
         ...
       } value;
     };
   with the ellipses replaced with code for the remaining Scheme types.

   This representation is sufficient to implement all of Scheme's
semantics.  If X is an `SCM' value:
   *   To test if X is an integer, we can write `X->type == integer'.

   *   To find its value, we can write `X->value.integer'.

   *   To test if X is a vector, we can write `X->type == vector'.

   *   If we know X is a vector, we can write
     `X->value.vector.elts[0]' to refer to its first element.

   *   If we know X is a pair, we can write   `X->value.pair.car' to
     extract its car.


File: guile.info,  Node: Faster Integers,  Next: Cheaper Pairs,  Prev: A Simple Representation,  Up: Data Representation in Scheme

18.1.2 Faster Integers
----------------------

Unfortunately, the above representation has a serious disadvantage.  In
order to return an integer, an expression must allocate a `struct
value', initialize it to represent that integer, and return a pointer to
it.  Furthermore, fetching an integer's value requires a memory
reference, which is much slower than a register reference on most
processors.  Since integers are extremely common, this representation is
too costly, in both time and space.  Integers should be very cheap to
create and manipulate.

   One possible solution comes from the observation that, on many
architectures, structures must be aligned on a four-byte boundary.
(Whether or not the machine actually requires it, we can write our own
allocator for `struct value' objects that assures this is true.)  In
this case, the lower two bits of the structure's address are known to
be zero.

   This gives us the room we need to provide an improved representation
for integers.  We make the following rules:
   * If the lower two bits of an `SCM' value are zero, then the SCM
     value is a pointer to a `struct value', and everything proceeds as
     before.

   * Otherwise, the `SCM' value represents an integer, whose value
     appears in its upper bits.

   Here is C code implementing this convention:
     enum type { pair, string, vector, ... };

     typedef struct value *SCM;

     struct value {
       enum type type;
       union {
         struct { SCM car, cdr; } pair;
         struct { int length; char *elts; } string;
         struct { int length; SCM  *elts; } vector;
         ...
       } value;
     };

     #define POINTER_P(x) (((int) (x) & 3) == 0)
     #define INTEGER_P(x) (! POINTER_P (x))

     #define GET_INTEGER(x)  ((int) (x) >> 2)
     #define MAKE_INTEGER(x) ((SCM) (((x) << 2) | 1))

   Notice that `integer' no longer appears as an element of `enum
type', and the union has lost its `integer' member.  Instead, we use
the `POINTER_P' and `INTEGER_P' macros to make a coarse classification
of values into integers and non-integers, and do further type testing
as before.

   Here's how we would answer the questions posed above (again, assume
X is an `SCM' value):
   *   To test if X is an integer, we can write `INTEGER_P (X)'.

   *   To find its value, we can write `GET_INTEGER (X)'.

   *   To test if X is a vector, we can write:
            `POINTER_P (X) && X->type == vector'
       Given the new representation, we must make sure X is truly a
     pointer before we dereference it to determine its complete type.

   *   If we know X is a vector, we can write
     `X->value.vector.elts[0]' to refer to its first element, as
     before.

   *   If we know X is a pair, we can write   `X->value.pair.car' to
     extract its car, just as before.

   This representation allows us to operate more efficiently on integers
than the first.  For example, if X and Y are known to be integers, we
can compute their sum as follows:
     MAKE_INTEGER (GET_INTEGER (X) + GET_INTEGER (Y))
   Now, integer math requires no allocation or memory references.  Most
real Scheme systems actually use an even more efficient representation,
but this essay isn't about bit-twiddling.  (Hint: what if pointers had
`01' in their least significant bits, and integers had `00'?)


File: guile.info,  Node: Cheaper Pairs,  Next: Guile Is Hairier,  Prev: Faster Integers,  Up: Data Representation in Scheme

18.1.3 Cheaper Pairs
--------------------

However, there is yet another issue to confront.  Most Scheme heaps
contain more pairs than any other type of object; Jonathan Rees says
that pairs occupy 45% of the heap in his Scheme implementation, Scheme
48.  However, our representation above spends three `SCM'-sized words
per pair -- one for the type, and two for the CAR and CDR.  Is there
any way to represent pairs using only two words?

   Let us refine the convention we established earlier.  Let us assert
that:
   *   If the bottom two bits of an `SCM' value are `#b00', then   it
     is a pointer, as before.

   *   If the bottom two bits are `#b01', then the upper bits are an
     integer.  This is a bit more restrictive than before.

   *   If the bottom two bits are `#b10', then the value, with the
     bottom   two bits masked out, is the address of a pair.

   Here is the new C code:
     enum type { string, vector, ... };

     typedef struct value *SCM;

     struct value {
       enum type type;
       union {
         struct { int length; char *elts; } string;
         struct { int length; SCM  *elts; } vector;
         ...
       } value;
     };

     struct pair {
       SCM car, cdr;
     };

     #define POINTER_P(x) (((int) (x) & 3) == 0)

     #define INTEGER_P(x)  (((int) (x) & 3) == 1)
     #define GET_INTEGER(x)  ((int) (x) >> 2)
     #define MAKE_INTEGER(x) ((SCM) (((x) << 2) | 1))

     #define PAIR_P(x) (((int) (x) & 3) == 2)
     #define GET_PAIR(x) ((struct pair *) ((int) (x) & ~3))

   Notice that `enum type' and `struct value' now only contain
provisions for vectors and strings; both integers and pairs have become
special cases.  The code above also assumes that an `int' is large
enough to hold a pointer, which isn't generally true.

   Our list of examples is now as follows:
   *   To test if X is an integer, we can write `INTEGER_P   (X)'; this
     is as before.

   *   To find its value, we can write `GET_INTEGER (X)', as   before.

   *   To test if X is a vector, we can write:
            `POINTER_P (X) && X->type == vector'
       We must still make sure that X is a pointer to a `struct
     value' before dereferencing it to find its type.

   *   If we know X is a vector, we can write
     `X->value.vector.elts[0]' to refer to its first element, as
     before.

   *   We can write `PAIR_P (X)' to determine if X is a   pair, and
     then write `GET_PAIR (X)->car' to refer to its   car.

   This change in representation reduces our heap size by 15%.  It also
makes it cheaper to decide if a value is a pair, because no memory
references are necessary; it suffices to check the bottom two bits of
the `SCM' value.  This may be significant when traversing lists, a
common activity in a Scheme system.

   Again, most real Scheme systems use a slightly different
implementation; for example, if GET_PAIR subtracts off the low bits of
`x', instead of masking them off, the optimizer will often be able to
combine that subtraction with the addition of the offset of the
structure member we are referencing, making a modified pointer as fast
to use as an unmodified pointer.


File: guile.info,  Node: Guile Is Hairier,  Prev: Cheaper Pairs,  Up: Data Representation in Scheme

18.1.4 Guile Is Hairier
-----------------------

We originally started with a very simple typing system -- each object
has a field that indicates its type.  Then, for the sake of efficiency
in both time and space, we moved some of the typing information directly
into the `SCM' value, and left the rest in the `struct value'.  Guile
itself employs a more complex hierarchy, storing finer and finer
gradations of type information in different places, depending on the
object's coarser type.

   In the author's opinion, Guile could be simplified greatly without
significant loss of efficiency, but the simplified system would still be
more complex than what we've presented above.


File: guile.info,  Node: How Guile does it,  Next: Defining New Types (Smobs),  Prev: Data Representation in Scheme,  Up: Data Representation

18.2 How Guile does it
======================

Here we present the specifics of how Guile represents its data.  We
don't go into complete detail; an exhaustive description of Guile's
system would be boring, and we do not wish to encourage people to write
code which depends on its details anyway.  We do, however, present
everything one need know to use Guile's data.

* Menu:

* General Rules::
* Conservative GC::
* Immediates vs Non-immediates::
* Immediate Datatypes::
* Non-immediate Datatypes::
* Signalling Type Errors::
* Unpacking the SCM type::


File: guile.info,  Node: General Rules,  Next: Conservative GC,  Up: How Guile does it

18.2.1 General Rules
--------------------

Any code which operates on Guile datatypes must `#include' the header
file `<libguile.h>'.  This file contains a definition for the `SCM'
typedef (Guile's universal type, as in the examples above), and
definitions and declarations for a host of macros and functions that
operate on `SCM' values.

   All identifiers declared by `<libguile.h>' begin with `scm_' or
`SCM_'.

   The functions described here generally check the types of their
`SCM' arguments, and signal an error if their arguments are of an
inappropriate type.  Macros generally do not, unless that is their
specified purpose.  You must verify their argument types beforehand, as
necessary.

   Macros and functions that return a boolean value have names ending in
`P' or `_p' (for "predicate").  Those that return a negated boolean
value have names starting with `SCM_N'.  For example, `SCM_IMP (X)' is
a predicate which returns non-zero iff X is an immediate value (an
`IM').  `SCM_NCONSP (X)' is a predicate which returns non-zero iff X is
_not_ a pair object (a `CONS').


File: guile.info,  Node: Conservative GC,  Next: Immediates vs Non-immediates,  Prev: General Rules,  Up: How Guile does it

18.2.2 Conservative Garbage Collection
--------------------------------------

Aside from the latent typing, the major source of constraints on a
Scheme implementation's data representation is the garbage collector.
The collector must be able to traverse every live object in the heap, to
determine which objects are not live.

   There are many ways to implement this, but Guile uses an algorithm
called "mark and sweep".  The collector scans the system's global
variables and the local variables on the stack to determine which
objects are immediately accessible by the C code.  It then scans those
objects to find the objects they point to, et cetera.  The collector
sets a "mark bit" on each object it finds, so each object is traversed
only once.  This process is called "tracing".

   When the collector can find no unmarked objects pointed to by marked
objects, it assumes that any objects that are still unmarked will never
be used by the program (since there is no path of dereferences from any
global or local variable that reaches them) and deallocates them.

   In the above paragraphs, we did not specify how the garbage collector
finds the global and local variables; as usual, there are many different
approaches.  Frequently, the programmer must maintain a list of pointers
to all global variables that refer to the heap, and another list
(adjusted upon entry to and exit from each function) of local variables,
for the collector's benefit.

   The list of global variables is usually not too difficult to
maintain, since global variables are relatively rare.  However, an
explicitly maintained list of local variables (in the author's personal
experience) is a nightmare to maintain.  Thus, Guile uses a technique
called "conservative garbage collection", to make the local variable
list unnecessary.

   The trick to conservative collection is to treat the stack as an
ordinary range of memory, and assume that _every_ word on the stack is
a pointer into the heap.  Thus, the collector marks all objects whose
addresses appear anywhere in the stack, without knowing for sure how
that word is meant to be interpreted.

   Obviously, such a system will occasionally retain objects that are
actually garbage, and should be freed.  In practice, this is not a
problem.  The alternative, an explicitly maintained list of local
variable addresses, is effectively much less reliable, due to programmer
error.

   To accommodate this technique, data must be represented so that the
collector can accurately determine whether a given stack word is a
pointer or not.  Guile does this as follows:

   * Every heap object has a two-word header, called a "cell".  Some
     objects, like pairs, fit entirely in a cell's two words; others may
     store pointers to additional memory in either of the words.  For
     example, strings and vectors store their length in the first word,
     and a pointer to their elements in the second.

   * Guile allocates whole arrays of cells at a time, called "heap
     segments".  These segments are always allocated so that the cells
     they contain fall on eight-byte boundaries, or whatever is
     appropriate for the machine's word size.  Guile keeps all cells in
     a heap segment initialized, whether or not they are currently in
     use.

   * Guile maintains a sorted table of heap segments.

   Thus, given any random word W fetched from the stack, Guile's
garbage collector can consult the table to see if W falls within a
known heap segment, and check W's alignment.  If both tests pass, the
collector knows that W is a valid pointer to a cell, intentional or
not, and proceeds to trace the cell.

   Note that heap segments do not contain all the data Guile uses; cells
for objects like vectors and strings contain pointers to other memory
areas.  However, since those pointers are internal, and not shared among
many pieces of code, it is enough for the collector to find the cell,
and then use the cell's type to find more pointers to trace.


File: guile.info,  Node: Immediates vs Non-immediates,  Next: Immediate Datatypes,  Prev: Conservative GC,  Up: How Guile does it

18.2.3 Immediates vs Non-immediates
-----------------------------------

Guile classifies Scheme objects into two kinds: those that fit entirely
within an `SCM', and those that require heap storage.

   The former class are called "immediates".  The class of immediates
includes small integers, characters, boolean values, the empty list, the
mysterious end-of-file object, and some others.

   The remaining types are called, not surprisingly, "non-immediates".
They include pairs, procedures, strings, vectors, and all other data
types in Guile.

 -- Macro: int SCM_IMP (SCM X)
     Return non-zero iff X is an immediate object.

 -- Macro: int SCM_NIMP (SCM X)
     Return non-zero iff X is a non-immediate object.  This is the
     exact complement of `SCM_IMP', above.

   Note that for versions of Guile prior to 1.4 it was necessary to use
the `SCM_NIMP' macro before calling a finer-grained predicate to
determine X's type, such as `SCM_CONSP' or `SCM_VECTORP'.  This is no
longer required: the definitions of all Guile type predicates now
include a call to `SCM_NIMP' where necessary.


File: guile.info,  Node: Immediate Datatypes,  Next: Non-immediate Datatypes,  Prev: Immediates vs Non-immediates,  Up: How Guile does it

18.2.4 Immediate Datatypes
--------------------------

The following datatypes are immediate values; that is, they fit entirely
within an `SCM' value.  The `SCM_IMP' and `SCM_NIMP' macros will
distinguish these from non-immediates; see *Note Immediates vs
Non-immediates:: for an explanation of the distinction.

   Note that the type predicates for immediate values work correctly on
any `SCM' value; you do not need to call `SCM_IMP' first, to establish
that a value is immediate.

* Menu:

* Integer Data::
* Character Data::
* Boolean Data::
* Unique Values::


File: guile.info,  Node: Integer Data,  Next: Character Data,  Up: Immediate Datatypes

18.2.4.1 Integers
.................

Here are functions for operating on small integers, that fit within an
`SCM'.  Such integers are called "immediate numbers", or "INUMs".  In
general, INUMs occupy all but two bits of an `SCM'.

   Bignums and floating-point numbers are non-immediate objects, and
have their own, separate accessors.  The functions here will not work on
them.  This is not as much of a problem as you might think, however,
because the system never constructs bignums that could fit in an INUM,
and never uses floating point values for exact integers.

 -- Macro: int SCM_INUMP (SCM X)
     Return non-zero iff X is a small integer value.

 -- Macro: int SCM_NINUMP (SCM X)
     The complement of SCM_INUMP.

 -- Macro: int SCM_INUM (SCM X)
     Return the value of X as an ordinary, C integer.  If X is not an
     INUM, the result is undefined.

 -- Macro: SCM SCM_MAKINUM (int I)
     Given a C integer I, return its representation as an `SCM'.  This
     function does not check for overflow.


File: guile.info,  Node: Character Data,  Next: Boolean Data,  Prev: Integer Data,  Up: Immediate Datatypes

18.2.4.2 Characters
...................

Here are functions for operating on characters.

 -- Macro: int SCM_CHARP (SCM X)
     Return non-zero iff X is a character value.

 -- Macro: unsigned int SCM_CHAR (SCM X)
     Return the value of `x' as a C character.  If X is not a Scheme
     character, the result is undefined.

 -- Macro: SCM SCM_MAKE_CHAR (int C)
     Given a C character C, return its representation as a Scheme
     character value.


File: guile.info,  Node: Boolean Data,  Next: Unique Values,  Prev: Character Data,  Up: Immediate Datatypes

18.2.4.3 Booleans
.................

Here are functions and macros for operating on booleans.

 -- Macro: SCM SCM_BOOL_T
 -- Macro: SCM SCM_BOOL_F
     The Scheme true and false values.

 -- Macro: int SCM_NFALSEP (X)
     Convert the Scheme boolean value to a C boolean.  Since every
     object in Scheme except `#f' is true, this amounts to comparing X
     to `#f'; hence the name.

 -- Macro: SCM SCM_BOOL_NOT (X)
     Return the boolean inverse of X.  If X is not a Scheme boolean,
     the result is undefined.


File: guile.info,  Node: Unique Values,  Prev: Boolean Data,  Up: Immediate Datatypes

18.2.4.4 Unique Values
......................

The immediate values that are neither small integers, characters, nor
booleans are all unique values -- that is, datatypes with only one
instance.

 -- Macro: SCM SCM_EOL
     The Scheme empty list object, or "End Of List" object, usually
     written in Scheme as `'()'.

 -- Macro: SCM SCM_EOF_VAL
     The Scheme end-of-file value.  It has no standard written
     representation, for obvious reasons.

 -- Macro: SCM SCM_UNSPECIFIED
     The value returned by expressions which the Scheme standard says
     return an "unspecified" value.

     This is sort of a weirdly literal way to take things, but the
     standard read-eval-print loop prints nothing when the expression
     returns this value, so it's not a bad idea to return this when you
     can't think of anything else helpful.

 -- Macro: SCM SCM_UNDEFINED
     The "undefined" value.  Its most important property is that is not
     equal to any valid Scheme value.  This is put to various internal
     uses by C code interacting with Guile.

     For example, when you write a C function that is callable from
     Scheme and which takes optional arguments, the interpreter passes
     `SCM_UNDEFINED' for any arguments you did not receive.

     We also use this to mark unbound variables.

 -- Macro: int SCM_UNBNDP (SCM X)
     Return true if X is `SCM_UNDEFINED'.  Apply this to a symbol's
     value to see if it has a binding as a global variable.


File: guile.info,  Node: Non-immediate Datatypes,  Next: Signalling Type Errors,  Prev: Immediate Datatypes,  Up: How Guile does it

18.2.5 Non-immediate Datatypes
------------------------------

A non-immediate datatype is one which lives in the heap, either because
it cannot fit entirely within a `SCM' word, or because it denotes a
specific storage location (in the nomenclature of the Revised^5 Report
on Scheme).

   The `SCM_IMP' and `SCM_NIMP' macros will distinguish these from
immediates; see *Note Immediates vs Non-immediates::.

   Given a cell, Guile distinguishes between pairs and other
non-immediate types by storing special "tag" values in a non-pair
cell's car, that cannot appear in normal pairs.  A cell with a non-tag
value in its car is an ordinary pair.  The type of a cell with a tag in
its car depends on the tag; the non-immediate type predicates test this
value.  If a tag value appears elsewhere (in a vector, for example),
the heap may become corrupted.

   Note how the type information for a non-immediate object is split
between the `SCM' word and the cell that the `SCM' word points to.  The
`SCM' word itself only indicates that the object is non-immediate -- in
other words stored in a heap cell.  The tag stored in the first word of
the heap cell indicates more precisely the type of that object.

   The type predicates for non-immediate values work correctly on any
`SCM' value; you do not need to call `SCM_NIMP' first, to establish
that a value is non-immediate.

* Menu:

* Pair Data::
* Vector Data::
* Procedures::
* Closures::
* Subrs::
* Port Data::


File: guile.info,  Node: Pair Data,  Next: Vector Data,  Up: Non-immediate Datatypes

18.2.5.1 Pairs
..............

Pairs are the essential building block of list structure in Scheme.  A
pair object has two fields, called the "car" and the "cdr".

   It is conventional for a pair's CAR to contain an element of a list,
and the CDR to point to the next pair in the list, or to contain
`SCM_EOL', indicating the end of the list.  Thus, a set of pairs
chained through their CDRs constitutes a singly-linked list.  Scheme
and libguile define many functions which operate on lists constructed
in this fashion, so although lists chained through the CARs of pairs
will work fine too, they may be less convenient to manipulate, and
receive less support from the community.

   Guile implements pairs by mapping the CAR and CDR of a pair directly
into the two words of the cell.

 -- Macro: int SCM_CONSP (SCM X)
     Return non-zero iff X is a Scheme pair object.

 -- Macro: int SCM_NCONSP (SCM X)
     The complement of SCM_CONSP.

 -- Macro: void SCM_NEWCELL (SCM INTO)
     Allocate a new cell, and set INTO to point to it.  This macro
     expands to a statement, not an expression, and INTO must be an
     lvalue of type SCM.

     This is the most primitive way to allocate a cell; it is quite
     fast.

     The CAR of the cell initially tags it as a "free cell".  If the
     caller intends to use it as an ordinary cons, she must store
     ordinary SCM values in its CAR and CDR.

     If the caller intends to use it as a header for some other type,
     she must store an appropriate magic value in the cell's CAR, to
     mark it as a member of that type, and store whatever value in the
     CDR that type expects.  You should generally not do this, unless
     you are implementing a new datatype, and thoroughly understand the
     code in `<libguile/tags.h>'.

 -- Functie: SCM scm_cons (SCM CAR, SCM CDR)
     Allocate ("CONStruct") a new pair, with CAR and CDR as its
     contents.

   The macros below perform no type checking.  The results are
undefined if CELL is an immediate.  However, since all non-immediate
Guile objects are constructed from cells, and these macros simply
return the first element of a cell, they actually can be useful on
datatypes other than pairs.  (Of course, it is not very modular to use
them outside of the code which implements that datatype.)

 -- Macro: SCM SCM_CAR (SCM CELL)
     Return the CAR, or first field, of CELL.

 -- Macro: SCM SCM_CDR (SCM CELL)
     Return the CDR, or second field, of CELL.

 -- Macro: void SCM_SETCAR (SCM CELL, SCM X)
     Set the CAR of CELL to X.

 -- Macro: void SCM_SETCDR (SCM CELL, SCM X)
     Set the CDR of CELL to X.

 -- Macro: SCM SCM_CAAR (SCM CELL)
 -- Macro: SCM SCM_CADR (SCM CELL)
 -- Macro: SCM SCM_CDAR (SCM CELL) ...
 -- Macro: SCM SCM_CDDDDR (SCM CELL)
     Return the CAR of the CAR of CELL, the CAR of the CDR of CELL, et
     cetera.


File: guile.info,  Node: Vector Data,  Next: Procedures,  Prev: Pair Data,  Up: Non-immediate Datatypes

18.2.5.2 Vectors, Strings, and Symbols
......................................

Vectors, strings, and symbols have some properties in common.  They all
have a length, and they all have an array of elements.  In the case of a
vector, the elements are `SCM' values; in the case of a string or
symbol, the elements are characters.

   All these types store their length (along with some tagging bits) in
the CAR of their header cell, and store a pointer to the elements in
their CDR.  Thus, the `SCM_CAR' and `SCM_CDR' macros are (somewhat)
meaningful when applied to these datatypes.

 -- Macro: int SCM_VECTORP (SCM X)
     Return non-zero iff X is a vector.

 -- Macro: int SCM_STRINGP (SCM X)
     Return non-zero iff X is a string.

 -- Macro: int SCM_SYMBOLP (SCM X)
     Return non-zero iff X is a symbol.

 -- Macro: int SCM_VECTOR_LENGTH (SCM X)
 -- Macro: int SCM_STRING_LENGTH (SCM X)
 -- Macro: int SCM_SYMBOL_LENGTH (SCM X)
     Return the length of the object X.  The result is undefined if X
     is not a vector, string, or symbol, respectively.

 -- Macro: SCM * SCM_VECTOR_BASE (SCM X)
     Return a pointer to the array of elements of the vector X.  The
     result is undefined if X is not a vector.

 -- Macro: char * SCM_STRING_CHARS (SCM X)
 -- Macro: char * SCM_SYMBOL_CHARS (SCM X)
     Return a pointer to the characters of X.  The result is undefined
     if X is not a symbol or string, respectively.

   There are also a few magic values stuffed into memory before a
symbol's characters, but you don't want to know about those.  What
cruft!


File: guile.info,  Node: Procedures,  Next: Closures,  Prev: Vector Data,  Up: Non-immediate Datatypes

18.2.5.3 Procedures
...................

Guile provides two kinds of procedures: "closures", which are the
result of evaluating a `lambda' expression, and "subrs", which are C
functions packaged up as Scheme objects, to make them available to
Scheme programmers.

   (There are actually other sorts of procedures: compiled closures, and
continuations; see the source code for details about them.)

 -- Functie: SCM scm_procedure_p (SCM X)
     Return `SCM_BOOL_T' iff X is a Scheme procedure object, of any
     sort.  Otherwise, return `SCM_BOOL_F'.


File: guile.info,  Node: Closures,  Next: Subrs,  Prev: Procedures,  Up: Non-immediate Datatypes

18.2.5.4 Closures
.................

[FIXME: this needs to be further subbed, but texinfo has no subsubsub]

   A closure is a procedure object, generated as the value of a
`lambda' expression in Scheme.  The representation of a closure is
straightforward -- it contains a pointer to the code of the lambda
expression from which it was created, and a pointer to the environment
it closes over.

   In Guile, each closure also has a property list, allowing the system
to store information about the closure.  I'm not sure what this is used
for at the moment -- the debugger, maybe?

 -- Macro: int SCM_CLOSUREP (SCM X)
     Return non-zero iff X is a closure.

 -- Macro: SCM SCM_PROCPROPS (SCM X)
     Return the property list of the closure X.  The results are
     undefined if X is not a closure.

 -- Macro: void SCM_SETPROCPROPS (SCM X, SCM P)
     Set the property list of the closure X to P.  The results are
     undefined if X is not a closure.

 -- Macro: SCM SCM_CODE (SCM X)
     Return the code of the closure X.  The result is undefined if X is
     not a closure.

     This function should probably only be used internally by the
     interpreter, since the representation of the code is intimately
     connected with the interpreter's implementation.

 -- Macro: SCM SCM_ENV (SCM X)
     Return the environment enclosed by X.  The result is undefined if
     X is not a closure.

     This function should probably only be used internally by the
     interpreter, since the representation of the environment is
     intimately connected with the interpreter's implementation.


File: guile.info,  Node: Subrs,  Next: Port Data,  Prev: Closures,  Up: Non-immediate Datatypes

18.2.5.5 Subrs
..............

[FIXME: this needs to be further subbed, but texinfo has no subsubsub]

   A subr is a pointer to a C function, packaged up as a Scheme object
to make it callable by Scheme code.  In addition to the function
pointer, the subr also contains a pointer to the name of the function,
and information about the number of arguments accepted by the C
function, for the sake of error checking.

   There is no single type predicate macro that recognizes subrs, as
distinct from other kinds of procedures.  The closest thing is
`scm_procedure_p'; see *Note Procedures::.

 -- Macro: char * SCM_SNAME (X)
     Return the name of the subr X.  The result is undefined if X is
     not a subr.

 -- Functie: SCM scm_c_define_gsubr (char *NAME, int REQ, int OPT, int
          REST, SCM (*FUNCTION)())
     Create a new subr object named NAME, based on the C function
     FUNCTION, make it visible to Scheme the value of as a global
     variable named NAME, and return the subr object.

     The subr object accepts REQ required arguments, OPT optional
     arguments, and a REST argument iff REST is non-zero.  The C
     function FUNCTION should accept `REQ + OPT' arguments, or `REQ +
     OPT + 1' arguments if `rest' is non-zero.

     When a subr object is applied, it must be applied to at least REQ
     arguments, or else Guile signals an error.  FUNCTION receives the
     subr's first REQ arguments as its first REQ arguments.  If there
     are fewer than OPT arguments remaining, then FUNCTION receives the
     value `SCM_UNDEFINED' for any missing optional arguments.  If RST
     is non-zero, then any arguments after the first `REQ + OPT' are
     packaged up as a list as passed as FUNCTION's last argument.

     Note that subrs can actually only accept a predefined set of
     combinations of required, optional, and rest arguments.  For
     example, a subr can take one required argument, or one required
     and one optional argument, but a subr can't take one required and
     two optional arguments.  It's bizarre, but that's the way the
     interpreter was written.  If the arguments to `scm_c_define_gsubr'
     do not fit one of the predefined patterns, then
     `scm_c_define_gsubr' will return a compiled closure object instead
     of a subr object.


File: guile.info,  Node: Port Data,  Prev: Subrs,  Up: Non-immediate Datatypes

18.2.5.6 Ports
..............

Haven't written this yet, 'cos I don't understand ports yet.


File: guile.info,  Node: Signalling Type Errors,  Next: Unpacking the SCM type,  Prev: Non-immediate Datatypes,  Up: How Guile does it

18.2.6 Signalling Type Errors
-----------------------------

Every function visible at the Scheme level should aggressively check the
types of its arguments, to avoid misinterpreting a value, and perhaps
causing a segmentation fault.  Guile provides some macros to make this
easier.

 -- Macro: void SCM_ASSERT (int TEST, SCM OBJ, unsigned int POSITION,
          const char *SUBR)
     If TEST is zero, signal a "wrong type argument" error, attributed
     to the subroutine named SUBR, operating on the value OBJ, which is
     the POSITION'th argument of SUBR.

 -- Macro: int SCM_ARG1
 -- Macro: int SCM_ARG2
 -- Macro: int SCM_ARG3
 -- Macro: int SCM_ARG4
 -- Macro: int SCM_ARG5
 -- Macro: int SCM_ARG6
 -- Macro: int SCM_ARG7
     One of the above values can be used for POSITION to indicate the
     number of the argument of SUBR which is being checked.
     Alternatively, a positive integer number can be used, which allows
     to check arguments after the seventh.  However, for parameter
     numbers up to seven it is preferable to use `SCM_ARGN' instead of
     the corresponding raw number, since it will make the code easier to
     understand.

 -- Macro: int SCM_ARGn
     Passing a value of zero or `SCM_ARGn' for POSITION allows to leave
     it unspecified which argument's type is incorrect.  Again,
     `SCM_ARGn' should be preferred over a raw zero constant.


File: guile.info,  Node: Unpacking the SCM type,  Prev: Signalling Type Errors,  Up: How Guile does it

18.2.7 Unpacking the SCM Type
-----------------------------

The previous sections have explained how `SCM' values can refer to
immediate and non-immediate Scheme objects.  For immediate objects, the
complete object value is stored in the `SCM' word itself, while for
non-immediates, the `SCM' word contains a pointer to a heap cell, and
further information about the object in question is stored in that
cell.  This section describes how the `SCM' type is actually
represented and used at the C level.

   In fact, there are two basic C data types to represent objects in
Guile:

 -- Data type: SCM
     `SCM' is the user level abstract C type that is used to represent
     all of Guile's Scheme objects, no matter what the Scheme object
     type is.  No C operation except assignment is guaranteed to work
     with variables of type `SCM', so you should only use macros and
     functions to work with `SCM' values.  Values are converted between
     C data types and the `SCM' type with utility functions and macros.
   
 -- Data type: scm_t_bits
     `scm_t_bits' is an integral data type that is guaranteed to be
     large enough to hold all information that is required to represent
     any Scheme object.  While this data type is mostly used to
     implement Guile's internals, the use of this type is also
     necessary to write certain kinds of extensions to Guile.

* Menu:

* Relationship between SCM and scm_t_bits::
* Immediate objects::
* Non-immediate objects::
* Heap Cell Type Information::
* Accessing Cell Entries::
* Basic Rules for Accessing Cell Entries::


File: guile.info,  Node: Relationship between SCM and scm_t_bits,  Next: Immediate objects,  Up: Unpacking the SCM type

18.2.7.1 Relationship between `SCM' and `scm_t_bits'
....................................................

A variable of type `SCM' is guaranteed to hold a valid Scheme object.
A variable of type `scm_t_bits', on the other hand, may hold a
representation of a `SCM' value as a C integral type, but may also hold
any C value, even if it does not correspond to a valid Scheme object.

   For a variable X of type `SCM', the Scheme object's type information
is stored in a form that is not directly usable.  To be able to work on
the type encoding of the scheme value, the `SCM' variable has to be
transformed into the corresponding representation as a `scm_t_bits'
variable Y by using the `SCM_UNPACK' macro.  Once this has been done,
the type of the scheme object X can be derived from the content of the
bits of the `scm_t_bits' value Y, in the way illustrated by the example
earlier in this chapter (*note Cheaper Pairs::).  Conversely, a valid
bit encoding of a Scheme value as a `scm_t_bits' variable can be
transformed into the corresponding `SCM' value using the `SCM_PACK'
macro.

 -- Macro: scm_t_bits SCM_UNPACK (SCM X)
     Transforms the `SCM' value X into its representation as an
     integral type.  Only after applying `SCM_UNPACK' it is possible to
     access the bits and contents of the `SCM' value.

 -- Macro: SCM SCM_PACK (scm_t_bits X)
     Takes a valid integral representation of a Scheme object and
     transforms it into its representation as a `SCM' value.


File: guile.info,  Node: Immediate objects,  Next: Non-immediate objects,  Prev: Relationship between SCM and scm_t_bits,  Up: Unpacking the SCM type

18.2.7.2 Immediate objects
..........................

A Scheme object may either be an immediate, i.e. carrying all necessary
information by itself, or it may contain a reference to a "cell" with
additional information on the heap.  Although in general it should be
irrelevant for user code whether an object is an immediate or not,
within Guile's own code the distinction is sometimes of importance.
Thus, the following low level macro is provided:

 -- Macro: int SCM_IMP (SCM X)
     A Scheme object is an immediate if it fulfills the `SCM_IMP'
     predicate, otherwise it holds an encoded reference to a heap cell.
     The result of the predicate is delivered as a C style boolean
     value.  User code and code that extends Guile should normally not
     be required to use this macro.

Summary:
   * Given a Scheme object X of unknown type, check first with `SCM_IMP
     (X)' if it is an immediate object.

   * If so, all of the type and value information can be determined
     from the `scm_t_bits' value that is delivered by `SCM_UNPACK (X)'.


File: guile.info,  Node: Non-immediate objects,  Next: Heap Cell Type Information,  Prev: Immediate objects,  Up: Unpacking the SCM type

18.2.7.3 Non-immediate objects
..............................

A Scheme object of type `SCM' that does not fulfill the `SCM_IMP'
predicate holds an encoded reference to a heap cell.  This reference
can be decoded to a C pointer to a heap cell using the `SCM2PTR' macro.
The encoding of a pointer to a heap cell into a `SCM' value is done
using the `PTR2SCM' macro.

 -- Macro: (scm_t_cell *) SCM2PTR (SCM X)
     Extract and return the heap cell pointer from a non-immediate `SCM'
     object X.

 -- Macro: SCM PTR2SCM (scm_t_cell * X)
     Return a `SCM' value that encodes a reference to the heap cell
     pointer X.

   Note that it is also possible to transform a non-immediate `SCM'
value by using `SCM_UNPACK' into a `scm_t_bits' variable.  However, the
result of `SCM_UNPACK' may not be used as a pointer to a `scm_t_cell':
only `SCM2PTR' is guaranteed to transform a `SCM' object into a valid
pointer to a heap cell.  Also, it is not allowed to apply `PTR2SCM' to
anything that is not a valid pointer to a heap cell.

Summary:
   * Only use `SCM2PTR' on `SCM' values for which `SCM_IMP' is false!

   * Don't use `(scm_t_cell *) SCM_UNPACK (X)'!  Use `SCM2PTR (X)'
     instead!

   * Don't use `PTR2SCM' for anything but a cell pointer!


File: guile.info,  Node: Heap Cell Type Information,  Next: Accessing Cell Entries,  Prev: Non-immediate objects,  Up: Unpacking the SCM type

18.2.7.4 Heap Cell Type Information
...................................

Heap cells contain a number of entries, each of which is either a scheme
object of type `SCM' or a raw C value of type `scm_t_bits'.  Which of
the cell entries contain Scheme objects and which contain raw C values
is determined by the first entry of the cell, which holds the cell type
information.

 -- Macro: scm_t_bits SCM_CELL_TYPE (SCM X)
     For a non-immediate Scheme object X, deliver the content of the
     first entry of the heap cell referenced by X.  This value holds
     the information about the cell type.

 -- Macro: void SCM_SET_CELL_TYPE (SCM X, scm_t_bits T)
     For a non-immediate Scheme object X, write the value T into the
     first entry of the heap cell referenced by X.  The value T must
     hold a valid cell type.


File: guile.info,  Node: Accessing Cell Entries,  Next: Basic Rules for Accessing Cell Entries,  Prev: Heap Cell Type Information,  Up: Unpacking the SCM type

18.2.7.5 Accessing Cell Entries
...............................

For a non-immediate Scheme object X, the object type can be determined
by reading the cell type entry using the `SCM_CELL_TYPE' macro.  For
each different type of cell it is known which cell entries hold Scheme
objects and which cell entries hold raw C data.  To access the
different cell entries appropriately, the following macros are provided.

 -- Macro: scm_t_bits SCM_CELL_WORD (SCM X, unsigned int N)
     Deliver the cell entry N of the heap cell referenced by the
     non-immediate Scheme object X as raw data.  It is illegal, to
     access cell entries that hold Scheme objects by using these
     macros.  For convenience, the following macros are also provided.
        * SCM_CELL_WORD_0 (X) => SCM_CELL_WORD (X, 0)

        * SCM_CELL_WORD_1 (X) => SCM_CELL_WORD (X, 1)

        * ...

        * SCM_CELL_WORD_N (X) => SCM_CELL_WORD (X, N)

 -- Macro: SCM SCM_CELL_OBJECT (SCM X, unsigned int N)
     Deliver the cell entry N of the heap cell referenced by the
     non-immediate Scheme object X as a Scheme object.  It is illegal,
     to access cell entries that do not hold Scheme objects by using
     these macros.  For convenience, the following macros are also
     provided.
        * SCM_CELL_OBJECT_0 (X) => SCM_CELL_OBJECT (X, 0)

        * SCM_CELL_OBJECT_1 (X) => SCM_CELL_OBJECT (X, 1)

        * ...

        * SCM_CELL_OBJECT_N (X) => SCM_CELL_OBJECT (X, N)

 -- Macro: void SCM_SET_CELL_WORD (SCM X, unsigned int N, scm_t_bits W)
     Write the raw C value W into entry number N of the heap cell
     referenced by the non-immediate Scheme value X.  Values that are
     written into cells this way may only be read from the cells using
     the `SCM_CELL_WORD' macros or, in case cell entry 0 is written,
     using the `SCM_CELL_TYPE' macro.  For the special case of cell
     entry 0 it has to be made sure that W contains a cell type
     information which does not describe a Scheme object.  For
     convenience, the following macros are also provided.
        * SCM_SET_CELL_WORD_0 (X, W) => SCM_SET_CELL_WORD (X, 0, W)

        * SCM_SET_CELL_WORD_1 (X, W) => SCM_SET_CELL_WORD (X, 1, W)

        * ...

        * SCM_SET_CELL_WORD_N (X, W) => SCM_SET_CELL_WORD (X, N, W)

 -- Macro: void SCM_SET_CELL_OBJECT (SCM X, unsigned int N, SCM O)
     Write the Scheme object O into entry number N of the heap cell
     referenced by the non-immediate Scheme value X.  Values that are
     written into cells this way may only be read from the cells using
     the `SCM_CELL_OBJECT' macros or, in case cell entry 0 is written,
     using the `SCM_CELL_TYPE' macro.  For the special case of cell
     entry 0 the writing of a Scheme object into this cell is only
     allowed if the cell forms a Scheme pair.  For convenience, the
     following macros are also provided.
        * SCM_SET_CELL_OBJECT_0 (X, O) => SCM_SET_CELL_OBJECT (X, 0, O)

        * SCM_SET_CELL_OBJECT_1 (X, O) => SCM_SET_CELL_OBJECT (X, 1, O)

        * ...

        * SCM_SET_CELL_OBJECT_N (X, O) => SCM_SET_CELL_OBJECT (X, N, O)

Summary:
   * For a non-immediate Scheme object X of unknown type, get the type
     information by using `SCM_CELL_TYPE (X)'.

   * As soon as the cell type information is available, only use the
     appropriate access methods to read and write data to the different
     cell entries.


File: guile.info,  Node: Basic Rules for Accessing Cell Entries,  Prev: Accessing Cell Entries,  Up: Unpacking the SCM type

18.2.7.6 Basic Rules for Accessing Cell Entries
...............................................

For each cell type it is generally up to the implementation of that type
which of the corresponding cell entries hold Scheme objects and which
hold raw C values.  However, there is one basic rule that has to be
followed: Scheme pairs consist of exactly two cell entries, which both
contain Scheme objects.  Further, a cell which contains a Scheme object
in it first entry has to be a Scheme pair.  In other words, it is not
allowed to store a Scheme object in the first cell entry and a non
Scheme object in the second cell entry.

 -- Macro: int SCM_CONSP (SCM X)
     Determine, whether the Scheme object X is a Scheme pair, i.e.
     whether X references a heap cell consisting of exactly two
     entries, where both entries contain a Scheme object.  In this
     case, both entries will have to be accessed using the
     `SCM_CELL_OBJECT' macros.  On the contrary, if the `SCM_CONSP'
     predicate is not fulfilled, the first entry of the Scheme cell is
     guaranteed not to be a Scheme value and thus the first cell entry
     must be accessed using the `SCM_CELL_WORD_0' macro.


File: guile.info,  Node: Defining New Types (Smobs),  Prev: How Guile does it,  Up: Data Representation

18.3 Defining New Types (Smobs)
===============================

"Smobs" are Guile's mechanism for adding new non-immediate types to the
system.(1)  To define a new smob type, the programmer provides Guile
with some essential information about the type -- how to print it, how
to garbage collect it, and so on -- and Guile returns a fresh type tag
for use in the first word of new cells.  The programmer can then use
`scm_c_define_gsubr' to make a set of C functions that create and
operate on these objects visible to Scheme code.

   (You can find a complete version of the example code used in this
section in the Guile distribution, in `doc/example-smob'.  That
directory includes a makefile and a suitable `main' function, so you
can build a complete interactive Guile shell, extended with the
datatypes described here.)

* Menu:

* Describing a New Type::
* Creating Instances::
* Type checking::
* Garbage Collecting Smobs::
* A Common Mistake In Allocating Smobs::
* Garbage Collecting Simple Smobs::
* A Complete Example::

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

   (1) The term "smob" was coined by Aubrey Jaffer, who says it comes
from "small object", referring to the fact that only the CDR and part
of the CAR of a smob's cell are available for use.


File: guile.info,  Node: Describing a New Type,  Next: Creating Instances,  Up: Defining New Types (Smobs)

18.3.1 Describing a New Type
----------------------------

To define a new type, the programmer must write four functions to
manage instances of the type:

`mark'
     Guile will apply this function to each instance of the new type it
     encounters during garbage collection.  This function is
     responsible for telling the collector about any other
     non-immediate objects the object refers to.  The default smob mark
     function is to not mark any data.  *Note Garbage Collecting
     Smobs::, for more details.

`free'
     Guile will apply this function to each instance of the new type it
     could not find any live pointers to.  The function should release
     all resources held by the object and return the number of bytes
     released.  This is analogous to the Java finalization method- it
     is invoked at an unspecified time (when garbage collection occurs)
     after the object is dead.  The default free function frees the
     smob data (if the size of the struct passed to
     `scm_make_smob_type' is non-zero) using `scm_must_free' and
     returns the size of that struct.  *Note Garbage Collecting
     Smobs::, for more details.

`print'
     Guile will apply this function to each instance of the new type to
     print the value, as for `display' or `write'.  The function should
     write a printed representation of EXP on PORT, in accordance with
     the parameters in PSTATE.  (For more information on print states,
     see *Note Port Data::.)  The default print function prints `#<NAME
     ADDRESS>' where `NAME' is the first argument passed to
     `scm_make_smob_type'.

`equalp'
     If Scheme code asks the `equal?' function to compare two instances
     of the same smob type, Guile calls this function.  It should return
     `SCM_BOOL_T' if A and B should be considered `equal?', or
     `SCM_BOOL_F' otherwise.  If `equalp' is `NULL', `equal?' will
     assume that two instances of this type are never `equal?' unless
     they are `eq?'.


   To actually register the new smob type, call `scm_make_smob_type':

 -- Functie: scm_t_bits scm_make_smob_type (const char *name, size_t
          size)
     This function implements the standard way of adding a new smob
     type, named NAME, with instance size SIZE, to the system.  The
     return value is a tag that is used in creating instances of the
     type.  If SIZE is 0, then no memory will be allocated when
     instances of the smob are created, and nothing will be freed by
     the default free function.  Default values are provided for mark,
     free, print, and, equalp, as described above.  If you want to
     customize any of these functions, the call to `scm_make_smob_type'
     should be immediately followed by calls to one or several of
     `scm_set_smob_mark', `scm_set_smob_free', `scm_set_smob_print',
     and/or `scm_set_smob_equalp'.

   Each of the below `scm_set_smob_XXX' functions registers a smob
special function for a given type.  Each function is intended to be used
only zero or one time per type, and the call should be placed
immediately following the call to `scm_make_smob_type'.

 -- Functie: void scm_set_smob_mark (scm_t_bits tc, SCM (*mark) (SCM))
     This function sets the smob marking procedure for the smob type
     specified by the tag TC. TC is the tag returned by
     `scm_make_smob_type'.

 -- Functie: void scm_set_smob_free (scm_t_bits tc, size_t (*free)
          (SCM))
     This function sets the smob freeing procedure for the smob type
     specified by the tag TC. TC is the tag returned by
     `scm_make_smob_type'.

 -- Functie: void scm_set_smob_print (scm_t_bits tc, int (*print) (SCM,
          SCM, scm_print_state*))
     This function sets the smob printing procedure for the smob type
     specified by the tag TC. TC is the tag returned by
     `scm_make_smob_type'.

 -- Functie: void scm_set_smob_equalp (scm_t_bits tc, SCM (*equalp)
          (SCM, SCM))
     This function sets the smob equality-testing predicate for the
     smob type specified by the tag TC. TC is the tag returned by
     `scm_make_smob_type'.

   In versions 1.4 and earlier, there was another way of creating smob
types, using `scm_make_smob_type_mfpe'.  This function is now
deprecated and will be removed in a future version of Guile.  You should
use the mechanism described above for new code, and change old code not
to use deprecated features.

   Instead of using `scm_make_smob_type' and calling each of the
individual `scm_set_smob_XXX' functions to register each special
function independently, you could use `scm_make_smob_type_mfpe' to
register all of the special functions at once as you create the smob
type

 -- Functie: long scm_make_smob_type_mfpe (const char *name, size_t
          size, SCM (*mark) (SCM), size_t (*free) (SCM), int (*print)
          (SCM, SCM, scm_print_state*), SCM (*equalp) (SCM, SCM))
     This function invokes `scm_make_smob_type' on its first two
     arguments to add a new smob type named NAME, with instance size
     SIZE to the system.  It also registers the MARK, FREE, PRINT,
     EQUALP smob special functions for that new type.  Any of these
     parameters can be `NULL' to have that special function use the
     default behavior for guile.  The return value is a tag that is
     used in creating instances of the type.  If SIZE is 0, then no
     memory will be allocated when instances of the smob are created,
     and nothing will be freed by the default free function.

   For example, here is how one might declare and register a new type
representing eight-bit gray-scale images:

     #include <libguile.h>

     static scm_t_bits image_tag;

     void
     init_image_type (void)
     {
       image_tag = scm_make_smob_type ("image", sizeof (struct image));
       scm_set_smob_mark (image_tag, mark_image);
       scm_set_smob_free (image_tag, free_image);
       scm_set_smob_print (image_tag, print_image);
     }


File: guile.info,  Node: Creating Instances,  Next: Type checking,  Prev: Describing a New Type,  Up: Defining New Types (Smobs)

18.3.2 Creating Instances
-------------------------

Like other non-immediate types, smobs start with a cell whose first word
contains typing information, and whose remaining words are free for any
use.

   After the header word containing the type code, smobs can have either
one, two or three additional words of data. These words store either a
pointer to the internal C structure holding the smob-specific data, or
the smob data itself.  To create an instance of a smob type following
these standards, you should use `SCM_NEWSMOB', `SCM_NEWSMOB2' or
`SCM_NEWSMOB3':(1)

 -- Macro: void SCM_NEWSMOB (SCM value, scm_t_bits tag, void *data)
 -- Macro: void SCM_NEWSMOB2 (SCM value, scm_t_bits tag, void *data1,
          void *data2)
 -- Macro: void SCM_NEWSMOB3 (SCM value, scm_t_bits tag, void *data1,
          void *data2, void *data3)
     Make VALUE contain a smob instance of the type with tag TAG and
     smob data DATA (or DATA1, DATA2, and DATA3).  VALUE must be
     previously declared as C type `SCM'.

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

 -- Macro: fn_returns SCM_RETURN_NEWSMOB (scm_t_bits tag, void *data)
 -- Macro: fn_returns SCM_RETURN_NEWSMOB2 (scm_t_bits tag, void *data1,
          void *data2)
 -- Macro: fn_returns SCM_RETURN_NEWSMOB3 (scm_t_bits tag, void *data1,
          void *data2, void *data3)
     This macro expands to a block of code that creates a smob instance
     of the type with tag TAG and smob data DATA (or DATA1, DATA2, and
     DATA3), and causes the surrounding function to return that `SCM'
     value.  It should be the last piece of code in a block.

   Guile provides the following functions for managing memory, which are
often helpful when implementing smobs:

 -- Functie: char * scm_must_malloc (size_t LEN, char *WHAT)
     Allocate LEN bytes of memory, using `malloc', and return a pointer
     to them.

     If there is not enough memory available, invoke the garbage
     collector, and try once more.  If there is still not enough,
     signal an error, reporting that we could not allocate WHAT.

     This function also helps maintain statistics about the size of the
     heap.

 -- Functie: char * scm_must_realloc (char *ADDR, size_t OLEN, size_t
          LEN, char *WHAT)
     Resize (and possibly relocate) the block of memory at ADDR, to
     have a size of LEN bytes, by calling `realloc'.  Return a pointer
     to the new block.

     If there is not enough memory available, invoke the garbage
     collector, and try once more.  If there is still not enough,
     signal an error, reporting that we could not allocate WHAT.

     The value OLEN should be the old size of the block of memory at
     ADDR; it is only used for keeping statistics on the size of the
     heap.

 -- Functie: void scm_must_free (char *ADDR)
     Free the block of memory at ADDR, using `free'.  If ADDR is zero,
     signal an error, complaining of an attempt to free something that
     is already free.

     This does no record-keeping; instead, the smob's `free' function
     must take care of that.

     This function isn't usually sufficiently different from the usual
     `free' function to be worth using.

   Continuing the above example, if the global variable `image_tag'
contains a tag returned by `scm_make_smob_type', here is how we could
construct a smob whose CDR contains a pointer to a freshly allocated
`struct image':

     struct image {
       int width, height;
       char *pixels;

       /* The name of this image */
       SCM name;

       /* A function to call when this image is
          modified, e.g., to update the screen,
          or SCM_BOOL_F if no action necessary */
       SCM update_func;
     };

     SCM
     make_image (SCM name, SCM s_width, SCM s_height)
     {
       struct image *image;
       int width, height;

       SCM_ASSERT (SCM_STRINGP (name), name, SCM_ARG1, "make-image");
       SCM_ASSERT (SCM_INUMP (s_width),  s_width,  SCM_ARG2, "make-image");
       SCM_ASSERT (SCM_INUMP (s_height), s_height, SCM_ARG3, "make-image");

       width = SCM_INUM (s_width);
       height = SCM_INUM (s_height);

       image = (struct image *) scm_must_malloc (sizeof (struct image), "image");
       image->width = width;
       image->height = height;
       image->pixels = scm_must_malloc (width * height, "image pixels");
       image->name = name;
       image->update_func = SCM_BOOL_F;

       SCM_RETURN_NEWSMOB (image_tag, image);
     }

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

   (1) The `SCM_NEWSMOB2' and `SCM_NEWSMOB3' variants will allocate
double cells and thus use twice as much memory as smobs created by
`SCM_NEWSMOB'.


File: guile.info,  Node: Type checking,  Next: Garbage Collecting Smobs,  Prev: Creating Instances,  Up: Defining New Types (Smobs)

18.3.3 Type checking
--------------------

Functions that operate on smobs should aggressively check the types of
their arguments, to avoid misinterpreting some other datatype as a smob,
and perhaps causing a segmentation fault.  Fortunately, this is pretty
simple to do.  The function need only verify that its argument is a
non-immediate, whose first word is the type tag returned by
`scm_make_smob_type'.

   For example, here is a simple function that operates on an image
smob, and checks the type of its argument.  We also present an expanded
version of the `init_image_type' function, to make `clear_image' and
the image constructor function `make_image' visible to Scheme code.

     SCM
     clear_image (SCM image_smob)
     {
       int area;
       struct image *image;

       SCM_ASSERT (SCM_SMOB_PREDICATE (image_tag, image_smob),
                   image_smob, SCM_ARG1, "clear-image");

       image = (struct image *) SCM_SMOB_DATA (image_smob);
       area = image->width * image->height;
       memset (image->pixels, 0, area);

       /* Invoke the image's update function.  */
       if (image->update_func != SCM_BOOL_F)
         scm_apply (image->update_func, SCM_EOL, SCM_EOL);

       return SCM_UNSPECIFIED;
     }


     void
     init_image_type (void)
     {
       image_tag = scm_make_smob_type ("image", sizeof (struct image));
       scm_set_smob_mark (image_tag, mark_image);
       scm_set_smob_free (image_tag, free_image);
       scm_set_smob_print (image_tag, print_image);

       scm_c_define_gsubr ("clear-image", 1, 0, 0, clear_image);
       scm_c_define_gsubr ("make-image", 3, 0, 0, make_image);
     }


File: guile.info,  Node: Garbage Collecting Smobs,  Next: A Common Mistake In Allocating Smobs,  Prev: Type checking,  Up: Defining New Types (Smobs)

18.3.4 Garbage Collecting Smobs
-------------------------------

Once a smob has been released to the tender mercies of the Scheme
system, it must be prepared to survive garbage collection.  Guile calls
the `mark' and `free' functions of the `scm_smobfuns' structure to
manage this.

   As described before (*note Conservative GC::), every object in the
Scheme system has a "mark bit", which the garbage collector uses to
tell live objects from dead ones.  When collection starts, every
object's mark bit is clear.  The collector traces pointers through the
heap, starting from objects known to be live, and sets the mark bit on
each object it encounters.  When it can find no more unmarked objects,
the collector walks all objects, live and dead, frees those whose mark
bits are still clear, and clears the mark bit on the others.

   The two main portions of the collection are called the "mark phase",
during which the collector marks live objects, and the "sweep phase",
during which the collector frees all unmarked objects.

   The mark bit of a smob lives in a special memory region.  When the
collector encounters a smob, it sets the smob's mark bit, and uses the
smob's type tag to find the appropriate `mark' function for that smob:
the one listed in that smob's `scm_smobfuns' structure.  It then calls
the `mark' function, passing it the smob as its only argument.

   The `mark' function is responsible for marking any other Scheme
objects the smob refers to.  If it does not do so, the objects' mark
bits will still be clear when the collector begins to sweep, and the
collector will free them.  If this occurs, it will probably break, or at
least confuse, any code operating on the smob; the smob's `SCM' values
will have become dangling references.

   To mark an arbitrary Scheme object, the `mark' function may call
this function:

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

   Thus, here is how we might write the `mark' function for the image
smob type discussed above:

     SCM
     mark_image (SCM image_smob)
     {
       /* Mark the image's name and update function.  */
       struct image *image = (struct image *) SCM_SMOB_DATA (image_smob);

       scm_gc_mark (image->name);
       scm_gc_mark (image->update_func);

       return SCM_BOOL_F;
     }

   Note that, even though the image's `update_func' could be an
arbitrarily complex structure (representing a procedure and any values
enclosed in its environment), `scm_gc_mark' will recurse as necessary
to mark all its components.  Because `scm_gc_mark' sets an object's
mark bit before it recurses, it is not confused by circular structures.

   As an optimization, the collector will mark whatever value is
returned by the `mark' function; this helps limit depth of recursion
during the mark phase.  Thus, the code above could also be written as:
     SCM
     mark_image (SCM image_smob)
     {
       /* Mark the image's name and update function.  */
       struct image *image = (struct image *) SCM_SMOB_DATA (image_smob);

       scm_gc_mark (image->name);
       return image->update_func;
     }

   Finally, when the collector encounters an unmarked smob during the
sweep phase, it uses the smob's tag to find the appropriate `free'
function for the smob.  It then calls the function, passing it the smob
as its only argument.

   The `free' function must release any resources used by the smob.
However, it need not free objects managed by the collector; the
collector will take care of them.  The return type of the `free'
function should be `size_t', an unsigned integral type; the `free'
function should return the number of bytes released, to help the
collector maintain statistics on the size of the heap.

   Here is how we might write the `free' function for the image smob
type:
     size_t
     free_image (SCM image_smob)
     {
       struct image *image = (struct image *) SCM_SMOB_DATA (image_smob);
       size_t size = image->width * image->height + sizeof (*image);

       free (image->pixels);
       free (image);

       return size;
     }

   During the sweep phase, the garbage collector will clear the mark
bits on all live objects.  The code which implements a smob need not do
this itself.

   There is no way for smob code to be notified when collection is
complete.

   It is usually a good idea to minimize the amount of processing done
during garbage collection; keep `mark' and `free' functions very
simple.  Since collections occur at unpredictable times, it is easy for
any unusual activity to interfere with normal code.


File: guile.info,  Node: A Common Mistake In Allocating Smobs,  Next: Garbage Collecting Simple Smobs,  Prev: Garbage Collecting Smobs,  Up: Defining New Types (Smobs)

18.3.5 A Common Mistake In Allocating Smobs
-------------------------------------------

When constructing new objects, you must be careful that the garbage
collector can always find any new objects you allocate.  For example,
suppose we wrote the `make_image' function this way:

     SCM
     make_image (SCM name, SCM s_width, SCM s_height)
     {
       struct image *image;
       SCM image_smob;
       int width, height;

       SCM_ASSERT (SCM_STRINGP (name), name, SCM_ARG1, "make-image");
       SCM_ASSERT (SCM_INUMP (s_width),  s_width,  SCM_ARG2, "make-image");
       SCM_ASSERT (SCM_INUMP (s_height), s_height, SCM_ARG3, "make-image");

       width = SCM_INUM (s_width);
       height = SCM_INUM (s_height);

       image = (struct image *) scm_must_malloc (sizeof (struct image), "image");
       image->width = width;
       image->height = height;
       image->pixels = scm_must_malloc (width * height, "image pixels");

       /* THESE TWO LINES HAVE CHANGED: */
       image->name = scm_string_copy (name);
       image->update_func = scm_c_define_gsubr (...);

       SCM_NEWCELL (image_smob);
       SCM_SET_CELL_WORD_1 (image_smob, image);
       SCM_SET_CELL_TYPE (image_smob, image_tag);

       return image_smob;
     }

   This code is incorrect.  The calls to `scm_string_copy' and
`scm_c_define_gsubr' allocate fresh objects.  Allocating any new object
may cause the garbage collector to run.  If `scm_c_define_gsubr'
invokes a collection, the garbage collector has no way to discover that
`image->name' points to the new string object; the `image' structure is
not yet part of any Scheme object, so the garbage collector will not
traverse it.  Since the garbage collector cannot find any references to
the new string object, it will free it, leaving `image' pointing to a
dead object.

   A correct implementation might say, instead:

       image->name = SCM_BOOL_F;
       image->update_func = SCM_BOOL_F;

       SCM_NEWCELL (image_smob);
       SCM_SET_CELL_WORD_1 (image_smob, image);
       SCM_SET_CELL_TYPE (image_smob, image_tag);

       image->name = scm_string_copy (name);
       image->update_func = scm_c_define_gsubr (...);

       return image_smob;

   Now, by the time we allocate the new string and function objects,
`image_smob' points to `image'.  If the garbage collector scans the
stack, it will find a reference to `image_smob' and traverse `image',
so any objects `image' points to will be preserved.


File: guile.info,  Node: Garbage Collecting Simple Smobs,  Next: A Complete Example,  Prev: A Common Mistake In Allocating Smobs,  Up: Defining New Types (Smobs)

18.3.6 Garbage Collecting Simple Smobs
--------------------------------------

It is often useful to define very simple smob types -- smobs which have
no data to mark, other than the cell itself, or smobs whose first data
word is simply an ordinary Scheme object, to be marked recursively.
Guile provides some functions to handle these common cases; you can use
this function as your smob type's `mark' function, if your smob's
structure is simple enough.

   If the smob refers to no other Scheme objects, then no action is
necessary; the garbage collector has already marked the smob cell
itself.  In that case, you can use zero as your mark function.

 -- Functie: SCM scm_markcdr (SCM X)
     Mark the references in the smob X, assuming that X's first data
     word contains an ordinary Scheme object, and X refers to no other
     objects.  This function simply returns X's first data word.

     This is only useful for simple smobs created by `SCM_NEWSMOB' or
     `SCM_RETURN_NEWSMOB', not for smobs allocated as double cells.

 -- Functie: size_t scm_free0 (SCM X)
     Do nothing; return zero.  This function is appropriate for smobs
     that use either zero or `scm_markcdr' as their marking functions,
     and refer to no heap storage, including memory managed by `malloc',
     other than the smob's header cell.

     This function should not be needed anymore, because simply passing
     `NULL' as the free function does the same.


File: guile.info,  Node: A Complete Example,  Prev: Garbage Collecting Simple Smobs,  Up: Defining New Types (Smobs)

18.3.7 A Complete Example
-------------------------

Here is the complete text of the implementation of the image datatype,
as presented in the sections above.  We also provide a definition for
the smob's `print' function, and make some objects and functions
static, to clarify exactly what the surrounding code is using.

   As mentioned above, you can find this code in the Guile
distribution, in `doc/example-smob'.  That directory includes a
makefile and a suitable `main' function, so you can build a complete
interactive Guile shell, extended with the datatypes described here.)

     /* file "image-type.c" */

     #include <stdlib.h>
     #include <libguile.h>

     static scm_t_bits image_tag;

     struct image {
       int width, height;
       char *pixels;

       /* The name of this image */
       SCM name;

       /* A function to call when this image is
          modified, e.g., to update the screen,
          or SCM_BOOL_F if no action necessary */
       SCM update_func;
     };

     static SCM
     make_image (SCM name, SCM s_width, SCM s_height)
     {
       struct image *image;
       int width, height;

       SCM_ASSERT (SCM_STRINGP (name), name, SCM_ARG1, "make-image");
       SCM_ASSERT (SCM_INUMP (s_width),  s_width,  SCM_ARG2, "make-image");
       SCM_ASSERT (SCM_INUMP (s_height), s_height, SCM_ARG3, "make-image");

       width = SCM_INUM (s_width);
       height = SCM_INUM (s_height);

       image = (struct image *) scm_must_malloc (sizeof (struct image), "image");
       image->width = width;
       image->height = height;
       image->pixels = scm_must_malloc (width * height, "image pixels");
       image->name = name;
       image->update_func = SCM_BOOL_F;

       SCM_RETURN_NEWSMOB (image_tag, image);
     }

     static SCM
     clear_image (SCM image_smob)
     {
       int area;
       struct image *image;

       SCM_ASSERT (SCM_SMOB_PREDICATE (image_tag, image_smob),
                   image_smob, SCM_ARG1, "clear-image");

       image = (struct image *) SCM_SMOB_DATA (image_smob);
       area = image->width * image->height;
       memset (image->pixels, 0, area);

       /* Invoke the image's update function.  */
       if (image->update_func != SCM_BOOL_F)
         scm_apply (image->update_func, SCM_EOL, SCM_EOL);

       return SCM_UNSPECIFIED;
     }

     static SCM
     mark_image (SCM image_smob)
     {
       /* Mark the image's name and update function.  */
       struct image *image = (struct image *) SCM_SMOB_DATA (image_smob);

       scm_gc_mark (image->name);
       return image->update_func;
     }

     static size_t
     free_image (SCM image_smob)
     {
       struct image *image = (struct image *) SCM_SMOB_DATA (image_smob);
       size_t size = image->width * image->height + sizeof (struct image);

       free (image->pixels);
       free (image);

       return size;
     }

     static int
     print_image (SCM image_smob, SCM port, scm_print_state *pstate)
     {
       struct image *image = (struct image *) SCM_SMOB_DATA (image_smob);

       scm_puts ("#<image ", port);
       scm_display (image->name, port);
       scm_puts (">", port);

       /* non-zero means success */
       return 1;
     }

     void
     init_image_type (void)
     {
       image_tag = scm_make_smob_type ("image", sizeof (struct image));
       scm_set_smob_mark (image_tag, mark_image);
       scm_set_smob_free (image_tag, free_image);
       scm_set_smob_print (image_tag, print_image);

       scm_c_define_gsubr ("clear-image", 1, 0, 0, clear_image);
       scm_c_define_gsubr ("make-image", 3, 0, 0, make_image);
     }

   Here is a sample build and interaction with the code from the
`example-smob' directory, on the author's machine:

     zwingli:example-smob$ make CC=gcc
     gcc `guile-config compile`   -c image-type.c -o image-type.o
     gcc `guile-config compile`   -c myguile.c -o myguile.o
     gcc image-type.o myguile.o `guile-config link` -o myguile
     zwingli:example-smob$ ./myguile
     guile> make-image
     #<primitive-procedure make-image>
     guile> (define i (make-image "Whistler's Mother" 100 100))
     guile> i
     #<image Whistler's Mother>
     guile> (clear-image i)
     guile> (clear-image 4)
     ERROR: In procedure clear-image in expression (clear-image 4):
     ERROR: Wrong type argument in position 1: 4
     ABORT: (wrong-type-arg)

     Type "(backtrace)" to get more information.
     guile>


File: guile.info,  Node: GH,  Next: Reference Intro,  Prev: Data Representation,  Up: Top

19 GH: A Portable C to Scheme Interface
***************************************

This chapter shows how to use the GH interface to call Guile from your
application's C code, and to add new Scheme level procedures to Guile
whose behaviour is specified by application specific code written in C.

   Note, however, that the GH interface is now deprecated, and
developers are encouraged to switch to using the scm interface instead.
Therefore, for each GH feature, this chapter should also document how
to achieve the same result using the scm interface.

* Menu:

* GH deprecation::              Why the GH interface is now deprecated.
* gh preliminaries::
* Data types and constants defined by gh::
* Starting and controlling the interpreter::
* Error messages::
* Executing Scheme code::
* Defining new Scheme procedures in C::
* Converting data between C and Scheme::
* Type predicates::
* Equality predicates::
* Memory allocation and garbage collection::
* Calling Scheme procedures from C::
* Mixing gh and scm APIs::
* scm transition summary::


File: guile.info,  Node: GH deprecation,  Next: gh preliminaries,  Up: GH

19.1 Why the GH Interface is Now Deprecated
===========================================

Historically, the GH interface was the product of a practical problem
and a neat idea.  The practical problem was that the interface of the
`scm_' functions with which Guile itself was written (inherited from
Aubrey Jaffer's SCM) was so closely tied to the (rather arcane) details
of the internal data representation that it was extremely difficult to
write a Guile extension using these functions.  The neat idea was to
define a high level language extension interface in such a way that
other extension language projects, not just Guile, would be able to
provide an implementation of that interface; then applications using
this interface could be compiled with whichever of the various
available implementations they chose.  So the GH interface was created,
and advertised both as the recommended interface for application
developers wishing to use Guile, and as a portable high level interface
that could theoretically be implemented by other extension language
projects.

   Time passed, and various things changed.  Crucially, an enormous
number of improvements were made to the `scm_' interface that Guile
itself uses in its implementation, with the result that it is now both
easy and comfortable to write a Guile extension with this interface.
At the same time, the contents of the GH interface were somewhat
neglected by the core Guile developers, such that some key operations
-- such as smob creation and management -- are simply not possible
using GH alone.  Finally, the idea of multiple implementations of the
GH interface did not really crystallize (apart, I believe, from a short
lived implementation by the MzScheme project).

   For all these reasons, the Guile developers have decided to deprecate
the GH interface -- which means that support for GH will be completely
removed after the next few releases -- and to focus only on the `scm_'
interface, with additions to ensure that it is as easy to use in all
respects as GH was.

   It remains an open question whether a deep kind of interface
portability would be useful for extension language-based applications,
and it may still be an interesting project to attempt to define a
corresponding GH-like interface, but the Guile developers no longer
plan to try to do this as part of the core Guile project.


File: guile.info,  Node: gh preliminaries,  Next: Data types and constants defined by gh,  Prev: GH deprecation,  Up: GH

19.2 gh preliminaries
=====================

To use gh, you must have the following toward the beginning of your C
source:
     #include <guile/gh.h>
   
   When you link, you will have to add at least `-lguile' to the list
of libraries.  If you are using more of Guile than the basic Scheme
interpreter, you will have to add more libraries.  


File: guile.info,  Node: Data types and constants defined by gh,  Next: Starting and controlling the interpreter,  Prev: gh preliminaries,  Up: GH

19.3 Data types and constants defined by gh
===========================================

The following C constants and data types are defined in gh:

   `SCM' is a C data type used to store all Scheme data, no matter what
the Scheme type.  Values are converted between C data types and the SCM
type with utility functions described below (*note Converting data
between C and Scheme::).  [FIXME: put in references to Jim's essay and
so forth.]

 -- Constant: SCM_BOOL_T
 -- Constant: SCM_BOOL_F
     The _Scheme_ values returned by many boolean procedures in
     libguile.

     This can cause confusion because they are different from 0 and 1.
     In testing a boolean function in libguile programming, you must
     always make sure that you check the spec: `gh_' and `scm_'
     functions will usually return `SCM_BOOL_T' and `SCM_BOOL_F', but
     other C functions usually can be tested against 0 and 1, so
     programmers' fingers tend to just type `if (boolean_function()) {
     ... }'

 -- Constant: SCM_UNSPECIFIED
     This is a SCM value that is not the same as any legal Scheme
     value.  It is the value that a Scheme function returns when its
     specification says that its return value is unspecified.

 -- Constant: SCM_UNDEFINED
     This is another SCM value that is not the same as any legal Scheme
     value.  It is the value used to mark variables that do not yet
     have a value, and it is also used in C to terminate functions with
     variable numbers of arguments, such as `gh_list()'.


File: guile.info,  Node: Starting and controlling the interpreter,  Next: Error messages,  Prev: Data types and constants defined by gh,  Up: GH

19.4 Starting and controlling the interpreter
=============================================

In almost every case, your first `gh_' call will be:

 -- Functie: void gh_enter (int ARGC, char *ARGV[], void (*MAIN_PROG)())
     Starts up a Scheme interpreter with all the builtin Scheme
     primitives.  `gh_enter()' never exits, and the user's code should
     all be in the `MAIN_PROG()' function.  `argc' and `argv' will be
     passed to MAIN_PROG.

      -- Functie: void main_prog (int ARGC, char *ARGV[])
          This is the user's main program.  It will be invoked by
          `gh_enter()' after Guile has been started up.

     Note that you can use `gh_repl' inside `gh_enter' (in other words,
     inside the code for `main-prog') if you want the program to be
     controlled by a Scheme read-eval-print loop.

   A convenience routine which enters the Guile interpreter with the
standard Guile read-eval-print loop ("REPL") is:

 -- Functie: void gh_repl (int ARGC, char *ARGV[])
     Enters the Scheme interpreter giving control to the Scheme REPL.
     Arguments are processed as if the Guile program `guile' were being
     invoked.

     Note that `gh_repl' should be used _inside_ `gh_enter', since any
     Guile interpreter calls are meaningless unless they happen in the
     context of the interpreter.

     Also note that when you use `gh_repl', your program will be
     controlled by Guile's REPL (which is written in Scheme and has many
     useful features).  Use straight C code inside `gh_enter' if you
     want to maintain execution control in your C program.

   You will typically use `gh_enter' and `gh_repl' when you want a
Guile interpreter enhanced by your own libraries, but otherwise quite
normal.  For example, to build a Guile-derived program that includes
some random number routines "GSL" (GNU Scientific Library), you would
write a C program that looks like this:

     #include <guile/gh.h>
     #include <gsl_ran.h>

     /* random number suite */
     SCM gw_ran_seed(SCM s)
     {
       gsl_ran_seed(gh_scm2int(s));
       return SCM_UNSPECIFIED;
     }

     SCM gw_ran_random()
     {
       SCM x;

       x = gh_ulong2scm(gsl_ran_random());
       return x;
     }

     SCM gw_ran_uniform()
     {
       SCM x;

       x = gh_double2scm(gsl_ran_uniform());
       return x;
     }
     SCM gw_ran_max()
     {
       return gh_double2scm(gsl_ran_max());
     }

     void
     init_gsl()
     {
       /* random number suite */
       gh_new_procedure("gsl-ran-seed", gw_ran_seed, 1, 0, 0);
       gh_new_procedure("gsl-ran-random", gw_ran_random, 0, 0, 0);
       gh_new_procedure("gsl-ran-uniform", gw_ran_uniform, 0, 0, 0);
       gh_new_procedure("gsl-ran-max", gw_ran_max, 0, 0, 0);
     }

     void
     main_prog (int argc, char *argv[])
     {
       init_gsl();

       gh_repl(argc, argv);
     }

     int
     main (int argc, char *argv[])
     {
       gh_enter (argc, argv, main_prog);
     }

   Then, supposing the C program is in `guile-gsl.c', you could compile
it with `gcc -o guile-gsl guile-gsl.c -lguile -lgsl'.

   The resulting program `guile-gsl' would have new primitive
procedures `gsl-ran-random', `gsl-ran-gaussian' and so forth.


File: guile.info,  Node: Error messages,  Next: Executing Scheme code,  Prev: Starting and controlling the interpreter,  Up: GH

19.5 Error messages
===================

[FIXME: need to fill this based on Jim's new mechanism]


File: guile.info,  Node: Executing Scheme code,  Next: Defining new Scheme procedures in C,  Prev: Error messages,  Up: GH

19.6 Executing Scheme code
==========================

Once you have an interpreter running, you can ask it to evaluate Scheme
code.  There are two calls that implement this:

 -- Functie: SCM gh_eval_str (char *SCHEME_CODE)
     This asks the interpreter to evaluate a single string of Scheme
     code, and returns the result of the last expression evaluated.

     Note that the line of code in SCHEME_CODE must be a well formed
     Scheme expression.  If you have many lines of code before you
     balance parentheses, you must either concatenate them into one
     string, or use `gh_eval_file()'.

 -- Functie: SCM gh_eval_file (char *FNAME)
 -- Functie: SCM gh_load (char *FNAME)
     `gh_eval_file' is completely analogous to `gh_eval_str()', except
     that a whole file is evaluated instead of a string.
     `gh_eval_file' returns `SCM_UNSPECIFIED'.

     `gh_load' is identical to `gh_eval_file' (it's a macro that calls
     `gh_eval_file' on its argument).  It is provided to start making
     the `gh_' interface match the R5RS Scheme procedures closely.


File: guile.info,  Node: Defining new Scheme procedures in C,  Next: Converting data between C and Scheme,  Prev: Executing Scheme code,  Up: GH

19.7 Defining new Scheme procedures in C
========================================

The real interface between C and Scheme comes when you can write new
Scheme procedures in C.  This is done through the routine

 -- Libguile high: SCM gh_new_procedure (char *PROC_NAME, SCM (*FN)(),
          int N_REQUIRED_ARGS, int N_OPTIONAL_ARGS, int RESTP)
     `gh_new_procedure' defines a new Scheme procedure.  Its Scheme name
     will be PROC_NAME, it will be implemented by the C function
     (*FN)(), it will take at least N_REQUIRED_ARGS arguments, and at
     most N_OPTIONAL_ARGS extra arguments.

     When the RESTP parameter is 1, the procedure takes a final
     argument: a list of remaining parameters.

     `gh_new_procedure' returns an SCM value representing the procedure.

     The C function FN should have the form

      -- Libguile high: SCM fn (SCM REQ1, SCM REQ2, ..., SCM OPT1, SCM
               OPT2, ..., SCM REST_ARGS)
          The arguments are all passed as SCM values, so the user will
          have to use the conversion functions to convert to standard C
          types.

          Examples of C functions used as new Scheme primitives can be
          found in the sample programs `learn0' and `learn1'.


   *Rationale:* this is the correct way to define new Scheme procedures
in C.  The ugly mess of arguments is required because of how C handles
procedures with variable numbers of arguments.

   *Note* what about documentation strings?

   There are several important considerations to be made when writing
the C routine `(*fn)()'.

   First of all the C routine has to return type `SCM'.

   Second, all arguments passed to the C function will be of type `SCM'.

   Third: the C routine is now subject to Scheme flow control, which
means that it could be interrupted at any point, and then reentered.
This means that you have to be very careful with operations such as
allocating memory, modifying static data ...

   Fourth: to get around the latter issue, you can use `GH_DEFER_INTS'
and `GH_ALLOW_INTS'.

 -- Makro: GH_DEFER_INTS
 -- Makro: GH_ALLOW_INTS
     These macros disable and re-enable Scheme's flow control.  They


File: guile.info,  Node: Converting data between C and Scheme,  Next: Type predicates,  Prev: Defining new Scheme procedures in C,  Up: GH

19.8 Converting data between C and Scheme
=========================================

Guile provides mechanisms to convert data between C and Scheme.  This
allows new builtin procedures to understand their arguments (which are
of type `SCM') and return values of type `SCM'.

* Menu:

* C to Scheme::
* Scheme to C::


File: guile.info,  Node: C to Scheme,  Next: Scheme to C,  Up: Converting data between C and Scheme

19.8.1 C to Scheme
------------------

 -- Functie: SCM gh_bool2scm (int X)
     Returns `#f' if X is zero, `#t' otherwise.

 -- Functie: SCM gh_ulong2scm (unsigned long X)
 -- Functie: SCM gh_long2scm (long X)
 -- Functie: SCM gh_double2scm (double X)
 -- Functie: SCM gh_char2scm (char X)
     Returns a Scheme object with the value of the C quantity X.

 -- Functie: SCM gh_str2scm (char *S, int LEN)
     Returns a new Scheme string with the (not necessarily
     null-terminated) C array S data.

 -- Functie: SCM gh_str02scm (char *S)
     Returns a new Scheme string with the null-terminated C string S
     data.

 -- Functie: SCM gh_set_substr (char *SRC, SCM DST, int START, int LEN)
     Copy LEN characters at SRC into the _existing_ Scheme string DST,
     starting at START.  START is an index into DST; zero means the
     beginning of the string.

     If START + LEN is off the end of DST, signal an out-of-range error.

 -- Functie: SCM gh_symbol2scm (char *NAME)
     Given a null-terminated string NAME, return the symbol with that
     name.

 -- Functie: SCM gh_ints2scm (int *DPTR, int N)
 -- Functie: SCM gh_doubles2scm (double *DPTR, int N)
     Make a scheme vector containing the N ints or doubles at memory
     location DPTR.

 -- Functie: SCM gh_chars2byvect (char *DPTR, int N)
 -- Functie: SCM gh_shorts2svect (short *DPTR, int N)
 -- Functie: SCM gh_longs2ivect (long *DPTR, int N)
 -- Functie: SCM gh_ulongs2uvect (ulong *DPTR, int N)
 -- Functie: SCM gh_floats2fvect (float *DPTR, int N)
 -- Functie: SCM gh_doubles2dvect (double *DPTR, int N)
     Make a scheme uniform vector containing the N chars, shorts,
     longs, unsigned longs, floats or doubles at memory location DPTR.


File: guile.info,  Node: Scheme to C,  Prev: C to Scheme,  Up: Converting data between C and Scheme

19.8.2 Scheme to C
------------------

 -- Functie: int gh_scm2bool (SCM OBJ)
 -- Functie: unsigned long gh_scm2ulong (SCM OBJ)
 -- Functie: long gh_scm2long (SCM OBJ)
 -- Functie: double gh_scm2double (SCM OBJ)
 -- Functie: int gh_scm2char (SCM OBJ)
     These routines convert the Scheme object to the given C type.

 -- Functie: char *gh_scm2newstr (SCM STR, size_t *LENP)
     Given a Scheme string STR, return a pointer to a new copy of its
     contents, followed by a null byte.  If LENP is non-null, set
     `*LENP' to the string's length.

     This function uses malloc to obtain storage for the copy; the
     caller is responsible for freeing it.

     Note that Scheme strings may contain arbitrary data, including null
     characters.  This means that null termination is not a reliable
     way to determine the length of the returned value.  However, the
     function always copies the complete contents of STR, and sets *LENP
     to the true length of the string (when LENP is non-null).

 -- Functie: void gh_get_substr (SCM str, char *return_str, int *lenp)
     Copy LEN characters at START from the Scheme string SRC to memory
     at DST.  START is an index into SRC; zero means the beginning of
     the string.  DST has already been allocated by the caller.

     If START + LEN is off the end of SRC, signal an out-of-range error.

 -- Functie: char *gh_symbol2newstr (SCM SYM, int *LENP)
     Takes a Scheme symbol and returns a string of the form
     `"'symbol-name"'.  If LENP is non-null, the string's length is
     returned in `*LENP'.

     This function uses malloc to obtain storage for the returned
     string; the caller is responsible for freeing it.

 -- Functie: char *gh_scm2chars (SCM VECTOR, chars *RESULT)
 -- Functie: short *gh_scm2shorts (SCM VECTOR, short *RESULT)
 -- Functie: long *gh_scm2longs (SCM VECTOR, long *RESULT)
 -- Functie: float *gh_scm2floats (SCM VECTOR, float *RESULT)
 -- Functie: double *gh_scm2doubles (SCM VECTOR, double *RESULT)
     Copy the numbers in VECTOR to the array pointed to by RESULT and
     return it.  If RESULT is NULL, allocate a double array large
     enough.

     VECTOR can be an ordinary vector, a weak vector, or a signed or
     unsigned uniform vector of the same type as the result array.  For
     chars, VECTOR can be a string or substring.  For floats and
     doubles, VECTOR can contain a mix of inexact and integer values.

     If VECTOR is of unsigned type and contains values too large to fit
     in the signed destination array, those values will be wrapped
     around, that is, data will be copied as if the destination array
     was unsigned.


File: guile.info,  Node: Type predicates,  Next: Equality predicates,  Prev: Converting data between C and Scheme,  Up: GH

19.9 Type predicates
====================

These C functions mirror Scheme's type predicate procedures with one
important difference.  The C routines return C boolean values (0 and 1)
instead of `SCM_BOOL_T' and `SCM_BOOL_F'.

   The Scheme notational convention of putting a `?' at the end of
predicate procedure names is mirrored in C by placing `_p' at the end
of the procedure.  For example, `(pair? ...)' maps to `gh_pair_p(...)'.

 -- Functie: int gh_boolean_p (SCM VAL)
     Returns 1 if VAL is a boolean, 0 otherwise.

 -- Functie: int gh_symbol_p (SCM VAL)
     Returns 1 if VAL is a symbol, 0 otherwise.

 -- Functie: int gh_char_p (SCM VAL)
     Returns 1 if VAL is a char, 0 otherwise.

 -- Functie: int gh_vector_p (SCM VAL)
     Returns 1 if VAL is a vector, 0 otherwise.

 -- Functie: int gh_pair_p (SCM VAL)
     Returns 1 if VAL is a pair, 0 otherwise.

 -- Functie: int gh_procedure_p (SCM VAL)
     Returns 1 if VAL is a procedure, 0 otherwise.

 -- Functie: int gh_list_p (SCM VAL)
     Returns 1 if VAL is a list, 0 otherwise.

 -- Functie: int gh_inexact_p (SCM VAL)
     Returns 1 if VAL is an inexact number, 0 otherwise.

 -- Functie: int gh_exact_p (SCM VAL)
     Returns 1 if VAL is an exact number, 0 otherwise.


File: guile.info,  Node: Equality predicates,  Next: Memory allocation and garbage collection,  Prev: Type predicates,  Up: GH

19.10 Equality predicates
=========================

These C functions mirror Scheme's equality predicate procedures with one
important difference.  The C routines return C boolean values (0 and 1)
instead of `SCM_BOOL_T' and `SCM_BOOL_F'.

   The Scheme notational convention of putting a `?' at the end of
predicate procedure names is mirrored in C by placing `_p' at the end
of the procedure.  For example, `(equal? ...)' maps to
`gh_equal_p(...)'.

 -- Functie: int gh_eq_p (SCM x, SCM y)
     Returns 1 if X and Y are equal in the sense of Scheme's `eq?'
     predicate, 0 otherwise.

 -- Functie: int gh_eqv_p (SCM x, SCM y)
     Returns 1 if X and Y are equal in the sense of Scheme's `eqv?'
     predicate, 0 otherwise.

 -- Functie: int gh_equal_p (SCM x, SCM y)
     Returns 1 if X and Y are equal in the sense of Scheme's `equal?'
     predicate, 0 otherwise.

 -- Functie: int gh_string_equal_p (SCM S1, SCM S2)
     Returns 1 if the strings S1 and S2 are equal, 0 otherwise.

 -- Functie: int gh_null_p (SCM L)
     Returns 1 if L is an empty list or pair; 0 otherwise.


File: guile.info,  Node: Memory allocation and garbage collection,  Next: Calling Scheme procedures from C,  Prev: Equality predicates,  Up: GH

19.11 Memory allocation and garbage collection
==============================================


File: guile.info,  Node: Calling Scheme procedures from C,  Next: Mixing gh and scm APIs,  Prev: Memory allocation and garbage collection,  Up: GH

19.12 Calling Scheme procedures from C
======================================

Many of the Scheme primitives are available in the `gh_' interface;
they take and return objects of type SCM, and one could basically use
them to write C code that mimics Scheme code.

   I will list these routines here without much explanation, since what
they do is the same as documented in *Note R5RS: (r5rs)Standard
procedures.  But I will point out that when a procedure takes a
variable number of arguments (such as `gh_list'), you should pass the
constant SCM_UNDEFINED from C to signify the end of the list.

 -- Functie: SCM gh_define (char *NAME, SCM VAL)
     Corresponds to the Scheme `(define name val)': it binds a value to
     the given name (which is a C string).  Returns the new object.

Pairs and lists
===============

 -- Functie: SCM gh_cons (SCM A, SCM B)
 -- Functie: SCM gh_list (SCM l0, SCM l1, ... , SCM_UNDEFINED)
     These correspond to the Scheme `(cons a b)' and `(list l0 l1 ...)'
     procedures.  Note that `gh_list()' is a C macro that invokes
     `scm_listify()'.

 -- Functie: SCM gh_car (SCM OBJ)
 -- Functie: SCM gh_cdr (SCM OBJ)
     ...

 -- Functie: SCM gh_c[ad][ad][ad][ad]r (SCM OBJ)
     These correspond to the Scheme `(caadar ls)' procedures etc ...

 -- Functie: SCM gh_set_car_x (SCM PAIR, SCM VALUE)
     Modifies the CAR of PAIR to be VALUE.  This is equivalent to the
     Scheme procedure `(set-car! ...)'.

 -- Functie: SCM gh_set_cdr_x (SCM PAIR, SCM VALUE)
     Modifies the CDR of PAIR to be VALUE.  This is equivalent to the
     Scheme procedure `(set-cdr! ...)'.

 -- Functie: unsigned long gh_length (SCM LS)
     Returns the length of the list.

 -- Functie: SCM gh_append (SCM ARGS)
 -- Functie: SCM gh_append2 (SCM L1, SCM L2)
 -- Functie: SCM gh_append3 (SCM L1, SCM L2, L3)
 -- Functie: SCM gh_append4 (SCM L1, SCM L2, L3, L4)
     `gh_append()' takes ARGS, which is a list of lists `(list1 list2
     ...)', and returns a list containing all the elements of the
     individual lists.

     A typical invocation of `gh_append()' to append 5 lists together
     would be
            gh_append(gh_list(l1, l2, l3, l4, l5, SCM_UNDEFINED));

     The functions `gh_append2()', `gh_append2()', `gh_append3()' and
     `gh_append4()' are convenience routines to make it easier for C
     programs to form the list of lists that goes as an argument to
     `gh_append()'.

 -- Functie: SCM gh_reverse (SCM LS)
     Returns a new list that has the same elements as LS but in the
     reverse order.  Note that this is implemented as a macro which
     calls `scm_reverse()'.

 -- Functie: SCM gh_list_tail (SCM LS, SCM K)
     Returns the sublist of LS with the last K elements.

 -- Functie: SCM gh_list_ref (SCM LS, SCM K)
     Returns the Kth element of the list LS.

 -- Functie: SCM gh_memq (SCM X, SCM LS)
 -- Functie: SCM gh_memv (SCM X, SCM LS)
 -- Functie: SCM gh_member (SCM X, SCM LS)
     These functions return the first sublist of LS whose CAR is X.
     They correspond to `(memq x ls)', `(memv x ls)' and `(member x
     ls)', and hence use (respectively) `eq?', `eqv?' and `equal?' to
     do comparisons.

     If X does not appear in LS, the value `SCM_BOOL_F' (not the empty
     list) is returned.

     Note that these functions are implemented as macros which call
     `scm_memq()', `scm_memv()' and `scm_member()' respectively.

 -- Functie: SCM gh_assq (SCM X, SCM ALIST)
 -- Functie: SCM gh_assv (SCM X, SCM ALIST)
 -- Functie: SCM gh_assoc (SCM X, SCM ALIST)
     These functions search an "association list" (list of pairs) ALIST
     for the first pair whose CAR is X, and they return that pair.

     If no pair in ALIST has X as its CAR, the value `SCM_BOOL_F' (not
     the empty list) is returned.

     Note that these functions are implemented as macros which call
     `scm_assq()', `scm_assv()' and `scm_assoc()' respectively.

Symbols
=======

Vectors
=======

 -- Functie: SCM gh_make_vector (SCM N, SCM FILL)
 -- Functie: SCM gh_vector (SCM LS)
 -- Functie: SCM gh_vector_ref (SCM V, SCM I)
 -- Functie: SCM gh_vector_set (SCM V, SCM I, SCM VAL)
 -- Functie: unsigned long gh_vector_length (SCM V)
 -- Functie: SCM gh_list_to_vector (SCM LS)
     These correspond to the Scheme `(make-vector n fill)', `(vector a
     b c ...)' `(vector-ref v i)' `(vector-set v i value)'
     `(vector-length v)' `(list->vector ls)' procedures.

     The correspondence is not perfect for `gh_vector': this routine
     takes a list LS instead of the individual list elements, thus
     making it identical to `gh_list_to_vector'.

     There is also a difference in gh_vector_length: the value returned
     is a C `unsigned long' instead of an SCM object.

Procedures
==========

 -- Functie: SCM gh_apply (SCM proc, SCM args)
     Call the Scheme procedure PROC, with the elements of ARGS as
     arguments.  ARGS must be a proper list.

 -- Functie: SCM gh_call0 (SCM proc)
 -- Functie: SCM gh_call1 (SCM proc, SCM arg)
 -- Functie: SCM gh_call2 (SCM proc, SCM arg1, SCM arg2)
 -- Functie: SCM gh_call3 (SCM proc, SCM arg1, SCM arg2, SCM arg3)
     Call the Scheme procedure PROC with no arguments (`gh_call0'), one
     argument (`gh_call1'), and so on.  You can get the same effect by
     wrapping the arguments up into a list, and calling `gh_apply';
     Guile provides these functions for convenience.

 -- Functie: SCM gh_catch (SCM key, SCM thunk, SCM handler)
 -- Functie: SCM gh_throw (SCM key, SCM args)
     Corresponds to the Scheme `catch' and `throw' procedures, which in
     Guile are provided as primitives.

 -- Functie: SCM gh_is_eq (SCM a, SCM b)
 -- Functie: SCM gh_is_eqv (SCM a, SCM b)
 -- Functie: SCM gh_is_equal (SCM a, SCM b)
     These correspond to the Scheme `eq?', `eqv?' and `equal?'
     predicates.

 -- Functie: int gh_obj_length (SCM OBJ)
     Returns the raw object length.

Data lookup
===========

For now I just include Tim Pierce's comments from the `gh_data.c' file;
it should be organized into a documentation of the two functions here.

     /* Data lookups between C and Scheme

        Look up a symbol with a given name, and return the object to which
        it is bound.  gh_lookup examines the Guile top level, and
        gh_module_lookup checks the module name space specified by the
        `vec' argument.

        The return value is the Scheme object to which SNAME is bound, or
        SCM_UNDEFINED if SNAME is not bound in the given context. [FIXME:
        should this be SCM_UNSPECIFIED?  Can a symbol ever legitimately be
        bound to SCM_UNDEFINED or SCM_UNSPECIFIED?  What is the difference?
        -twp] */


File: guile.info,  Node: Mixing gh and scm APIs,  Next: scm transition summary,  Prev: Calling Scheme procedures from C,  Up: GH

19.13 Mixing gh and scm APIs
============================

