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.

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

  * If this source code file is not ASCII or ISO-8859-1 encoded, a coding declaration such as coding: utf-8 should appear in a comment somewhere in the first five lines of the file: see Character Encoding of Source Files.

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

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 DIRECTORY
     Add DIRECTORY to the front of Guile's module load path.  The given directories are searched in the order given on the command line and before any directories in the GUILE_LOAD_PATH environment variable.  Paths added here are not in effect during execution of the user's .guile file.

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

     The FUNCTION is most often a simple symbol that names a function that is defined in the script.  It can also be of the form (@ MODULE-NAME SYMBOL) and in that case, the symbol is looked up in the module named MODULE-NAME.

     For compatibility with some versions of Guile 1.4, you can also use the form (symbol ...) (that is, a list of only symbols that doesn't start with @), which is equivalent to (@ (symbol ...) main), or (symbol ...)  symbol (that is, a list of only symbols followed by a symbol), which is equivalent to (@ (symbol ...) symbol).  We recommend to use the equivalent forms directly since they correspond to the (@ ...)  read syntax that can be used in normal code, see Using Guile Modules.

     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.

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

     1.8

--no-debug
     Do not use the debugging evaluator, even when entering an interactive session.

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

Command Line Handling
---------------------

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

When a Guile script is invoked, Guile makes the command line arguments accessible via the procedure 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: see 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.

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, see getopt-long.

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