Introduction
************

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^4 Report on the Algorithmic Language Scheme (usually known as R4RS), providing clean and general data and control structures.  Guile goes beyond the rather austere language presented in R4RS, 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 compiling 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.

This manual assumes you know Scheme, as described in R4RS.  From there, it describes:

Part I
     how to use Guile interactively and as an interpreter, how to link Guile into your own applications, and how to write modules of interpreted and compiled code for use with Guile,

Part II
     Guile's extensions to the language described in R4RS,

Part III
     how to call Guile from C code, and how to add new functions written in C to Guile, using C functions which (we hope) will also someday work with other Scheme interpreters, allowing you to write C code which will work with any of several Scheme systems, and

Part IV
     further functions available to the C level which are specific to Guile, but provide more thorough access to Guile's internals.

Finally, the appendices explain how to obtain the latest version of Guile, how to install it, where to find modules to work with Guile, and how to use the Guile debugger.

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
     $

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)

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 R4RS, 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 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)

 -- procedure: command-line
 -- primitive: 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.

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

     See 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 Scripting Examples.

\
     Read more command-line arguments, starting from the second line of the script file.  See 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.

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

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

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.

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

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 Relationship between Scheme and C functions.

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 can link them against Guile by passing the flag -lguile to your linker.  If you installed Guile with multi-thread support (by passing --enable-threads to the configure script), you may also need to link against the QuickThreads library, -lqt.  Guile refers to various mathematical functions, so you will probably need to link against the mathematical library, -lm, as well.

Guile Initialization Functions
==============================

To initialize Guile, use this function:

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

     scm_boot_guile establishes a catch-all error handler which prints an error message and exits the process.  This means that Guile exits in a coherent way if a system error occurs and the user isn't prepared to handle it.  If the user doesn't like this behavior, they can establish their own universal catcher in MAIN_FUNC to shadow this one.

     Why must the caller do all the real work from MAIN_FUNC?  Guile's garbage collector assumes that all local variables which reference Scheme objects will be above scm_boot_guile's stack frame on the stack.  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.

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:

 -- Function: 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. See Invoking Guile, for more details.

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

     If you do not use this function to start Guile, you are responsible for making sure Guile's usual initialization files, init.scm and ice-9/boot-9.scm, get loaded.  This will change soon.

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.

     # Use GCC, if you have it installed.
     CC=gcc

     # Tell the C compiler where to find <libguile.h> and -lguile.
     CFLAGS=-I/usr/local/include -L/usr/local/lib

     # Include -lqt and -lrx if they are present on your system.
     LIBS=-lguile -lqt -lrx -lm

     simple-guile: simple-guile.o
             ${CC} ${CFLAGS} 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.  Here is a configure.in file for simple-guile, which Autoconf can use as a template to generate a configure script:

     AC_INIT(simple-guile.c)

     # Find a C compiler.
     AC_PROG_CC

     # Check for libraries.
     AC_CHECK_LIB(m, sin)
     AC_CHECK_LIB(rx, regcomp)
     AC_CHECK_LIB(qt, main)
     AC_CHECK_LIB(guile, scm_boot_guile)

     # 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=@CFLAGS@
     LIBS=@LIBS@

     simple-guile: simple-guile.o
             ${CC} ${CFLAGS} 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... 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... yes
     checking whether gcc accepts -g... yes
     checking for sin in -lm... yes
     checking for regcomp in -lrx... yes
     checking for main in -lqt... yes
     checking for scm_boot_guile in -lguile... yes
     updating cache ./config.cache
     creating ./config.status
     creating Makefile
     $ make
     gcc -c -g -O2 simple-guile.c
     gcc -g -O2 simple-guile.o -lguile -lqt -lrx -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)
     $

Writing Guile Modules
*********************