This is bigloo.info, produced by makeinfo version 4.12 from bigloo.texi.

3.1a

  This file documents Bigloo, an implementation of an extended version
of the Scheme programming language.

  Copyright (C) 1992-99, 2000-08 Manuel Serrano

     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 of the License, 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 program; if not, write to the Free
     Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
     MA 02111-1307, USA.

INFO-DIR-SECTION The Algorithmic Language Scheme
START-INFO-DIR-ENTRY
* bigloo: (bigloo).            The Bigloo Scheme compiler
END-INFO-DIR-ENTRY


File: bigloo.info,  Node: Grammar Definition,  Next: Precedence and Associativity,  Up: Lalr Parsing

11.1 Grammar definition
=======================

An lalr(1) grammar is defined by the form:

 -- bigloo syntax: lalr-grammar term-def non-term-def...
     TERM-DEF is a list of terminal elements of the grammar.  Terminals
     can grouped together to form precedence groups by including the
     related symbols in a sub-lists of the TERM-DEF list.  Each
     precedence group must start with one of the keywords `left:',
     `right:' or `none:'- this indicates the associativity of the
     terminal symbol.  Here is a sample TERM-DEF which declares eight
     terminals:
          (terminal-1 terminal-2
           (left: terminal-3 terminal-4)
           terminal-5
           (right: terminal-6)
           (none: terminal-7)
           terminal-8)

     In this case, `terminal-3' and `terminal-4' both have the same
     precedence, which is greater than the precedence assigned to
     `terminal-6'. No precedence was assigned to symbols `terminal-1',
     `terminal-2', `terminal-5' or `terminal-8'.

     Each NON-TERM-DEF is a list whose first element is the
     non-terminal being defined, i.e. a symbol. The remaining elements
     are the production rules associated with this non-terminal. Each
     rule is a list whose first element is the rule itself (a list of
     symbols) and the other elements are the semantic actions
     associated with that particular rule.

     For example, consider the following grammar:
          E ==> E1 + ID {E.val := E1.val + ID.val}
                | ID {E.val := ID.val}

     With Bigloo, it would be written:
          (lalr-grammar
            (plus id)
            (e
             ((e plus id)   (+ e id))
             ((id)          id)))

     The semantic value of a symbol in a rule can be accessed by simply
     using the name of the symbol in the semantic action associated with
     the rule. Because a rule can contain multiple occurrences of the
     same symbol, Bigloo provides a way to access these occurrences
     separately. To do so, the name of each occurrence must be suffixed
     by `@'VAR where VAR is the name of a variable that will be bound
     to the semantic value of the occurrence. For example, if the rule
     is

             ifstmt ==> if E then Stmt else Stmt

     then, in Bigloo, it would look like
          (if-stmt
           ((if e then stmt@conseq else stmt@altern)
            (if (eval e)
                (eval conseq)
                (eval altern))))


File: bigloo.info,  Node: Precedence and Associativity,  Next: The Parsing Function,  Prev: Grammar Definition,  Up: Lalr Parsing

11.2 Precedence and associativity
=================================

The bigloo lalr(1) parser generator supports operator precedence and
associativity.  The method for specifying the precedence for terminal
symbols is described in *note Grammar Definition::.  Precedence is
assigned to each non-terminal production from the precedence of the
last terminal symbol appearing in that production.

  Typically, when the parser generator encounters a shift/reduce
conflict, it produces a warning message, then chooses to reduce.  When
a parser generator has precedence and associativity information, it can
make a much more sophisticated decision.

  Let's use this simple calculator grammar as an example:
     (lalr-grammar
      ((left: op-mult op-div)
       (left: op-add op-sub)
       op-lparen op-rparen
       op-semicolon
       number)

      (file
        (())
        ((file stmt)))
      (stmt
        ((expr op-semicolon) (print expr)))
      (expr
        ((number) number)
        ((expr@a op-add expr@b) (+ a b))
        ((expr@a op-sub expr@b) (- a b))
        ((expr@a op-mult expr@b) (* a b))
        ((expr@a op-div expr@b) (/ a b))
        ((op-lparen expr op-rparen) expr))))

  Let's start with this input:
     1 + 2 * 3;

  At the point where the parser has read `1 + 2' and the lookahead
symbol is `*', the parser encounters a shift/reduce conflict.  Should
it first reduce by the `(expr op-add expr)' production or shift the `*'
in the hopes of reducing the latter expression first?

  The `(expr op-add expr)' production has gotten its precedence from the
`op-add' terminal symbol.  This is the precedence of the reduce.  The
precedence of the shift comes from the precedence assigned to the
lookahead terminal symbol, which is `op-mult'.  Since `op-mult' has
higher precedence, the parser generator in this state chooses to shift
and does not produce a warning.

  Here's an example which we can use to demonstrate associativity:
     1 + 2 - 3;

  The parser generator encounters a similar shift/reduce conflict this
time, except that when it tries to determine whether to shift or
reduce, it finds that both actions have the same precedence.  In this
case, the parser generator looks at the associativity of the precedence
group containing the `op-add' and `op-sub'.  Since these are declared
to be left-associative, the parser generator chooses to reduce from
this state, effectively calculating the `1 + 2'.  Had these symbols been
right-associative, the parser would have chosen to shift, effectively
calculating `2 - 3' first.  If these symbols had been declared
non-associative with the `none:' keyword, the parser would generate an
error if it ever encountered this state.


File: bigloo.info,  Node: The Parsing Function,  Next: The Regular Grammar,  Prev: Precedence and Associativity,  Up: Lalr Parsing

11.3 The parsing function
=========================

Once a grammar has been defined, it can be used to parse some input
using the following function:

 -- bigloo procedure: read/lalrp lg rg port [emptyp]
     This function takes three, possibly four, arguments. The first,
     LG, is the Lalr(1) grammar. The second, RG, is the lexical
     analyzer that feeds the grammar with tokens. The third argument,
     PORT, is the port that contains the input to be parsed. The last
     argument, EMPTYP, if provided, should be a function of one
     argument. It is called with each new token read from the port and
     should return `#t' if the token denotes the end of input. The
     result of the call is the value computed by the semantic actions
     of the production rules.


File: bigloo.info,  Node: The Regular Grammar,  Next: Debugging Lalr Grammars,  Prev: The Parsing Function,  Up: Lalr Parsing

11.4 The regular grammar
========================

In order to work properly, the regular grammar used with an Lalr(1)
grammar should follow some conventions:

   * If a semantic value is to be associated with the token just
     parsed, the regular grammar should return a pair whose `car' is the
     token name (a symbol) and the `cdr' is the semantic value.

   * If there is no value associated with the token, the regular
     grammar can return just the token name. When used in conjunction
     with an Lalr grammar, regular grammar should never return `#f' as
     a token value. This is specially true when the regular grammar
     detects the end of parsing. In that case, the regular grammar
     _must not_ return the `#f' value. A good way to handle end-of-file
     is illustrated in the following example:

          (let ((g (regular-grammar ()
                       ...
                       (else
                        (let ((c (the-failure)))
                           (if (eof-object? c)
                               c
                               (error 'rgc "Illegal character" c))))))
                (l (lalr-grammar ...)))
             (read/lalrp l g (current-input-port)))

     This way, the Lalr grammar will automatically handles the
     end-of-file.


File: bigloo.info,  Node: Debugging Lalr Grammars,  Next: A Simple Example,  Prev: The Regular Grammar,  Up: Lalr Parsing

11.5 Debugging Lalr Grammars
============================

Currently the debugging facility for debugging Lalr grammars is very
limited.

 -- bigloo variable: *debug-parser*
     When set to true, The variable *DEBUG-PARSER*, outputs all of the
     state changes the parser is going through.


File: bigloo.info,  Node: A Simple Example,  Prev: Debugging Lalr Grammars,  Up: Lalr Parsing

11.6 A simple example
=====================

Here is the code for a simple calculator implemented by an Lalr(1)
grammar:

     (begin
       (read/lalrp
        (lalr-grammar
         (nl plus mult minus div const lpar rpar)
         (lines
          (())
          ((lines expression nl)    (display "--> ")
                                    (display expression)
                                    (newline))
          ((lines nl)))
         (expression
          ((expression plus term)   (+ expression term))
          ((expression minus term)  (- expression term))
          ((term)                   term))
         (term
          ((term mult factor)       (* term factor))
          ((term div factor)        (/ term factor))
          ((factor)                 factor))
         (factor
          ((lpar expression rpar)   expression)
          ((const)                  const)))

        (regular-grammar ()
         ((+ (or #\tab #\space)) (ignore))
         (#\newline              'nl)
         ((+ digit)              (cons 'const (string->number (the-string))))
         (#\+                    'plus)
         (#\-                    'minus)
         (#\*                    'mult)
         (#\/                    'div)
         (#\(                    'lpar)
         (#\)                    'rpar))

        (current-input-port))
       (reset-eof (current-input-port)))


File: bigloo.info,  Node: Posix Regular Expressions,  Next: Database,  Prev: Lalr Parsing,  Up: Top

12 Posix Regular Expressions
****************************

This whole section has been written by Dorai Sitaram.  It consists in
the documentation of the `pregexp' package that may be found at
`http://www.ccs.neu.edu/~dorai/pregexp/pregexp.html'.


  The regexp notation supported is modeled on Perl's, and includes such
powerful directives as numeric and nongreedy quantifiers, capturing and
non-capturing clustering, POSIX character classes, selective case- and
space-insensitivity, backreferences, alternation, backtrack pruning,
positive and negative lookahead and lookbehind, in addition to the more
basic directives familiar to all regexp users.  A _regexp_ is a string
that describes a pattern.  A regexp matcher tries to _match_ this
pattern against (a portion of) another string, which we will call the
_text string_.  The text string is treated as raw text and not as a
pattern.

  Most of the characters in a regexp pattern are meant to match
occurrences of themselves in the text string.  Thus, the pattern
`"abc"' matches a string that contains the characters `a', `b', `c' in
succession.

  In the regexp pattern, some characters  act as _metacharacters_, and
some character sequences act as _metasequences_.  That is, they specify
something other than their literal selves.  For example, in the pattern
`"a.c"', the characters `a' and `c' do stand for themselves but the
_metacharacter_ `.' can match _any_ character (other than newline).
Therefore, the pattern `"a.c"' matches an `a', followed by _any_
character, followed by a `c'.

  If we needed to match the character `.' itself, we _escape_ it, ie,
precede it with a backslash (`\').  The character sequence `\.' is thus
a _metasequence_, since it doesn't match itself but rather just `.'.
So, to match `a' followed by a literal `.' followed by `c', we use the
regexp pattern `"a\\.c"'.(1) (*note Posix Regular
Expressions-Footnote-1::) Another example of a metasequence is `\t',
which is a readable way to represent the tab character.

  We will call the string representation of a regexp the _U-regexp_,
where _U_ can be taken to mean _Unix-style_ or _universal_, because this
notation for regexps is universally familiar.  Our implementation uses
an intermediate tree-like representation called the _S-regexp_, where
_S_ can stand for _Scheme_, _symbolic_, or _s-expression_.  S-regexps
are more verbose and less readable than U-regexps, but they are much
easier for Scheme's recursive procedures to navigate.

* Menu:

* Regular Expressions Procedures::
* The Regular Expressions Pattern Language::
* An Extended Example::


File: bigloo.info,  Node: Posix Regular Expressions-Footnotes,  Up: Posix Regular Expressions

  (1) The double backslash is an artifact of Scheme strings, not the
regexp pattern itself.  When we want a literal backslash inside a
Scheme string, we must escape it so that it shows up in the string at
all. Scheme strings use backslash as the escape character, so we end up
with two backslashes -- one Scheme-string backslash to escape the
regexp backslash, which then escapes the dot.  Another character that
would need escaping inside a Scheme string is `"'.


File: bigloo.info,  Node: Regular Expressions Procedures,  Next: The Regular Expressions Pattern Language,  Up: Posix Regular Expressions

12.1 Regular Expressions Procedures
===================================

Four procedures `pregexp', `pregexp-match-positions', `pregexp-match',
`pregexp-replace', and `pregexp-replace*' enable compilation and
matching of regular expressions.

 -- bigloo procedure: pregexp U-regexp
     The procedure `pregexp' takes a U-regexp, which is a string, and
     returns an S-regexp, which is a tree.

          (pregexp "c.r") => (:sub (:or (:seq #\c :any #\r)))

     There is rarely any need to look at the S-regexps returned by
     `pregexp'.

 -- bigloo procedure: pregexp-match-positions regexp string
     The procedure `pregexp-match-positions' takes a regexp pattern and
     a text string, and returns a _match_ if the pattern _matches_ the
     text string.  The pattern may be either a U- or an S-regexp.
     (`pregexp-match-positions' will internally compile a U-regexp to
     an S-regexp before proceeding with the matching.  If you find
     yourself calling `pregexp-match-positions' repeatedly with the same
     U-regexp, it may be advisable to explicitly convert the latter
     into an S-regexp once beforehand, using `pregexp', to save
     needless recompilation.)

     `pregexp-match-positions' returns `#f' if the pattern did not
     match the string; and a list of _index pairs_ if it did match. Eg,

          (pregexp-match-positions "brain" "bird")
           => #f
          (pregexp-match-positions "needle" "hay needle stack")
           => ((4 . 10))

     In the second example, the integers 4 and 10 identify the
     substring that was matched. 1 is the starting (inclusive) index
     and 2 the ending (exclusive) index of the matching substring.

          (substring "hay needle stack" 4 10)
           => "needle"

     Here, `pregexp-match-positions''s return list contains only one
     index pair, and that pair represents the entire substring matched
     by the regexp.  When we discuss _subpatterns_ later, we will see
     how a single match operation can yield a list of _submatches_.

     `pregexp-match-positions' takes optional third and fourth
     arguments that specify the indices of the text string within which
     the matching should take place.

          (pregexp-match-positions "needle"
            "his hay needle stack -- my hay needle stack -- her hay needle stack"
            24 43)
           => ((31 . 37))

     Note that the returned indices are still reckoned relative to the
     full text string.

 -- bigloo procedure: pregexp-match regexp string
     The procedure `pregexp-match' is called like
     `pregexp-match-positions' but instead of returning index pairs it
     returns the matching substrings:

          (pregexp-match "brain" "bird")
           => #f
          (pregexp-match "needle" "hay needle stack")
           => ("needle")

     `pregexp-match' also takes optional third and fourth arguments,
     with the same meaning as does `pregexp-match-positions'.

 -- bigloo procedure: pregexp-replace regexp string1 string2
     The procedure `pregexp-replace' replaces the matched portion of
     the text string by another string.  The first argument is the
     regexp, the second the text string, and the third is the _insert
     string_ (string to be inserted).

          (pregexp-replace "te" "liberte" "ty")
           => "liberty"

     If the pattern doesn't occur in the text string, the returned
     string is identical (`eq?') to the text string.

 -- bigloo procedure: pregexp-replace* regexp string1 string2
     The procedure `pregexp-replace*' replaces _all_ matches in the
     text STRING1 by the insert STRING2:

          (pregexp-replace* "te" "liberte egalite fraternite" "ty")
           => "liberty egality fratyrnity"

     As with `pregexp-replace', if the pattern doesn't occur in the text
     string, the returned string is identical (`eq?') to the text
     string.

 -- bigloo procedure: pregexp-split regexp string
     The procedure `pregexp-split' takes two arguments, a regexp
     pattern and a text string, and returns a list of substrings of the
     text string, where the pattern identifies the delimiter separating
     the substrings.

          (pregexp-split ":" "/bin:/usr/bin:/usr/bin/X11:/usr/local/bin")
           => ("/bin" "/usr/bin" "/usr/bin/X11" "/usr/local/bin")

          (pregexp-split " " "pea soup")
           => ("pea" "soup")

     If the first argument can match an empty string, then the list of
     all the single-character substrings is returned.

          (pregexp-split "" "smithereens")
           => ("s" "m" "i" "t" "h" "e" "r" "e" "e" "n" "s")

     To identify one-or-more spaces as the delimiter, take care to use
     the regexp `" +"', not `" *"'.

          (pregexp-split " +" "split pea     soup")
           => ("split" "pea" "soup")

          (pregexp-split " *" "split pea     soup")
           => ("s" "p" "l" "i" "t" "p" "e" "a" "s" "o" "u" "p")

 -- bigloo procedure: pregexp-quote string
     The procedure `pregexp-quote' takes an arbitrary STRING and
     returns a U-regexp (string) that precisely represents it. In
     particular, characters in the input string that could serve as
     regexp metacharacters are escaped with a backslash, so that they
     safely match only themselves.

          (pregexp-quote "cons")
           => "cons"

          (pregexp-quote "list?")
           => "list\\?"

     `pregexp-quote' is useful when building a composite regexp from a
     mix of regexp strings and verbatim strings.


File: bigloo.info,  Node: The Regular Expressions Pattern Language,  Next: An Extended Example,  Prev: Regular Expressions Procedures,  Up: Posix Regular Expressions

12.2 Regular Expressions Pattern Language
=========================================

* Menu:

* Basic assertions::
* Characters and character classes::
* Quantifiers::
* Clusters::
* Alternation::
* Backtracking::
* Looking ahead and behind::

  Here is a complete description of the regexp pattern language
recognized by the `pregexp' procedures.


File: bigloo.info,  Node: Basic assertions,  Next: Characters and character classes,  Up: The Regular Expressions Pattern Language

12.2.1 Basic assertions
-----------------------

The _assertions_ `^' and `$' identify the beginning and the end of the
text string respectively.  They ensure that their adjoining regexps
match at one or other end of the text string.  Examples:

     (pregexp-match-positions "^contact" "first contact") => #f

The regexp fails to match because `contact' does not occur at the
beginning of the text string.

     (pregexp-match-positions "laugh$" "laugh laugh laugh laugh") => ((18 . 23))

The regexp matches the _last_ `laugh'.

  The metasequence `\b' asserts that a _word boundary_ exists.

     (pregexp-match-positions "yack\\b" "yackety yack") => ((8 . 12))

The `yack' in `yackety' doesn't end at a word boundary so it isn't
matched.  The second `yack' does and is.

  The metasequence `\B' has the opposite effect to `\b'.  It asserts
that a word boundary does not exist.

     (pregexp-match-positions "an\\B" "an analysis") => ((3 . 5))

The `an' that doesn't end in a word boundary is matched.


File: bigloo.info,  Node: Characters and character classes,  Next: Quantifiers,  Prev: Basic assertions,  Up: The Regular Expressions Pattern Language

12.2.2 Characters and character classes
---------------------------------------

Typically a character in the regexp matches the same character in the
text string.  Sometimes it is necessary or convenient to use a regexp
metasequence to refer to a single character.  Thus, metasequences `\n',
`\r', `\t', and `\.'  match the newline, return, tab and period
characters respectively.

  The _metacharacter_ period (`.') matches _any_ character other than
newline.

     (pregexp-match "p.t" "pet") => ("pet")

It also matches `pat', `pit', `pot', `put', and `p8t' but not `peat' or
`pfffft'.

  A _character class_ matches any one character from a set of
characters.  A typical format for this is the _bracketed character
class_ `['...`]', which matches any one character from the non-empty
sequence of characters enclosed within the brackets.(1) (*note
Characters and character classes-Footnote-1::)  Thus `"p[aeiou]t"'
matches `pat', `pet', `pit', `pot', `put' and nothing else.

  Inside the brackets, a hyphen (`-') between two characters specifies
the ascii range between the characters.  Eg, `"ta[b-dgn-p]"' matches
`tab', `tac', `tad', _and_ `tag', _and_ `tan', `tao', `tap'.

  An initial caret (`^') after the left bracket inverts the set
specified by the rest of the contents, ie, it specifies the set of
characters _other than_ those identified in the brackets.  Eg,
`"do[^g]"' matches all three-character sequences starting with `do'
except `dog'.

  Note that the metacharacter `^' inside brackets means something quite
different from what it means outside.  Most other metacharacters (`.',
`*', `+', `?', etc) cease to be metacharacters when inside brackets,
although you may still escape them for peace of mind.  `-' is a
metacharacter only when it's inside brackets, and neither the first nor
the last character.

  Bracketed character classes cannot contain other bracketed character
classes (although they contain certain other types of character classes
-- see below).  Thus a left bracket (`[') inside a bracketed character
class doesn't have to be a metacharacter; it can stand for itself.  Eg,
`"[a[b]"' matches `a', `[', and `b'.

  Furthermore, since empty bracketed character classes are disallowed, a
right bracket (`]') immediately occurring after the opening left
bracket also doesn't need to be a metacharacter.  Eg, `"[]ab]"' matches
`]', `a', and `b'.

12.2.3 Some frequently used character classes
---------------------------------------------

Some standard character classes can be conveniently represented as
metasequences instead of as explicit bracketed expressions.  `\d'
matches a digit (`[0-9]'); `\s' matches a whitespace character; and
`\w' matches a character that could be part of a "word".(2) (*note
Characters and character classes-Footnote-2::)

  The upper-case versions of these metasequences stand for the
inversions of the corresponding character classes.  Thus `\D' matches a
non-digit, `\S' a non-whitespace character, and `\W' a non-"word"
character.

  Remember to include a double backslash when putting these
metasequences in a Scheme string:

     (pregexp-match "\\d\\d" "0 dear, 1 have 2 read catch 22 before 9") => ("22")

  These character classes can be used inside a bracketed expression.
Eg, `"[a-z\\d]"' matches a lower-case letter or a digit.

12.2.4 POSIX character classes
------------------------------

A _POSIX character class_ is a special metasequence of the form
`[:'...`:]' that can be used only inside a bracketed expression.  The
POSIX classes supported are

     `[:alnum:]'  letters and digits
     `[:alpha:]'  letters
     `[:algor:]'  the letters `c', `h', `a' and `d'
     `[:ascii:]'  7-bit ascii characters
     `[:blank:]'  widthful whitespace, ie, space and tab
     `[:cntrl:]'  ``control'' characters, viz, those with code `<' 32
     `[:digit:]'  digits, same as `\d'
     `[:graph:]'  characters that use ink
     `[:lower:]'  lower-case letters
     `[:print:]'  ink-users plus widthful whitespace
     `[:space:]'  whitespace, same as `\s'
     `[:upper:]'  upper-case letters
     `[:word:]'   letters, digits, and underscore, same as `\w'
     `[:xdigit:]' hex digits

For example, the regexp  `"[[:alpha:]_]"' matches a letter or
underscore.

     (pregexp-match "[[:alpha:]_]" "--x--") => ("x")
     (pregexp-match "[[:alpha:]_]" "--_--") => ("_")
     (pregexp-match "[[:alpha:]_]" "--:--") => #f

  The POSIX class notation is valid _only_ inside a bracketed
expression.  For instance, `[:alpha:]', when not inside a bracketed
expression, will _not_ be read as the letter class.  Rather it is (from
previous principles) the character class containing the characters `:',
`a', `l', `p', `h'.

     (pregexp-match "[[:alpha:]]" "--a--") => ("a")
     (pregexp-match "[[:alpha:]]" "--_--") => #f

  By placing a caret (`^') immediately after `[:', you get the
inversion of that POSIX character class.  Thus, `[:^alpha]' is the
class containing all characters except the letters.


File: bigloo.info,  Node: Characters and character classes-Footnotes,  Up: Characters and character classes

  (1) Requiring a bracketed character class to be non-empty is not a
limitation, since an empty character class can be more easily
represented by an empty string.

  (2) Following regexp custom, we identify "word" characters as
`[A-Za-z0-9_]', although these are too restrictive for what a Schemer
might consider a "word".


File: bigloo.info,  Node: Quantifiers,  Next: Clusters,  Prev: Characters and character classes,  Up: The Regular Expressions Pattern Language

12.2.5 Quantifiers
------------------

The _quantifiers_ `*', `+', and `?' match respectively: zero or more,
one or more, and zero or one instances of the preceding subpattern.

     (pregexp-match-positions "c[ad]*r" "cadaddadddr") => ((0 . 11))
     (pregexp-match-positions "c[ad]*r" "cr")          => ((0 . 2))

     (pregexp-match-positions "c[ad]+r" "cadaddadddr") => ((0 . 11))
     (pregexp-match-positions "c[ad]+r" "cr")          => #f

     (pregexp-match-positions "c[ad]?r" "cadaddadddr") => #f
     (pregexp-match-positions "c[ad]?r" "cr")          => ((0 . 2))
     (pregexp-match-positions "c[ad]?r" "car")         => ((0 . 3))

12.2.6 Numeric quantifiers
--------------------------

You can use braces to specify much finer-tuned quantification than is
possible with `*', `+', `?'.

  The quantifier `{m}' matches _exactly_ `m' instances of the preceding
_subpattern_.  `m' must be a nonnegative integer.

  The quantifier `{m,n}' matches at least `m' and at most `n'
instances.  `m' and `n' are nonnegative integers with `m <= n'.  You
may omit either or both numbers, in which case `m' defaults to 0 and
`n' to infinity.

  It is evident that `+' and `?' are abbreviations for `{1,}' and
`{0,1}' respectively.  `*' abbreviates `{,}', which is the same as
`{0,}'.

     (pregexp-match "[aeiou]{3}" "vacuous")  => ("uou")
     (pregexp-match "[aeiou]{3}" "evolve")   => #f
     (pregexp-match "[aeiou]{2,3}" "evolve") => #f
     (pregexp-match "[aeiou]{2,3}" "zeugma") => ("eu")

12.2.7 Non-greedy quantifiers
-----------------------------

The quantifiers described above are _greedy_, ie, they match the
maximal number of instances that would still lead to an overall match
for the full pattern.

     (pregexp-match "<.*>" "<tag1> <tag2> <tag3>")
      => ("<tag1> <tag2> <tag3>")

  To make these quantifiers _non-greedy_, append a `?' to them.
Non-greedy quantifiers match the minimal number of instances needed to
ensure an overall match.

     (pregexp-match "<.*?>" "<tag1> <tag2> <tag3>") => ("<tag1>")

  The non-greedy quantifiers are respectively: `*?', `+?', `??',
`{m}?', `{m,n}?'.  Note the two uses of the metacharacter `?'.


File: bigloo.info,  Node: Clusters,  Next: Alternation,  Prev: Quantifiers,  Up: The Regular Expressions Pattern Language

12.2.8 Clusters
---------------

_Clustering_, ie, enclosure within parens `('...`)', identifies the
enclosed _subpattern_ as a single entity.  It causes the matcher to
_capture_ the _submatch_, or the portion of the string matching the
subpattern, in addition to the overall match.

     (pregexp-match "([a-z]+) ([0-9]+), ([0-9]+)" "jan 1, 1970")
      => ("jan 1, 1970" "jan" "1" "1970")

  Clustering also causes a following quantifier to treat the entire
enclosed subpattern as an entity.

     (pregexp-match "(poo )*" "poo poo platter") => ("poo poo " "poo ")

  The number of submatches returned is always equal to the number of
subpatterns specified in the regexp, even if a particular subpattern
happens to match more than one substring or no substring at all.

     (pregexp-match "([a-z ]+;)*" "lather; rinse; repeat;")
      => ("lather; rinse; repeat;" " repeat;")

Here the `*'-quantified subpattern matches three times, but it is the
last submatch that is returned.

  It is also possible for a quantified subpattern to fail to match,
even if the overall pattern matches.  In such cases, the failing
submatch is represented by `#f'.

     (define date-re
       ;match `month year' or `month day, year'.
       ;subpattern matches day, if present
       (pregexp "([a-z]+) +([0-9]+,)? *([0-9]+)"))

     (pregexp-match date-re "jan 1, 1970")
      => ("jan 1, 1970" "jan" "1," "1970")

     (pregexp-match date-re "jan 1970")
      => ("jan 1970" "jan" #f "1970")

12.2.9 Backreferences
---------------------

Submatches can be used in the insert string argument of the procedures
`pregexp-replace' and `pregexp-replace*'.  The insert string can use
`\n' as a _backreference_ to refer back to the _n_th submatch, ie, the
substring that matched the _n_th subpattern.  `\0' refers to the entire
match, and it can also be specified as `\&'.

     (pregexp-replace "_(.+?)_"
       "the _nina_, the _pinta_, and the _santa maria_"
       "*\\1*")
      => "the *nina*, the _pinta_, and the _santa maria_"

     (pregexp-replace* "_(.+?)_"
       "the _nina_, the _pinta_, and the _santa maria_"
       "*\\1*")
      => "the *nina*, the *pinta*, and the *santa maria*"

     ;recall: \S stands for non-whitespace character

     (pregexp-replace "(\\S+) (\\S+) (\\S+)"
       "eat to live"
       "\\3 \\2 \\1")
      => "live to eat"

  Use `\\' in the insert string to specify a literal backslash.  Also,
`\$' stands for an empty string, and is useful for separating a
backreference `\n' from an immediately following number.

  Backreferences can also be used within the regexp pattern to refer
back to an already matched subpattern in the pattern.  `\n' stands for
an exact repeat of the _n_th submatch.(1) (*note Clusters-Footnote-1::)

     (pregexp-match "([a-z]+) and \\1"
       "billions and billions")
      => ("billions and billions" "billions")

Note that the backreference is not simply a repeat of the previous
subpattern.  Rather it is a repeat of _the particular  substring
already matched by the subpattern_.

  In the above example, the backreference can only match `billions'.
It will not match `millions', even though the subpattern it harks back
to -- `([a-z]+)' --  would have had no problem doing so:

     (pregexp-match "([a-z]+) and \\1"
       "billions and millions")
      => #f

  The following corrects doubled words:

     (pregexp-replace* "(\\S+) \\1"
       "now is the the time for all good men to to come to the aid of of the party"
       "\\1")
      => "now is the time for all good men to come to the aid of the party"

  The following marks all immediately repeating patterns in a number
string:

     (pregexp-replace* "(\\d+)\\1"
       "123340983242432420980980234"
       "{\\1,\\1}")
      => "12{3,3}40983{24,24}3242{098,098}0234"

12.2.10 Non-capturing clusters
------------------------------

It is often required to specify a cluster (typically for
quantification) but without triggering the capture of submatch
information.  Such clusters are called _non-capturing_.  In such cases,
use `(?:' instead of `(' as the cluster opener.  In the following
example, the  non-capturing cluster eliminates the "directory" portion
of a given pathname, and the capturing cluster  identifies the basename.

     (pregexp-match "^(?:[a-z]*/)*([a-z]+)$"
       "/usr/local/bin/mzscheme")
      => ("/usr/local/bin/mzscheme" "mzscheme")

12.2.11 Cloisters
-----------------

The location between the `?' and the `:' of a non-capturing cluster is
called a _cloister_.(2) (*note Clusters-Footnote-2::)  You can put
_modifiers_ there that will cause the enclustered subpattern to be
treated specially.  The modifier `i' causes the subpattern to match
_case-insensitively_:

     (pregexp-match "(?i:hearth)" "HeartH") => ("HeartH")

  The modifier `x' causes the subpattern to match
_space-insensitively_, ie, spaces and comments within the subpattern
are ignored.  Comments are introduced as usual with a semicolon (`;')
and extend till the end of the line.  If you need to include a literal
space or semicolon in a space-insensitized subpattern, escape it with a
backslash.

     (pregexp-match "(?x: a   lot)" "alot")
      => ("alot")

     (pregexp-match "(?x: a  \\  lot)" "a lot")
      => ("a lot")

     (pregexp-match "(?x:
        a \\ man  \\; \\   ; ignore
        a \\ plan \\; \\   ; me
        a \\ canal         ; completely
        )"
      "a man; a plan; a canal")
      => ("a man; a plan; a canal")

The global variable `*pregexp-comment-char*' contains the comment
character (`#\;').  For Perl-like comments,

     (set! *pregexp-comment-char* #\#)

  You can put more than one modifier in the cloister.

     (pregexp-match "(?ix:
        a \\ man  \\; \\   ; ignore
        a \\ plan \\; \\   ; me
        a \\ canal         ; completely
        )"
      "A Man; a Plan; a Canal")
      => ("A Man; a Plan; a Canal")

  A minus sign before a modifier inverts its meaning.  Thus, you can
use `-i' and `-x' in a _subcluster_ to overturn the insensitivities
caused by an enclosing cluster.

     (pregexp-match "(?i:the (?-i:TeX)book)"
       "The TeXbook")
      => ("The TeXbook")

This regexp will allow any casing for `the' and `book' but insists that
`TeX' not be differently cased.


File: bigloo.info,  Node: Clusters-Footnotes,  Up: Clusters

  (1) `\0', which is useful in an insert string, makes no  sense within
the regexp pattern, because the entire regexp has not matched yet that
you could refer back to it.

  (2) A useful, if terminally cute, coinage from the abbots of Perl.


File: bigloo.info,  Node: Alternation,  Next: Backtracking,  Prev: Clusters,  Up: The Regular Expressions Pattern Language

12.2.12 Alternation
-------------------

You can specify a list of _alternate_ subpatterns by separating them by
`|'.   The `|' separates subpatterns in the nearest enclosing cluster
(or in the entire pattern string if there are no enclosing parens).

     (pregexp-match "f(ee|i|o|um)" "a small, final fee")
      => ("fi" "i")

     (pregexp-replace* "([yi])s(e[sdr]?|ing|ation)"
        "it is energising to analyse an organisation
        pulsing with noisy organisms"
        "\\1z\\2")
      => "it is energizing to analyze an organization
        pulsing with noisy organisms"

  Note again that if you wish to use clustering merely to specify a
list of alternate subpatterns but do not want the submatch, use `(?:'
instead of `('.

     (pregexp-match "f(?:ee|i|o|um)" "fun for all")
      => ("fo")

  An important thing to note about alternation is that the leftmost
matching alternate is picked regardless of its length.  Thus, if one of
the alternates is a prefix of a later alternate, the latter may not have
a chance to match.

     (pregexp-match "call|call-with-current-continuation"
       "call-with-current-continuation")
      => ("call")

  To allow the longer alternate to have a shot at matching, place it
before the shorter one:

     (pregexp-match "call-with-current-continuation|call"
       "call-with-current-continuation")
      => ("call-with-current-continuation")

  In any case, an overall match for the entire regexp is always
preferred to an overall nonmatch.  In the following, the longer
alternate still wins, because its preferred shorter prefix fails to
yield an overall match.

     (pregexp-match "(?:call|call-with-current-continuation) constrained"
       "call-with-current-continuation constrained")
      => ("call-with-current-continuation constrained")


File: bigloo.info,  Node: Backtracking,  Next: Looking ahead and behind,  Prev: Alternation,  Up: The Regular Expressions Pattern Language

12.2.13 Backtracking
--------------------

We've already seen that greedy quantifiers match the maximal number of
times, but the overriding priority is that the overall match succeed.
Consider

     (pregexp-match "a*a" "aaaa")

The regexp consists of two subregexps, `a*' followed by `a'.  The
subregexp `a*' cannot be allowed to match all four `a''s in the text
string `"aaaa"', even though `*' is a greedy quantifier.  It may match
only the first three, leaving the last one for the second subregexp.
This ensures that the full regexp matches successfully.

  The regexp matcher accomplishes this via a process called
_backtracking_.  The matcher tentatively allows the greedy quantifier
to match all four `a''s, but then when it becomes clear that the
overall match is in jeopardy, it _backtracks_ to a less greedy match of
_three_ `a''s.  If even this fails, as in the call

     (pregexp-match "a*aa" "aaaa")

the matcher backtracks even further.  Overall failure is conceded only
when all possible backtracking has been tried with no success.

  Backtracking is not restricted to greedy quantifiers.  Nongreedy
quantifiers match as few instances as possible, and progressively
backtrack to more and more instances in order to attain an overall
match.  There is backtracking in alternation too, as the more rightward
alternates are tried when locally successful leftward ones fail to
yield an overall match.

12.2.14 Disabling backtracking
------------------------------

Sometimes it is efficient to disable backtracking.  For example, we may
wish  to  _commit_ to a choice, or we know that trying alternatives is
fruitless.  A nonbacktracking regexp is enclosed in `(?>'...`)'.

     (pregexp-match "(?>a+)." "aaaa")
      => #f

  In this call, the subregexp `?>a*' greedily matches all four `a''s,
and is denied the opportunity to backpedal.  So the overall match is
denied.  The effect of the regexp is therefore to match one or more
`a''s followed by something that is definitely non-`a'.


File: bigloo.info,  Node: Looking ahead and behind,  Prev: Backtracking,  Up: The Regular Expressions Pattern Language

12.2.15 Looking ahead and behind
--------------------------------

You can have assertions in your pattern that look _ahead_ or _behind_
to ensure that a subpattern does or does not occur.   These "look
around" assertions are specified by putting the subpattern checked for
in a cluster whose leading characters are: `?=' (for positive
lookahead), `?!' (negative lookahead), `?<=' (positive lookbehind),
`?<!' (negative lookbehind).  Note that the subpattern in the assertion
does not generate a match in the final result.  It merely allows or
disallows the rest of the match.

12.2.16 Lookahead
-----------------

Positive lookahead (`?=') peeks ahead to ensure that its subpattern
_could_ match.

     (pregexp-match-positions "grey(?=hound)"
       "i left my grey socks at the greyhound")
      => ((28 . 32))

The regexp `"grey(?=hound)"' matches `grey', but _only_ if it is
followed by `hound'.  Thus, the first `grey' in the text string is not
matched.

  Negative lookahead (`?!') peeks ahead to ensure that its subpattern
could not possibly match.

     (pregexp-match-positions "grey(?!hound)"
       "the gray greyhound ate the grey socks")
      => ((27 . 31))

The regexp `"grey(?!hound)"' matches `grey', but only if it is _not_
followed by `hound'.  Thus the `grey' just before `socks' is matched.

12.2.17 Lookbehind
------------------

Positive lookbehind (`?<=') checks that its subpattern _could_ match
immediately to the left of the current position in the text string.

     (pregexp-match-positions "(?<=grey)hound"
       "the hound in the picture is not a greyhound")
      => ((38 . 43))

The regexp `(?<=grey)hound' matches `hound', but only if it is preceded
by `grey'.

  Negative lookbehind (`?<!') checks that its subpattern could not
possibly match immediately to the left.

     (pregexp-match-positions "(?<!grey)hound"
       "the greyhound in the picture is not a hound")
      => ((38 . 43))

  The regexp `(?<!grey)hound' matches `hound', but only if it is _not_
preceded by `grey'.

  Lookaheads and lookbehinds can be convenient when they are not
confusing.


File: bigloo.info,  Node: An Extended Example,  Prev: The Regular Expressions Pattern Language,  Up: Posix Regular Expressions

12.3 An Extended Example
========================

Here's an extended example from Friedl that covers many of the features
described above.  The problem is to fashion a regexp that will match any
and only IP addresses or _dotted quads_, ie, four numbers separated by
three dots, with each number between 0 and 255.  We will use the
commenting mechanism to build the final regexp with clarity.  First, a
subregexp `n0-255' that matches 0 through 255.

     (define n0-255
       "(?x:
       \\d          ;  0 through   9
       | \\d\\d     ; 00 through  99
       | [01]\\d\\d ;000 through 199
       | 2[0-4]\\d  ;200 through 249
       | 25[0-5]    ;250 through 255
       )")

  The first two alternates simply get all single- and double-digit
numbers.  Since 0-padding is allowed, we need to match both 1 and 01.
We need to be careful when getting 3-digit numbers, since numbers above
255 must be excluded.  So we fashion alternates to get 000 through 199,
then 200 through 249, and finally 250 through 255.(1) (*note An
Extended Example-Footnote-1::)

  An IP-address is a string that consists of four `n0-255's with three
dots separating them.

     (define ip-re1
       (string-append
         "^"        ;nothing before
         n0-255     ;the first n0-255,
         "(?x:"     ;then the subpattern of
         "\\."      ;a dot followed by
         n0-255     ;an n0-255,
         ")"        ;which is
         "{3}"      ;repeated exactly 3 times
         "$"        ;with nothing following
         ))

  Let's try it out.

     (pregexp-match ip-re1 "1.2.3.4")        => ("1.2.3.4")
     (pregexp-match ip-re1 "55.155.255.265") => #f

  which is fine, except that we also have

     (pregexp-match ip-re1 "0.00.000.00") => ("0.00.000.00")

  All-zero sequences are not valid IP addresses!  Lookahead to the
rescue.  Before starting to match `ip-re1', we look ahead to ensure we
don't have all zeros.  We could use positive lookahead to ensure there
_is_ a digit other than zero.

     (define ip-re
       (string-append
         "(?=.*[1-9])" ;ensure there's a non-0 digit
         ip-re1))

  Or we could use negative lookahead to ensure that what's ahead isn't
composed of _only_ zeros and dots.

     (define ip-re
       (string-append
         "(?![0.]*$)" ;not just zeros and dots
                      ;(note: dot is not metachar inside [])
         ip-re1))

  The regexp `ip-re' will match all and only valid IP addresses.

     (pregexp-match ip-re "1.2.3.4") => ("1.2.3.4")
     (pregexp-match ip-re "0.0.0.0") => #f


File: bigloo.info,  Node: An Extended Example-Footnotes,  Up: An Extended Example

  (1) Note that `n0-255' lists prefixes as preferred alternates,
something we cautioned against in section *note Alternation::. However,
since we intend to anchor this subregexp explicitly to force an overall
match, the order of the alternates does not matter.


File: bigloo.info,  Node: Database,  Next: Errors and Assertions,  Prev: Posix Regular Expressions,  Up: Top

13 Database
***********

Bigloo supports database programming. The current version proposes a
SQLite binding.

* Menu:

* SQLite::


File: bigloo.info,  Node: SQLite,  Up: Database

13.1 SQLite
===========

The Bigloo's C back-end supports SQL queries. It relies on the SQLite
library (`http://www.sqlite.org/'). The SQLite binding is accessible to
Bigloo via the `sqlite' library. Here is an example of module that uses
this library.

     (module example1
       (library sqlite))

     (let ((db (instantiate::sqlite)))
       ...)

 -- Bigloo Sqlite class: sqlite
          (class sqlite
             (path::bstring read-only (default ":memory:")))

     The instances of the class `sqlite' hold SQLite databases. A
     database may be permanently stored on a disk or loaded in memory.
     The class attribute `path' is the location on the disk where the
     database is stored. The special path `:memory:' denotes in-memory
     databases. When an instance is created a SQLite database is
     _opened_.

     Example:
          (define db1 (instantiate::sqlite (path "/tmp/foo.db")))
          (define db2 (instantiate::sqlite))

     Binds the global variable DB1 to a database that is stored on the
     file system at location `/tmp/foo.db'. This example also binds the
     global variable DB2 to an in-memory SQLite database.

 -- Bigloo Sqlite function: sqlite-close SQLITE
     This function closes a database previously opened by creating an
     instance of the class `sqlite'.

     Example:
          (let ((db (instantiate::sqlite)))
            (sqlite-exec db "CREATE TABLE table1 (x INTEGER, y INTEGER)")
            (sqlite-exec db "INSERT INTO table1 VALUES( ~a, ~a )" 1 4)
            (sqlite-close db))

 -- Bigloo Sqlite function: sqlite-format STRING ARG ...
     Constructs a string of characters representing an SQLite commands.
     This function acts as `format' (see *note Input and Output::). It
     is augmented with three additional escape sequence: `~q', `~k',
     and `~l'. The first one build a string of characters where the
     characters denoting SQL strings (i.e., the character `'') is
     automatically escaped. The escape character `~k' introduces a list
     of SQL strings. The escape character `~l' introduces a SQL list.

     Summary of all escape codes:
        * `~a' The corresponding value is inserted into the string as
          if printed with display.

        * `~s' The corresponding value is inserted into the string as
          if printed with write.

        * `~%' A newline is inserted.

        * `~~' A tilde `~' is inserted.

        * `~q' An SQL escaped string.

        * `~l' Introduces a list (comma separated).

        * `~k' Introduces a list of SQL strings.

     Examples:

          (module example
             (library sqlite))

          (sqlite-format "~a" "foo'bar") => "foo'bar"
          (sqlite-format "~q" "foo'bar") => "'foo''bar'"
          (sqlite-format "~a" '("foo'bar" "foo")) => "(foo'bar foo)"
          (sqlite-format "~k" '("foo'bar" "foo")) => "'foo''bar','foo'"
          (sqlite-format "~l" '("foo'bar" "foo")) => "foo'bar,foo"

 -- Bigloo Sqlite function: sqlite-exec SQLITE STRING ARG ...
     The function `sqlite-exec' _executes_ an SQLite command. The
     command is the built by implicitly invoking `sqlite-format' on
     STRING and the optional ARG arguments. This function returns a
     possibly list empty.  The elements of the list are filled by the
     SQLite engine. In particular, on a query, each element of the list
     is a vector denoting a row of the searched tables.

     Example:
          (module example
             (library sqlite))

          (define *db* (instantiate::sqlite))

          (sqlite-exec *db* "CREATE TABLE foo (x INTEGER, y INTEGER)")
          (for-each (lambda (x)
          		(sqlite-exec *db*  "INSERT INTO foo VALUES(~A, ~A)" x (* x x)))
          	     (iota 10))
          (sqlite-exec *db* "SELECT * FROM foo")
             => 9


 -- Bigloo Sqlite function: sqlite-eval SQLITE PROCEDURE STRING ARG ...
     The function `sqlite-eval' invokes a SQLite command built by
     implicitly invoking `sqlite-format' on STRING and the optional ARG
     arguments. The result of the function is built by applying
     PROCEDURE to the first value returned by the SQLite call.

 -- Bigloo Sqlite function: sqlite-map SQLITE PROCEDURE STRING ARG ...
     The function `sqlite-map' invokes a SQLite command built by
     implicitly invoking `sqlite-format' on STRING and the optional ARG
     arguments. The result is a list whose elements are built by
     applying PROCEDURE to all the values returned by the SQLite call.

     Example:

          (module example
             (library sqlite))

          (define *db* (instantiate::sqlite))

          (sqlite-exec *db* "CREATE TABLE foo (x INTEGER, y INTEGER)")
          (for-each (lambda (x)
          		(sqlite-exec *db*  "INSERT INTO foo VALUES(~A, ~A)" x (* x x)))
          	     (iota 10))
          (sqlite-map *db*
            (lambda (s1 s2) (+ (string->integer s1) (string->integer s2)))
            "SELECT * FROM foo")
             => (0 2 6 12 20 30 42 56 72 90)

  Example2:
     (module example
        (library sqlite))

     (define *db* (instantiate::sqlite))

     (sqlite-exec *db* "CREATE TABLE foo (x INTEGER, y INTEGER)")
     (for-each (lambda (x)
     		(sqlite-exec *db*  "INSERT INTO foo VALUES(~A, ~A)" x (* x x)))
     	     (iota 10))
     (sqlite-map *db* vector "SELECT * FROM foo")
        => '(#("0" "0")
     	#("1" "1")
     	#("2" "4")
     	#("3" "9")
     	#("4" "16")
     	#("5" "25")
     	#("6" "36")
     	#("7" "49")
     	#("8" "64")
     	#("9" "81"))

 -- Bigloo Sqlite function: sqlite-last-insert-rowid SQLITE
     Returns the SQLite _rowid_ of the last inserted row.


File: bigloo.info,  Node: Errors and Assertions,  Next: Tracing,  Prev: Database,  Up: Top

14 Errors and Assertions
************************

14.1 Errors and Warnings
========================

Bigloo permits to signal an error via the `error' function. Errors are
implemented by the means of exceptions (see `with-exception-handler',
`with-handler', and `raise' forms). Assertions allow the checking of
predicates at certain points in programs.

 -- bigloo procedure: error proc msg obj
     This form signals an error by calling the current error handler
     with PROC, MSG and OBJ as arguments.

          (define (foo l)
             (if (not (pair? l))
                 (error "foo" "argument not a pair" l)
                 (car l)))

          (foo 4)
          error--> *** ERROR:bigloo:foo:
                   argument not a pair -- 4

     Switching on the `-g' compilation switch enables stack dumping
     when the `error' function is invoked. That is, when a program is
     compiled with `-g' and when, at runtime, the shell variable
     `BIGLOOSTACKDEPTH' is set and contains a number, an execution
     stack of depth `BIGLOOSTACKDEPTH' is printed when an error is
     raised.

 -- bigloo procedure: error/location proc msg obj file location
     This form signals an error by calling the current error handler
     with PROC, MSG and OBJ as arguments. The error is prompted in
     FILE, at character position LOCATION.

          (define (foo l)
             (if (not (pair? l))
                 (error/location
                   "foo" "argument not a pair" l "foo.scm" 115)
                 (car l)))

          (foo 4)
          error--> File "foo.scm", line 4, character 115:
                   #       (car l)))
                   #       ^
                   # *** ERROR:bigloo:foo
                   # argument not a pair -- 4
                       0. FOO
                       1. DYNAMIC-WIND
                       2. INTERP
                       3. ENGINE
                       4. MAIN

 -- bigloo procedure: get-trace-stack size
 -- bigloo procedure: dump-trace-stack output-port size
     Switching on the `-g' compilation switch enables stack dumping
     *note Compiler Description::. That is, the list of the pending
     calls can be dumped by the runtime-system. The function
     `get-trace-stack' builds such a trace. The list built by
     `get-trace-stack' only contains the SIZE top most pending calls.
     The function `dump-trace-stack' displays a representation of this
     stack on the OUTPUT-PORT.


 -- bigloo procedure: warning/location file location [arg]...
     This form signals a warning. That is, is ARG are displayed on the
     standard error port. The warning is prompted in FILE at character
     position LOCATION.

          (define (foo l)
             (if (not (pair? l))
                 (begin
                    (warning/location
                      "foo.scm" 154 "foo:" "argument not a pair -- " l)
                    '())
                 (car l)))

          (foo 4)
          -| File "foo.scm", line 6, character 154:
             #       (car l)))
             #       ^
             # *** WARNING:bigloo:foo:
             argument not a pair -- 4
          => '()

 -- bigloo procedure: exception-notify exc
 -- bigloo procedure: error-notify err
 -- bigloo procedure: warning-notify err
     Display a message describing the error or warning on the default
     error port.

14.2 Exceptions
===============

 -- SRFI-18 function: current-exception-handler
     Returns the current exception handler with is a 0-ary procedure.

 -- SRFI-18 function: with-exception-handler handler thunk
     Returns the result(s) of calling THUNK with no arguments. The
     HANDLER, which must be a procedure, is installed as the current
     exception handler in the dynamic environment in effect during the
     call to THUNK. When possible, prefer `with-handler' to
     `with-exception-handler' because the former is more efficient than
     the latter.

 -- bigloo form: with-handler handler body
     Returns the result(s) of evaluating BODY. The HANDLER, which must
     be a procedure, is installed as the current exception handler in
     the dynamic environment in effect during the evaluation of BODY.
     Contrarily to `with-exception-handler', is an exception is raised,
     the HANDLER is invoked and the value of the `with-handler' form is
     the value produced by invoking the HANDLER.

     JVM note: When executed within a JVM, the form `with-handler' also
     catches Java exceptions.

     The form `with-handler' is intrinsically more efficient than the
     function `with-exception-handler'. From a semantics point of view,
     `with-handler' could be re-written in terms of
     `with-exception-handler' such as:

          (with-handler handler1 body1)
          ==
          (bind-exit (exit)
            (with-exception-handler
              (lambda (e)
                (exit (handler1 e)))
              (lambda ()
                body)))


 -- SRFI-18 function: raise obj
     Calls the current exception handler with obj as the single
     argument. obj may be any Scheme object. Note that invoking the
     current handler does not escape from the current computation. It
     is up the to handler to perform the escape. It an error, signaled
     by the runtime system, if the current exception handler returns.

          (define (f n)
            (if (< n 0) (raise "negative arg") (sqrt n))))

          (define (g)
            (bind-exit (return)
              (with-exception-handler
                (lambda (exc)
                  (return
                    (if (string? exc)
                        (string-append "error: " exc)
                        "unknown error")))
                (lambda ()
                  (write (f 4.))
                  (write (f -1.))
                  (write (f 9.))))))

          (g)  -| 2. and returns "error: negative arg"

  The standard Bigloo runtime system uses the following classes for
signaling errors and warnings:

   * `&exception' which is defined as: 
          (class &exception
             (fname read-only (default #f))
             (location read-only (default #f)))

   * `&error' defined as: 
          (class &error::&exception
             (proc read-only)
             (msg read-only)
             (obj read-only))

   * `&type-error' defined as: 

          (class &type-error::&error
             (type read-only))

   * `&io-error' defined as: 

          (class &io-error::&error)

   * `&io-port-error' defined as: 

          (class &io-port-error::&io-error)

   * `&io-read-error' defined as: 

          (class &io-read-error::&io-port-error)

   * `&io-write-error' defined as: 

          (class &io-write-error::&io-port-error)

   * `&io-closed-error' defined as: 

          (class &io-closed-error::&io-port-error)

   * `&io-file-not-found-error' defined as: 

          (class &io-file-not-found-error::&io-error)

   * `&io-parse-error' defined as:

          (class &io-parse-error::&io-error)

   * `&io-unknown-host-error' defined as: 

          (class &io-unknown-host-error::&io-error)

   * `&io-malformed-url-error' defined as: 

          (class &io-malformed-url-error::&io-error)

   * `&process-exception' defined as: 

          (class &process-exception::&error)

   * `&warning' defined as: 

          (class &warning::&exception
             (args read-only))

   * `&eval-warning' defined as: 

          (class &warning::&warning)

14.3 Deprecated try form
========================

 -- bigloo syntax: try exp handler
     This form is deprecated. As much as possible, it should be
     replaced with true exceptions (i.e., `with-exception-handler' and
     `raise').  The argument EXP is evaluated. If an error is raised,
     the HANDLER is called. The argument HANDLER is a procedure of four
     arguments. Its first argument is the continuation of TRY. The
     other arguments are PROC, MES and OBJ. Invoking the first argument
     will resume after the error.

          (let ((handler (lambda (escape proc mes obj)
                            (print "***ERROR:" proc ":" mes " -- " obj)
                            (escape #f))))
             (try (car 1) handler))
             -| ***ERROR:CAR:not a pair -- 1
             => #f

     The argument HANDLER is not evaluated in the dynamic scope of its
     `try' form. That is:

          (let ((handler (lambda (escape proc mes obj)
                            (escape (car obj)))))
             (try (car 1) handler))
             error--> *** ERROR:bigloo:CAR
                      Type `PAIR' expected, `BINT' provided -- 1

Some library functions exist to help in writing handlers:

 -- bigloo procedure: warning [arg]...
     This form signals a warning. That is, is ARG are displayed on the
     standard error port.

          (define (foo l)
             (if (not (pair? l))
                 (begin
                    (warning "foo:" "argument not a pair -- " l)
                    '())
                 (car l)))

          (foo 4)
          -| *** WARNING:bigloo:foo:
             argument not a pair -- 4
          => '()

14.4 Assertions
===============

 -- bigloo syntax: assert (var...) s-expression
     Assertions can be enabled or disabled using Bigloo's compilation
     flags `-g' flag to enable them). If the assertions are disabled
     they are not evaluated. If an assertion is evaluated, if the
     expression EXP does not evaluate to `#t', an error is signaled and
     the interpreter is launched in an environment where VAR... are
     bound to their current values.

     Assertion forms are legal expressions which _always_ evaluate to
     the `unspecified' object.

     Here is an example of assertion usage:

          (module foo
             (eval (export foo)))

          (define (foo x y)
             [assert (x y) (< x y)]
             (labels ((gee (t)
                           [assert (t) (>= t 0)]
                           (let ((res (+ x t)))
                              [assert (res t) (> res 10)]
                              res)))
                (set! x (gee y))
                [assert (x) (> x 10)]
                x))

          (repl)

     This module is compiled with the `-g' flag to enable assertions,
     then the produced executable is run:

          $ a.out

          1:=> (foo 1 2)

          File "foo.scm", line 9, character 158:
          #                   [assert (res t) (> res 10)]
          #                   ^
          # *** ERROR:bigloo:assert
          # assertion failed - (BEGIN (> RES 10))
              0. GEE
              1. FOO
          ----------------------
          Variables' value are :
             RES : 3
             T : 2
          ----------------------
          *:=> ^D
          File "foo.scm", line 12, character 228:
          #      [assert (x) (> x 10)]
          #      ^
          # *** ERROR:bigloo:assert
          # assertion failed - (BEGIN (> X 10))
              0. FOO
          ----------------------
          Variables' value are :
             X : 3
          ----------------------

          *:=> 3
          1:=> (foo 1 2)
          File "foo.scm", line 9, character 158:
          #                   [assert (res t) (> res 10)]
          #                   ^
          # *** ERROR:bigloo:assert
          # assertion failed - (BEGIN (> RES 10))
              0. GEE
              1. FOO
          ----------------------
          Variables' value are :
             RES : 3
             T : 2
          ----------------------

          *:=>


File: bigloo.info,  Node: Tracing,  Next: Eval,  Prev: Errors and Assertions,  Up: Top

15 Tracing
**********

Bigloo provides a trace facility whose is intended for simple debugging
tasks. It is a replacement for user `display's that clutters the source
code. Here is a typical example using it:

     (define (foo x)
        (with-trace 1 'foo
           (let loop ((n x))
     	 (with-trace 2 'loop
     	    (trace-item "n=" n)
     	    (when (> n 0)
     	       (let liip ((m n))
     		  (with-trace 2 'liip
     		     (trace-item "m=" m))
     		  (when (> m 0)
     		     (liip (- m 1))))
     	       (loop (- n 1)))))))

     (foo 3)

  which produces the following output:

     + foo
       |--+ loop
       |  |- n=3
       |  |--+ liip
       |  |  |- m=3
       |  |--+ liip
       |  |  |- m=2
       |  |--+ liip
       |  |  |- m=1
       |  |--+ liip
       |  |  |- m=0
       |  |--+ loop
       |  |  |- n=2
       |  |  |--+ liip
       |  |  |  |- m=2
       |  |  |--+ liip
       |  |  |  |- m=1
       |  |  |--+ liip
       |  |  |  |- m=0
       |  |  |--+ loop
       |  |  |  |- n=1
       |  |  |  |--+ liip
       |  |  |  |  |- m=1
       |  |  |  |--+ liip
       |  |  |  |  |- m=0
       |  |  |  |--+ loop
       |  |  |  |  |- n=0

  Traces generation is controlled by a set of functions and parameters
(see *note Parameters::). The functions are described in this chapter.

 -- bigloo syntax: with-trace level label . body
     The variable LEVEL is the level of a trace. It is a positive
     integer. It enables simple filtering for traces. A trace is
     displayed if and only if the debugging level used to compile or to
     execute the program is greater than the trace level. The variable
     LABEL is a label, .e.i., an identifier denoting the trace. This
     identifier will be displayed in debug mode.  The variable BODY is
     the body of the form, that is, the expression to be evaluated.

     Unless a trace is activated `(with-trace lv la body)' (when its
     level LV is greater than the current debug level) is equivalent to
     `(begin body)'. When traces are activated, before executing BODY.

     The debugging level is controlled by two parameters:
     `bigloo-debug' and `bigloo-compiler-debug' (see *note
     Parameters::).


 -- bigloo function: trace-item . args
     This function displays all its arguments. It has to be used nested
     in a WITH-TRACE form.

 -- bigloo function: trace-bold s
 -- bigloo function: trace-string s
     These two functions are provided for convenience. They returns
     strings made of their parameters.

 -- bigloo function: trace-color color . args
     The COLOR argument is a positive integer.  This function returns a
     string which is the representation of ARGS and that appears on the
     terminal in color COLOR.

     Colors can be enable or disabled using the `bigloo-trace-color'
     parameter (see *note Parameters::).

 -- bigloo function: trace-margin
 -- bigloo function: trace-margin-set!
     The TRACE-MARGIN parameter is used to control the characters that
     are displayed in the margin of a trace. Usual applications should
     not use this. However, it may be convenient to set the margin by
     hands in some context. For instance, it can be used to
     distinguished threads in a multi-threaded application such as:

          (make-thread (lambda ()
                          (trace-margin-set! (trace-color 1 "="))
                          ...))
          (make-thread (lambda ()
                          (trace-margin-set! (trace-color 2 "="))
                          ...))

 -- bigloo function: trace-port
 -- bigloo function: trace-port-set!
     These functions return and set the output port used by traces.


File: bigloo.info,  Node: Eval,  Next: Macro Expansion,  Prev: Tracing,  Up: Top

16 Eval and code interpretation
*******************************

This chapter describes the Bigloo evaluator.

* Menu:

* Eval compliance::
* Eval standard functions::
* Eval command line options::
* Eval and the foreign interface::


File: bigloo.info,  Node: Eval compliance,  Next: Eval standard functions,  Up: Eval

16.1 Eval compliance
====================

Bigloo includes an interpreter. Unfortunately, the language accepted by
the interpreter is a proper subset of that accepted by the compiler.
The main differences are:

   * No foreign objects can be handled by interpreter.

   * Classes of the object system cannot be declared within interpreted
          code.

   * The interpreter ignores modules, and has a unique global
     environment.

  Compiled code and interpreted code can be mixed together. That is,
interpreted code is allowed to call compiled code and vice versa. This
connection can be use to circumvent the missing features of the
interpreter (see Section *note Module Declaration::, for a description
of how to connect compiled and interpreted code).

  By default the evaluator assumes that operators from the standard
library (e.g., `+', `car') are immutable. Hence, it optimizes these
operators calls. This optimization can be disables using the
`bigloo-eval-strict-module' parameter described in the chapter
describing the parameters (see *note Parameters::).


File: bigloo.info,  Node: Eval standard functions,  Next: Eval command line options,  Prev: Eval compliance,  Up: Eval

16.2 Eval standard functions
============================

 -- procedure: eval exp [env]
     This form evaluates EXP. The second argument is optional. It can be
     the evaluation of one of these three function forms:
          (scheme-report-environment 5)
          (null-environment 5)
          (interaction-environment)

 -- procedure: scheme-report-environment version
 -- procedure: null-environment VERSION
 -- procedure: interaction-environment VERSION
     These three procedures have the definitions given in the R5RS so
     see *note scheme-report-environment: (r5rs.info)Eval, for more
     details.

 -- bigloo procedure: byte-code-compile exp [env (default-environment)]
 -- bigloo procedure: byte-code-run byte-code
     The function `byte-code-compile' compiles a Scheme expression into
     a sequence of byte codes that is implemented as a string.  The
     function `byte-code-run' execute such a sequence.

 -- bigloo procedure: repl
     This invokes the READ-EVAL-PRINT loop. Several `repl' can be
     embedded.

     The `repl' function can be used to implement custom Bigloo
     interpreters.  For instance, one may write:

          (module repl)
          (repl)

     When compiled, this will deliver an executable containing the sole
     Bigloo interpreter.

 -- bigloo procedure: quit
     This exits from the currently running `repl'. If the current
     `repl' is the first one then this function ends the interpreter.

 -- bigloo procedure: set-prompter! proc
     The argument PROC has to be a procedure of one argument and
     invoking this function sets the `repl' prompter. That is, to
     display its prompt, `repl' invokes PROC giving it the nesting
     level of the current loop as its argument.

 -- bigloo procedure: get-prompter
     Returns the current `repl' prompter.

 -- bigloo procedure: set-repl-printer! proc
     The argument PROC has to be a procedure accepting one or two
     arguments.  This function sets the `repl' display function. That
     is, to display the result of its evaluations, `repl' invokes PROC
     giving it the evaluated expression as first argument and the
     current output port (or a file in case of transcript) as second
     argument. `Set-repl-printer!' returns the former `repl' display
     function.

     For instance, one may write:

          1:=> (define x (cons 1 2))         -| X
          1:=> (define y (cons x x))         -| Y
          1:=> y                             -| (#0=(1 . 2) . #0#)
          1:=> (set-repl-printer! display)   -| #<procedure:83b8c70.-2>
          1:=> y                             -| ((1 . 2) 1 . 2)

 -- bigloo procedure: native-repl-printer
     Returns the native (default) `repl' display function.

 -- bigloo procedure: expand exp
     Returns the value of EXP after all macro expansions have been
     performed.

 -- bigloo procedure: expand-once exp
     Returns the value of EXP after one macro expansion has been
     performed.

  It is possible to specify files which have to be loaded when the
interpreter is invoked. For this, see section *note Compiler
Description::.

  If a Bigloo file starts with the line:
      #! bigloo-command-name

  and if this file is executable (in the meaning of the system) and if
the user tries to execute it, Bigloo will evaluate it. Note also that
SRFI-22 support enables to run any Unix interpreter (*note SRFIs::).

 -- bigloo procedure: load filename
 -- bigloo procedure: loadq filename
     FILENAME should be a string naming an existing file which contains
     Bigloo source code. This file is searched in the current directory
     and in all the directories mentioned in the variable `*load-path*'.
     The `load' procedure reads expressions and definitions from the
     file, evaluating them sequentially. If the file loaded is a module
     (i.e. if it begins with a regular module clause), load behaves as
     module initialization. Otherwise, this function returns the result
     of the last evaluation. The function `oadq' differs from the
     function `load' in the sense that `loadq' does not print any
     intermediate evaluations.

     Both functions return the full path of the loaded file.

 -- bigloo procedure: loada filename
     Loads an "access file", which allows the interpreter to find the
     modules imported by a loaded module. It returns the full path of
     the loaded file.

 -- bigloo variable: *load-path*
     A list of search paths for the `load' functions.

 -- bigloo procedure: dynamic-load filename #!optional (init init-point)
     Loads a shared library named `filename'.

     _Important note: _ The function `dynamic-load' can only be used
     from interpreters linked against dynamic libraries. In particular,
     the `dynamic-load' function can be issued from the `bigloo'
     command if and only if the option `--sharedcompiler=yes' has been
     used when configuring Bigloo. If the `bigloo' command is not linked
     against dynamic libraries and if `dynamic-load' is required inside
     a read-eval-print loop (REPL) it exists a simple workaround.  It
     consists in implementing a new REPL and linking it against dynamic
     libraries. This can be done as:

          $ cat > new-repl.scm <<EOF
          (module new-repl)
          (repl)
          EOF
          $ bigloo new-repl.scm -o new-repl
          $ new-repl
          1:=> (dynamic-load ...)

     The function `dynamic-load' returns the name of the loaded
     library. If INIT-POINT is specified and if it is a string and if
     the library defines a function named `init-point', this function
     is called when the library is loaded. INIT-POINT is a C
     identifier, not a Scheme identifier. In order to set the C name a
     Scheme function, use the extern `export' clause (see Section *note
     C Interface::). If the INIT-POINT is provided and is not a string,
     no initialization function is called after the library is loaded.
     If the INIT-POINT value is not provided, once the library is
     loaded, `dynamic-load' uses the Bigloo default entry point.
     Normally you should _not_ provide an INIT-POINT to `dynamic-load'
     unless you known what you are doing. When producing C code, to
     force the Bigloo compiler to emit such a default entry point, use
     the `-dload-sym' compilation option (see Section *note Compiler
     Description::). This option is useless when using the JVM code
     generator. Let's assume a Linux system and two Bigloo modules. The
     first:

          (module mod1
             (eval (export foo))
             (export (foo x)))

          (define (foo x)
             (print "foo: " x))

          (foo 4)

     The second:

          (module mod2
             (import (mod1 "mod1.scm"))
             (eval (export bar))
             (export (bar x)))

          (define (bar x)
             (print "bar: " x))

          (bar 5)

     If these modules are compiled as:

          $ bigloo mod1.scm -c -o mod1.o
          $ bigloo mod2.scm -c -o mod2.o -dload-sym

     Then, if a shared library is built using these two modules (note
     that on non Linux systems, a different command line is required):

          $ ld -G -o lib.so mod1.o mod2.o

     Then, `lib.so' cant be dynamically loaded and the variables it
     defines used such as :

          $ bigloo -i
          (dynamic-load "lib.so")
               -| foo: 4
                 bar: 5
          1:=> (foo 6)
               -| foo: 7

     As the example illustrates, when Bigloo modules are dynamically
     loaded, they are initialized. This initialization is ensure _only_
     if `dynamic-load' is called with exactly one parameter. If
     `dynamic-load' is called with two parameters, it is of the
     responsibility of the program to initialize the dynamically loaded
     module before using any Scheme reference.

     _Note: _ In order to let the loaded module accesses the variables
     defined by the loader application, special compilation flags must
     be used (e.g., `-rdynamic' under the Linux operating system).
     `Dynamic-load' is implemented on the top of the `dlopen' facility.
     For more information read the `dlopen' and `ld' manuals.


 -- bigloo procedure: dynamic-unload filename
     On the operating system that supports this facility, unloads a
     shared library.  Returns `#t' on success. Returns `#f' otherwise.

 -- bigloo variable: *dynamic-load-path*
     A list of search paths for the `dynamic-load' functions.

 -- procedure: transcript-on filename
 -- procedure: transcript-off


File: bigloo.info,  Node: Eval command line options,  Next: Eval and the foreign interface,  Prev: Eval standard functions,  Up: Eval

16.3 Eval command line options
==============================

This section presents the Bigloo compiler options that impact the
interaction between compiled and interpreted code. The whole list of
the Bigloo compiler options can be found in *note The Bigloo command
line: Compiler Description.

   * `-i' Don't compile a module, interpret it!

   * `-export-all' Make all the bindings _defined_ by       the
     compiled module available from the interpreter.

   * `-export-export' Make all the bindings _exported_ by the
     compiled module available from the interpreter.

   * `-export-mutable' Make all the bindings _exported_ by the
     compiled module mutable from outside the module. This option is
       _dangerous_! Either all the modules composing the application
       must be compiled with or without `-export-mutable'. It is
     impossible       to mix `-export-mutable' enabled and disabled
     compilations.


File: bigloo.info,  Node: Eval and the foreign interface,  Prev: Eval command line options,  Up: Eval

16.4 Eval and the foreign interface
===================================

To be able to get access to foreign functions within the Bigloo
interpreter, some extra measurements have to be taken. The foreign
functions have to be present in the interpreter binary, which means you
have to compile a custom interpreter. This is described in Section
*note Using C bindings within the interpreter::.


File: bigloo.info,  Node: Macro Expansion,  Next: Parameters,  Prev: Eval,  Up: Top

17 Macro expansion
******************

Bigloo makes use of two macro expansion system. The one based on the
expansion passing style [Dybvig et al. 86] and the one advocated by the
R5RS, for which see *note Top: (r5rs.info)Top.

17.1 Expansion passing style macros
===================================

 -- bigloo syntax: define-expander name proc
     This form defines an expander, NAME, where PROC is a procedure of
     two arguments: a form to macro-expand, and an expander.

 -- bigloo syntax: define-macro (name [args]...) body
     This form is itself macro-expanded into a `define-expander' form.

     Macro expanders cannot be exported or imported since there is no
     way to specify expanders in a module declaration.

     Macros defined with `define-expander' and `define-macro' are used
     by both the compiler and the interpreter.

  Here is an example of an expander:
     (define-expander when
        (lambda (x e)
           (match-case x
              ((?- ?test . ?exps)
               (e `(if ,test (begin ,@exps)) e))
              (else
                (error "when" "illegal form" x)))))

     (when (> a 0) (print a) a)
        ==> (if (> a 0) (begin (print a) a))

  The same example can written with a `define-macro' form:
     (define-macro (when test . exps)
        `(if ,test (begin ,@exps)))

17.2 Revised(5) macro expansion
===============================

Bigloo support the Revised(5) Report on the Scheme programming language.
For a detailed documentation see *Note r5rs.info: (R5RS)Expressions.

 -- syntax: let-syntax (binding...) body
 -- syntax: letrec-syntax (binding...) body
 -- syntax: define-syntax keyword transformer
 -- syntax: syntax-rules literals rule...
     These three forms are compatible with the description of the
     Revised(5) Report on the Algorithmic Language Scheme.

     Implementation Note: Current Bigloo does not ensure hygiene for
     `let-syntax' and `letrec-syntax'. Hygienic expansion is only
     guaranteed for `define-syntax'.


File: bigloo.info,  Node: Parameters,  Next: Command Line Parsing,  Prev: Macro Expansion,  Up: Top

18 Parameters
*************

The Bigloo parameters drive the global behavior programs. A parameter
is accessed via a pair of functions: a reader and a setter. The type of
the value is given, in this documentation, by the name of the parameter
of the setter.

 -- bigloo function: bigloo-strict-r5rs-strings
 -- bigloo function: bigloo-strict-r5rs-strings-set! boolean
     Traditional syntax conforms to the Revised Report if the parameter
     `bigloo-strict-r5rs-strings' is not `#f'. Otherwise constant
     strings specified by the `"([^"]|\")*"' are considered as foreign
     strings.

     For example, after reading the expression `"1\n23\t4\"5"', the
     following string is built, which is equal to `(string #\1 #\n #\2
     #\3 #\t #\4 #\" #\5)' if `(bigloo-strict-r5rs-strings)' is not
     `#f'. It is `(string #\1 #\n #\2 #\3 #\tab #\4 #\" #\5)' otherwise.

     Printing this string will produce: `1n23t4"5'.

     The new foreign syntax allows C escape sequences to be recognized.
     For example, the expression `#"1\n23\t4\"5"' builds a string equal
     to:

     `(string #\1 #\newline #\2 #\3 #\t #\4 #\" #\5)'

     and printing this string will then produce:
          1
          23    4"5

 -- bigloo function: bigloo-compiler-debug
 -- bigloo function: bigloo-compiler-debug-set! integer
 -- bigloo function: bigloo-debug
 -- bigloo function: bigloo-debug-set! integer
 -- bigloo function: bigloo-warning
 -- bigloo function: bigloo-warning-set! integer
     These parameters control the debugging and warning level.  The
     `bigloo-compiler-debug' is automatically controlled by the compiler
     command line `-g' option (see *note Command Line Parsing::).

     When a program is compiled in debug mode LVL, the compiler
     introduces a call to `(bigloo-debug-set! lvl)' before the
     evaluation of the first expression.

     The `bigloo-debug' parameter is used to control traces (see *note
     Tracing::).

 -- bigloo function: bigloo-trace-color
 -- bigloo function: bigloo-trace-color-set! bool
     Enables/disables traces coloring (see *note Tracing::).

 -- bigloo function: bigloo-trace-stack-depth
 -- bigloo function: bigloo-trace-stack-depth-set! integer
     Controls the depth of the stack trace to be displayed on errors.
     With systems that supports shell variables (such as Unix) this
     parameters is dynamically adjusted according to the value of the
     SHELL variable BIGLOOSTACKDEPTH.

 -- bigloo function: bigloo-eval-strict-module
 -- bigloo function: bigloo-eval-strict-module-set! bool
     When set to `#t' enables eval optimization that inlines operators
     calls. This optimization reduces the memory footprint of an
     application and it reduces the execution time.

 -- bigloo function: bigloo-dns-enable-cache
 -- bigloo function: bigloo-dns-enable-cache-set! bool
     Enable/disable DNS name caching.

 -- bigloo function: bigloo-dns-cache-validity-timeout
 -- bigloo function: bigloo-dns-cache-validity-timeout-set! integer
     Get/set the validity period for the DNS cache entries. It is
     expressed in seconds.


File: bigloo.info,  Node: Command Line Parsing,  Next: Explicit Typing,  Prev: Parameters,  Up: Top

19 Command Line Parsing
***********************

Bigloo supports command line argument parsing. That is, when an
application is spawn from an Unix shell, the `main' function  is called
and its argument is bound to the list of the command line arguments,
*Note Module declaration: Modules. The `args-parse' form may be used to
parse these.

 -- bigloo syntax: args-parse list rules [null-rule] [else-rule] ...
     The argument LIST is a list of strings. RULES is defined by the
     following grammar:

          <rule>      ==> (`section' <string>)
                        | ((<option> <help>) <s-expression>)
                        | ((<option>) <s-expression>)
                        | ((<flag> <var> <var> ...) <s-expression>)
                        | ((<flag> <var> <var> ... <help>) <s-expression>)
          <null-rule> ==> (`()' <s-expression>)
          <else-rule> ==> (`else' <s-expression>)
          <option>    ==> <flag>
                        | <string><var>
          <flag>      ==> <string>
                        | (<string>+)
          <var>       ==> an identifier leaded by the `?' character
          <help>      ==> (`help' <s-expression>)
                        | (`help' <string> <s-expression>)

     Each elements of LIST are match against the RULES. If one of these
     matches, `args-parse' proceeds as follows:

       1. The matched argument elements of LIST are removed from the
          list.

       2. The `<s-expression>' associated to the matching rule       is
          evaluated in an environment where the rule variables are
          bound.

       3. The argument parsing is resumed with the rest of LIST.

  In addition to parsing the command line arguments, `args-parse'
enables help message printing.

 -- bigloo procedure: args-parse-usage fmt
     This is a procedure of one argument, an boolean. `Args-parse-usage'
     constructs an help message from all the option described in a
     `args-parse' form. `Args-parse-usage' is only defined in the
     `<s-expression>' of an `args-parse' form.

  At last, if no rule matches an argument and if the `args-parse' form
contains an `else' rule, this is evaluated. In the `<s-expression>'
part of that rule, a pseudo-variable `else' is bound to the unmatched
argument.

  Here is an example of argument parsing deploying all the possible
rules:

     (module args-example
        (main main))

     (define (main argv)
        (args-parse (cdr argv)
           (section "Help")
           (("?")
            (args-parse-usage #f))
           ((("-h" "--help") (help "?,-h,--help" "This help message"))
            (args-parse-usage #f))
           (section "Misc")
           ((("-v" "--version") (help "Version number"))
            (print *version*))
           (("-o" ?file (help "The output file"))
            (set! *dest* file))
           (("--input=?file" (help "The input file"))
            (set! *input* file))
           (else
            (print "Illegal argument `" else "'. Usage:")
            (args-parse-usage #f))))

  Invoking the compiled `args-example' module could produce:

     > bigloo.new args.scm
     args.scm:
     > a.out toto
     Illegal argument `toto'. Usage:

     Help:
        ?,-h,-help    -  This help message

     Misc:
        -v,-version   -  Version number
        -o <file>      -  The output file
        -input=<file> -  The input file


File: bigloo.info,  Node: Explicit Typing,  Next: C Interface,  Prev: Command Line Parsing,  Up: Top

20 Explicit typing
******************

Bigloo supports _type annotation_ or _type information_. As shown in
Section ref Module declaration, these annotations can be written both in
the module clauses and in module bodies although module body type
information is optional. It helps the compiler to produce better quality
code and to reject incorrectly typed programs. Type annotations can
describe both the result and formal parameter types for global
functions and also types for local variable. Due to our module language
design (in particular module initialization), Scheme global variables
_cannot_ support type information.

  _Warning: _ All type annotations are ignore by the interpreter.

  Module body type annotations are introduced by the following special
forms.

 -- bigloo syntax: define (f[::type] [a[::type]]...) body
 -- bigloo syntax: define-inline (f[::type] [a[::type]]...) body
 -- bigloo syntax: let ((var[::type] ...) ...) body
 -- bigloo syntax: let loop ((var[::type] ...) ...) body
 -- bigloo syntax: let* ((var[::type] ...) ...) body
 -- bigloo syntax: letrec ((var[::type] ...) ...) body
 -- bigloo syntax: labels ((var[::type] (var[::type]...) b) ...) body
     Type annotations are optional. That is, for any of these
     constructions, if a type annotation is missing, Bigloo uses the
     default generic type `obj' instead.

     Here is an example of type annotated program:

          (module example
             (export (vector-fill!::vector ::vector ::obj)))

          (define (vector-fill! v filler)
            (let loop ((i::long (- (vector-length v) 1)))
               (if (< i 0)
                   v
                   (begin
                      (vector-set! v i filler)
                      (loop (- i 1))))))

          (let ((v::vector (make-vector 3 4)))
             (vector-fill! v "dummy"))

     The types that can be used in annotations are any of:

        * the basic Scheme types `pair', `null', `bstring', `bint'
          (presented in Section *note Defining an extern type::).

        * the basic extern types `long', `int', `char', `string'
          presented in Section *note Defining an extern type::.

        * the compound extern types described in Section *note Defining
          an extern type::.

        * the types introduced by class declarations (Section *note
          Class declaration::).

     When a function that contains type annotation is exported, the type
     annotations must be written in the prototype of the function in
     the export clause. In that case the type annotation need to be
     written in the function definition:

          (module foo
             (export (succ::int ::int)))

          (define (succ x) (+ 1 x))


File: bigloo.info,  Node: C Interface,  Next: Java Interface,  Prev: Explicit Typing,  Up: Top

21 The C interface
******************

We call all the pieces of program devoted to the interactions between
Scheme and another language a _foreign interface_. In Bigloo, the
foreign interface allows Scheme's functions and variables to be
exported to a foreign language and foreign functions and variables to
be imported into the Scheme code. Using the foreign interface requires
two kind of operations.

   * Declarations -- type declarations, import declarations or export
     declarations.

   * Foreign reference in the Scheme code.

  Declarations take place in a special module clause, see *note Module
Declaration::, and reference to foreign variables within Scheme code
requires no special construction. The current release of Bigloo
includes a C and a Java interface. The Java connection is specified by
the means of a `java' clause (*note Java Interface::).  The C interface
is active (that is the `extern' module clauses are read) only when
compiling to C. So, when compiling to Jvm the binding declared in an
`extern' clause are not bound.

* Menu:

* The syntax of the foreign declarations::
* The very dangerous pragma Bigloo special forms::
* Name mangling::
* Embedded Bigloo applications::
* Using C bindings within the interpreter::


File: bigloo.info,  Node: The syntax of the foreign declarations,  Next: The very dangerous pragma Bigloo special forms,  Prev: C Interface,  Up: C Interface

21.1 The syntax of the foreign declarations
===========================================

The syntax of _foreign_ clauses is defined by:

     <extern> ==> <variable-clause>
          | <function-clause>
          | <include-clause>
          | <export-clause>
          | <type-clause>

  Foreign clauses are automatically "transmitted" by the importation
process.  That is, if module `module1' imports a module `module2',
`module' treats the `extern' clauses of `module2' as though they were
included in its own module declaration. Redefinition of a variable or a
function already defined in an foreign clause is an error.

* Menu:

* Automatic extern clauses generation::
* Importing an extern variable::
* Importing an extern function::
* Including an extern file::
* Exporting a Scheme variable::
* Defining an extern type::


File: bigloo.info,  Node: Automatic extern clauses generation,  Next: Importing an extern variable,  Prev: The syntax of the foreign declarations,  Up: The syntax of the foreign declarations

21.1.1 Automatic extern clauses generation
------------------------------------------

Extern clauses can be automatically generated using the Cigloo program
which is distributed in the same package as Bigloo. Using Cigloo may be
a good way to understand how C prototypes (and types) have to be
declared in Bigloo. Cigloo reads C files and generates the Bigloo
extern clauses for that files.


File: bigloo.info,  Node: Importing an extern variable,  Next: Importing an extern function,  Prev: Automatic extern clauses generation,  Up: The syntax of the foreign declarations

21.1.2 Importing an extern variable
-----------------------------------

The <variable-clause> denotes importation of variables.
     <variable-clause> ==> `(' <typed-ident> <c-name>`)'
          | `(macro' <typed-ident> <string>`)'
          | `(macro' <typed-ident> `('<typed-ident>+`)' <string>`)'
          | `(infix macro' <typed-ident> `('<typed-ident>+`)' <string>`)'

  Only extern "non-`macro'" variables are mutable (that is mutable
using the `set!' construction). Bigloo does not emit "extern C
prototype" for variables introduced by a `macro' clause. <string> is
the C name of variable. The Scheme name of that variable is extracted
from the <typed-ident>.

  Here is an example of variable importations:
     (module example
        (extern (c-var::double "c_var")
                (macro bufsiz::long "BUFSIZ")))

     (print "c-var: " c-var)
     (set! c-var (+ 1.0 c-var))
     (print "c-var: " c-var)
     (print "bufsize: " BUFSIZ)


File: bigloo.info,  Node: Importing an extern function,  Next: Including an extern file,  Prev: Importing an extern variable,  Up: The syntax of the foreign declarations

21.1.3 Importing an extern function
-----------------------------------

Function are imported using the <function-clause>.

     <function-clause> ==> `('<typed-ident> `('<typed-ident>*`)' <string>`)'
          | `('<typed-ident> `('<typed-ident>+ . <typed-ident>`)' <string>`)'
          | `(macro' <typed-ident> `('<typed-ident>*`)' <string>`)'
          | `(macro' <typed-ident> `('<typed-ident>+ . <typed-ident>`)' <string>`)'

  The function result type and Scheme name are extracted from the
<typed-ident>; the <typed-ident> denotes the type of the function
arguments and <string> is the C name of the function. Bigloo does not
produce "C extern prototype" for macro functions (those introduced by
`macro' clauses). If the typed identifier of the function does not
contain any type information. Bigloo will emit a warning message when
compiling and it will use a default C type (e.g. the `int' C type) as
the return type of the function.

     (module example
        (extern (macro prn::int (::string . ::long) "printf")))

     (let ((n (read)))
        (prn #"fib(%d): %d\n" n (fib n)))


File: bigloo.info,  Node: Including an extern file,  Next: Exporting a Scheme variable,  Prev: Importing an extern function,  Up: The syntax of the foreign declarations

21.1.4 Including an extern file
-------------------------------

C files can be included in the C code produced by using
<include-clause>.

     <include-clause> ==> `(include' <string>`)'


File: bigloo.info,  Node: Exporting a Scheme variable,  Next: Defining an extern type,  Prev: Including an extern file,  Up: The syntax of the foreign declarations

21.1.5 Exporting a Scheme variable
----------------------------------

A Scheme variable (or function) can be exported to the foreign world if
and only if it is also exported using an `export' clause. Type
information is given in the Scheme exportation, thus, the only
requirement for a variable to be extern exported is to be given a
foreign name. The foreign <export-clause> does this:

     <export-clause> ==> `(export' <ident> <string>`)'

  Here is an example of exportation:

     (module example
        (export (fib::long ::long))
        (extern (export fib "scheme_fib")))

     (define (fib x) (if (< x 2) 1 ...))


File: bigloo.info,  Node: Defining an extern type,  Prev: Exporting a Scheme variable,  Up: The syntax of the foreign declarations

21.1.6 Defining an extern type
------------------------------

New Bigloo types can be defined using extern <type-clause>. These newly
introduced types can be used in any declaration (that is in any extern
_or_ Scheme module clause and in any Scheme variable or function
definition). The syntax of <type-clause> is:

     <type-clause> ==> `(type' <ident> <type-def> <string>`)'
     <type-def> ==> <atomic-type>
          | <ident>
          | <struct-type>
          | <union-type>
          | <function-type>
          | <array-type>
          | <pointer-type>
          | <enum-type>
          | <opaque-type>

  The symbol <ident> is the Scheme name of the introduced type and
<string> is the C name of the type. When Bigloo produces the definition
of a variable v of type s, it produces the following C code: s v`;'.
This rules applies unless s is a pointer or an array and then, to
produce a C definition, the name of the elements of the array or the
elements pointed by the pointer type are used. Hence, if v is for
instance `foo' and s is `(array int)' the produced C code will be: `int
*foo'.

* Menu:

* Atomic types::
* C structures and unions::
* C pointers::
* C null pointers::
* C arrays::
* C functions::
* C enums::
* C opaques::


File: bigloo.info,  Node: Atomic types,  Next: C structures and unions,  Up: Defining an extern type

21.1.6.1 Atomic types
.....................

The atomic types are the pre-existing ones, defined in the standard
Bigloo's library.
     <atomic-type> ==> <bigloo-type>
          | <c-type>
     <bigloo-type> ==> `obj' `procedure'
          | `pair' | `nil' | `pair-nil' | `bint'
          | `blong' | `bbool' | `cnst'
          | `bstring' | `bchar' | `real'
          | `vector' | `tvector' | `struct'
          | `tstruct' | `output-port' | `input-port'
          | `binary-port' | `unspecified' | `symbol'
          | `foreign'
     <c-type> ==> `cobj' `char'
          | `uchar' | `short'
          | `ushort' | `int' | `uint' | `long'
          | `ulong' | `slong' | `bool' | `string'
          | `file' | `double' | `float' | `void'
          | `function'

  The type `obj' denotes the super type of all Bigloo types (i.e., all
Bigloo types, such as `procedure', `pair', ...) is an `obj'.  The type
`cobj' denotes the super of all C types (i.e., all preexisting C types
such as `char', `uchar', `schar', `short', ...). The type `pair-nil'
denotes values that are either pairs or the `()' value.


File: bigloo.info,  Node: C structures and unions,  Next: C pointers,  Prev: Atomic types,  Up: Defining an extern type

21.1.6.2 Struct and Union types
...............................

C struct and Union types can be declared in Bigloo using <struct-type>
clauses:

     <struct-type> ==> `(struct' `('<typed-ident> <string>`)^+'`)'
     <union-type> ==> `(union' `('<typed-ident> <string>`)^+'`)'

  This clause declared a C struct but C structure values _cannot_ be
handled by Bigloo. Instead Bigloo is able to handle _pointers to_ C
structure. Thus, in order to help the definition of extern types, when
a struct named STRUCT is defined, if it does not exists yet, Bigloo
automatically defines a type _pointer to the structure_. This type is
named STRUCT`*'.

  When a pointer to a structure type is defined, Bigloo automatically
produces functions to manipulate objects of this type. Let us suppose
the type definition of STRUCT`*':

     (type STRUCT
        (struct (ID1::TYPE1 NAME1)
                ...
                (IDN::TYPEN NAMEN))

  The following functions are created:

   * A creator:
          (STRUCT*::STRUCT* ::TYPE_1 ... ::TYPE_N)

     This function allocates a fresh STRUCT`*' (in the same heap as any
     Scheme value) and fills the fields of the C structure with the
     proper values provided in the call.

   * A type checker:
          (STRUCT*?::bool OBJ::obj)

     This function returns `#t' if and only if the argument OBJ is of
     type STRUCT`*'.

   * A null checker:
          (STRUCT*-null?::bool ::STRUCT*)
     This function returns `#t' if and only if its argument is `Null'.

   * A null creator:
          (make-null-STRUCT::STRUCT*)
     This function creates a `NULL' value of type STRUCT*.

   * An equality checker:
          (=STRUCT*?::bool ::STRUCT* ::STRUCT*)

     This function returns `#t' if and only if its arguments are equal.

   * Accessors and mutators:
          (STRUCT*-ID_1::TYPE_1 ::STRUCT*)
          (STRUCT*-ID_1-set!::obj ::STRUCT* ::TYPE_1)
          ...
     These functions read and store field values.


  Here is an example of structure usage:

     (module foo
        (extern
          (include "named_point_declaration.h")
          (type named-point
                (struct (x::double "x")
                        (y::double "y")
                        (name::string "name"))
                "struct named_point")
          (c-print-point::int (named-point*) "ppoint")))

     (define (scheme-print-point point)
        (print "point*-name: " point
               " x: " (named-point*-x point)
               " y: " (named-point*-y point)))

     (let ((orig (named-point* 0.0 0.0 "orig")))
        (if (named-point*-null? orig)
            (error "bigloo" "cannot allocate point" orig)
            (begin
               (c-print-point orig)
               (scheme-print-point orig))))


File: bigloo.info,  Node: C pointers,  Next: C null pointers,  Prev: C structures and unions,  Up: Defining an extern type

21.1.6.3 C pointers
...................

C pointers are defined by the <pointer-type>

     <pointer-type> ==> `(pointer' <ident>`)'

  <ident> is the name of a previously defined type.  Let us suppose the
pointer type declaration:
     (type PTR (pointer IDENT) ...)

  If IDENT is the name of a structure type, Bigloo automatically
creates structure accessors (*note C structures and unions::).
Otherwise, it creates the following functions:

   * A creator:
          (make-PTR::PTR NB::long)

     This function allocates memory for NB elements of type IDENT and
     returns a PTR to this zone. The memory is filled with the C `Null'
     value.

   * A type checker:
          (PTR?::bool OBJ::obj)
     This function returns `#t' the argument OBJ is of type PTR and
     `#f' otherwise.

   * A null checker:
          (PTR-null?::bool ::PTR)
     This function returns `#t' if its argument is `Null' and `#f'
     otherwise.

   * A null creator:
          (make-null-PTR::PTR*)
     This function creates a `NULL' value of type PTR*.

   * An equality checker:
          (=PTR*?::bool ::PTR* ::PTR*)
     This function returns `#t' if its arguments are equal and `#f'
     otherwise.

   * Accessors and mutators:
          (PTR-ref::IDENT ::PTR ::long)
          (PTR-set!::obj ::PTR ::long ::IDENT)
     These functions read and store field values.


  Here is an example of a program using pointer types:

     (module foo
        (extern
         (type double* (pointer double) "double *")))

     (define (make-vect::double* x y z)
        (let ((vect (make-double* 3)))
           (double*-set! vect 0 x)
           (double*-set! vect 1 y)
           (double*-set! vect 2 z)
           vect))

     (define (vect-norm vect::double*)
        (sqrt (+ (expt (double*-ref vect 0) 2)
     	    (expt (double*-ref vect 1) 2)
     	    (expt (double*-ref vect 2) 2))))

     (print (vect-norm (make-vect 1.2 4.5 -4.5)))


File: bigloo.info,  Node: C null pointers,  Next: C arrays,  Prev: C pointers,  Up: Defining an extern type

21.1.6.4 C null pointers
........................

It may be convenient to build C null pointers. Several means can be
used.  In particular, foreign structures and pointers are provided with
Null creators. For other foreign types, the easiest one is likely to be
a `pragma' form. For instance, in order to create a null pointer to a
`double*' type, one may use:

     (pragma::double* "((double *)0L)")

 -- bigloo procedure: string-ptr-null? string
 -- bigloo procedure: void*-null? void*
     These two predicates checks if there argument is the C `NULL'
     value.

 -- bigloo procedure: make-string-ptr-null
 -- bigloo procedure: make-void*-null
     These two constructors creates _null_ foreign values.


File: bigloo.info,  Node: C arrays,  Next: C functions,  Prev: C null pointers,  Up: Defining an extern type

21.1.6.5 C arrays
.................

C arrays are defined by the <array-type>

     <array-type> ==> `(array' <ident>`)'

  <ident> is the name of a previously defined type. Array types are
similar to pointer types except that they include their size in their
type definition string. Let us suppose the array type declaration:
     (type ARRAY (array IDENT) ...)

  If IDENT is the name of a structure type, Bigloo automatically
creates structures accessors (*note C structures and unions::).
Otherwise, it creates the following functions:

   * A creator:
          (make-ARRAY::ARRAY)
     This function allocates memory for the array ARRAY.  The memory is
     filled with the C `Null' value.

   * A type checker:
          (ARRAY?::bool OBJ::obj)
     This function returns `#t' if the argument OBJ is of type _array_
     and `#f' otherwise.

   * A null checker:
          (null-ARRAY?::bool ::ARRAY)
     This function returns `#t' if the argument OBJ is `Null' and `#f'
     otherwise.

   * An equality checker:
          (=ARRAY*?::bool ::ARRAY* ::ARRAY*)
     This function returns `#t' if its arguments are equal and `#f'
     otherwise.

   * Accessors and mutators:
          (ARRAY-ref::IDENT ::ARRAY ::long)
          (ARRAY-set!::obj ::ARRAY ::long ::IDENT)
     These functions read and store field values.


  Here is an example of a program using array types:

     (module foo
        (extern
         (type double* (array double) "double [ 10 ]")))

     (define (make-vect::double* x y z)
        (let ((vect (make-double*)))
           (double*-set! vect 0 x)
           (double*-set! vect 1 y)
           (double*-set! vect 2 z)
           vect))

     (define (vect-norm vect::double*)
        (sqrt (+ (expt (double*-ref vect 0) 2)
     	    (expt (double*-ref vect 1) 2)
     	    (expt (double*-ref vect 2) 2))))


     (print (vect-norm (make-vect 1.2 4.5 -4.5)))


File: bigloo.info,  Node: C functions,  Next: C enums,  Prev: C arrays,  Up: Defining an extern type

21.1.6.6 C functions
....................

C function types are introduced by the <function-type> clause:

     <function-type> ==> `(function' <ident> `('<ident>*`))'

  Let us suppose the array type declaration:
     (type FUN (function RES (ARG*)) ...)

  Bigloo creates the following functions:

   * A type checker:
          (FUN?::bool OBJ::obj)
     This function returns `#t' if the argument OBJ is of type FUN and
     `#f' otherwise.

   * An equality checker:
          (=FUN*?::bool ::FUN* ::FUN*)
     This function returns `#t' if and only if its arguments are equal.

   * Caller:
          (FUN-call::RES F::FUN A::TA ...)
     This function invokes F with the arguments A ...  AN.


  Suppose we have to use in Scheme the following C variable:

     double (*convert)(char *);

  It can be done as in:

     (module foo
        (extern
         (type *string->double
               (function double (string))
                         "double (*)(char *)")
         (macro cv::*string->double "convert")))

     (print (*string->double-call cv "3.14"))


File: bigloo.info,  Node: C enums,  Next: C opaques,  Prev: C functions,  Up: Defining an extern type

21.1.6.7 C enums
................

This form defines `enum' types.

     <enum-type> ==> `(enum ('<ident> <string>`)...' ...`)'

  Let us suppose the type:
     (type ENUM
        (enum (ID_1 NAME_1)
              ...
              (ID_N NAME_N)))

  Bigloo creates the following functions:

   * Creators:
          (ENUM-ID_1::ENUM)
          ...
          (ENUM-ID_N::ENUM)
     These functions create ENUM values.

   * A type checker:
          (ENUM?::bool OBJ::obj)
     This function returns `#t' if the argument OBJ is of type ENUM and
     `#f' otherwise.

   * An equality checker:
          (=ENUM?::bool ::ENUM ::ENUM)
     This function returns `#t' if the arguments are equal and `#f'
     otherwise.

  Here is an example of Scheme code using ENUM type.

     (module foo
        (extern
         (type gizmo
               (enum (titi "titi")
                     (tutu "tutu")
                     (tata "tata"))
               "enum toto")))

     (let ((v1 (gizmo-titi))
           (v2 (gizmo-tutu)))
        (print (=gizmo? v1 v2)))


File: bigloo.info,  Node: C opaques,  Prev: C enums,  Up: Defining an extern type

21.1.6.8 C opaques
..................

This form defines `opaque' types.

     <opaque-type> ==> `(opaque)'

  Let us suppose the type:
     (type OPA (opaque) ...)

  Bigloo creates the following functions:
   * A type checker:
          (OPA?::bool OBJ::obj)
     This function returns `#t' if the argument OBJ is of type OPA and
     `#f' otherwise.

   * An equality checker:
          (=OPA?::bool ::OPA ::OPA)
     This function returns `#t' if the arguments are equal and `#f'
     otherwise.

  Opaque types are relevant when a C value must transit via a Scheme
function from a C function to another C function. The value can't be
used in Scheme because no accessors are defined over that type it can
only be send back to a C function.

  Here is an example of Scheme code using OPAQUE type.

     (module foo
        (extern (type filedes (opaque) "FILE *")
                (macro _fopen::filedes (::string ::string) "fopen")
                (_fgetc::int (::filedes) "fgetc")
                (_fclose (::filedes) "fclose"))
        (export (fopen::filedes ::bstring ::bstring)
                (fclose ::filedes)
                (fgetc::char ::filedes)))

     (define (fopen fname mode)
        (_fopen fname mode))

     (define (fclose filedes)
        (_fclose filedes))

     (define (fgetc filedes)
        (integer->char (_fgetc filedes)))

  _Note: _ To illustrate the default type compilation of extern
function, we have voluntary introduced an incomplete declaration for
the `fclose' function. This will make Bigloo to produce a warning when
compiling that module.


File: bigloo.info,  Node: The very dangerous pragma Bigloo special forms,  Next: Name mangling,  Prev: The syntax of the foreign declarations,  Up: C Interface

21.2 The very dangerous "pragma" Bigloo special forms
=====================================================

Bigloo has a special form which allows the inclusion of C text into the
produced code. It is _only_ applicable to the C back-end.  In
particular, the JVM back-end (see Chapter *note Java Interface::) does
not support it.

 -- bigloo syntax: pragma::IDENT string [args]
 -- bigloo syntax: free-pragma::IDENT string [args]
     This force Bigloo to include STRING in the produced C code as a
     regular C fragment of code. This form must not be used without an
     in depth understanding of Bigloo C code production; with unskilled
     use, the produced C file may be unacceptable to the C compiler.

     Values can be passed to a `pragma' form, being referenced in
     STRING by expressions of the form `$NUMBER'.  Such expression are
     replaced by the corresponding values, the number of referenced
     values in STRING being exactly the number of values provided. Here
     is an example of `pragma' usage:

          (define (fibo x::long)
             (pragma "printf( \"fib(%d):%d\\n\", $1, $2 );"
                     x
                     (fib x)))

     Arguments provided to a pragma form are not converted during
     compilation.  Hence, pragma arguments can be of any types,
     including, foreign types.

     A pragma result type can be specified using the notation
     `pragma::NAME' where the default type is `unspecified'. Then, for
     instance, the expression `(pragma::bool "$1 == 0" x)' will be
     considered to be returning a object of type `bool' (C boolean)
     while the expression `(pragma "$1 == 0" x)' will be considered by
     Bigloo to be returning the `unspecified' typed object.

     The compiler assumes that a `pragma' forms operates a side effects
     and that it writes into its parameters. This assumption no long
     holds with `free-pragma'. This is the only difference between the
     two forms.


File: bigloo.info,  Node: Name mangling,  Next: Embedded Bigloo applications,  Prev: The very dangerous pragma Bigloo special forms,  Up: C Interface

21.3 Name mangling
==================

In order to avoid name clashes, Bigloo uses name mangling when
compiling to C or to Jvm. The name mangling for a Scheme identifier may
be overridden by the means of an extern `export' clause (see Section
*note Exporting a Scheme variable::).

  Four public functions may be used to mangle and to demangle Scheme
identifiers:

 -- bigloo procedure: bigloo-mangle string
     Mangle the identifier STRING.

 -- bigloo procedure: bigloo-module-mangle string1 string2
     Mangle the identifier STRING1 that belongs to module STRING2.

 -- bigloo procedure: bigloo-mangled? string
     Returns `#t' if STRING has been computed by the `bigloo-mangle' or
     `bigloo-module-mangle' function.

 -- bigloo procedure: bigloo-class-mangled? string
     Returns `#t' if STRING is a mangled name of a Bigloo class.

 -- bigloo procedure: bigloo-need-mangling string
     Returns `#t' if STRING requires name mangling because it is not a
     C or Jvm valid identifier.

 -- bigloo procedure: bigloo-demangle string
     Demangle previously mangled identifiers:

          (let ((id "foo!")
                (module "a-module"))
             (let ((mangled (bigloo-module-mangle id module)))
                (multiple-value-bind (new-id new-module)
                   (bigloo-demangle mangled)
                   (and (string=? id new-id) (string=? module new-module)))))
             => #t

 -- bigloo procedure: bigloo-class-demangle string
     Demangle previously mangled class identifier.


File: bigloo.info,  Node: Embedded Bigloo applications,  Next: Using C bindings within the interpreter,  Prev: Name mangling,  Up: C Interface

21.4 Embedded Bigloo applications
=================================

It is possible to design and realize embedded Bigloo applications. This
facility is useful for adding a new Scheme part to an already existing
C program. The C part of the program has only to enter the Bigloo
initialization, hence, it can call any Bigloo function.

  Normally, Bigloo creates an initialization function called ` main'
when it reads a `main' module clause. To use an embedded Bigloo
program, such an initialization function would have to be created but
with a different name. Changing the name can be be done using the
following Bigloo option: `-copt "-DBIGLOO_MAIN=<NEW-NAME>"'. To prevent
exit from the program after <NEW-NAME> is executed, the following
Bigloo option must be used: `-copt "-DBIGLOO_EXIT='BUNSPEC,'"'.

  A very important part of designing embedded Bigloo programs is being
sure that all used Bigloo modules are correctly initialized and the
normal way to initialize them is to use `with' clauses in the module
which contains the `main' clause.

  An example of an embedded program can be found in the distribution's
examples directory.


File: bigloo.info,  Node: Using C bindings within the interpreter,  Prev: Embedded Bigloo applications,  Up: C Interface

21.5 Using C bindings within the interpreter
============================================

To be able to get access to foreign functions within the Bigloo
interpreter, some extra measurements have to be taken. The foreign
functions have to be present in the interpreter binary, which means you
have to compile a custom interpreter. Fortunately, this is easy.  What
has to be done is to wrap the foreign functions within Scheme and make
an interpreter module.

  Let us consider an example where a C function `get_system_time'
returning and `int' is used in an interpreter. (When linking, be sure
to add the `.o' file containing the `get_system_time'.)

  The `ffi-interpreter.scm' file:

     (module ExtendendInterpreter
        (import (wrapper "wrapper.scm"))
        (main main))

     (define (main argv)
        (repl))

  The `wrapper.scm' file:

     (module wrapper
        (extern (macro %get-system-time::int () "get_system_time"))
        (export (get-system-time))
        (eval (export-exports))

     (define (get-system-time)
       (%get-system-time))

  Compile and link your application with something like:

     cc gettime.c -c gettime.o
     bigloo wrapper.scm -c
     bigloo ffi-interpreter.scm wrapper.o gettime.o


File: bigloo.info,  Node: Java Interface,  Next: SRFIs,  Prev: C Interface,  Up: Top

22 The Java interface
*********************

When the Bigloo is configured for a JVM back-end support, the compiler
is able to produce Java class file instead of C files. In order to
produce JVM class files, use the `-jvm' compiler option. Example:

     $ cat > foo.scm
     (module foo (main main))
     (define (main argv)
        (print "Hello world: " argv))
     $ bigloo -jvm foo.scm
     $ a.out
       -| Hello world: (a.out)

* Menu:

* Compiling with the JVM back-end::
* JVM back-end and SRFI-0::
* Limitation of the JVM back-end::
* Connecting Scheme and Java code::
* Performance of the JVM back-end::


File: bigloo.info,  Node: Compiling with the JVM back-end,  Next: JVM back-end and SRFI-0,  Up: Java Interface

22.1 Compiling with the JVM back-end
====================================

22.1.1 Compiler JVM options
---------------------------

All the compiler options that control the compilation (optimization
options, debugging options, etc.), can be used in conjunction with the
`-jvm' option.  However, the `-jvm' option _MUST_ be the first compiler
option on the command line.

  In order to prevent the compiler to produce a script shell file to run
the program, it is required to use simultaneously the `-jvm' and `-c'
options.

22.1.2 Compiling multi-modules applications
-------------------------------------------

In order to compile and link multi-modules applications, it is required
to specify the association between Scheme source modules and Java
qualified type names. This task is generally complex because of the
annoying mapping that exists from Java class names and the operating
file system names. In order to get rid of this problem, the Bigloo
standard distribution contains a tool, `jfile', that automatically
produces Bigloo Module/Java classes association files. The default name
for such a table is `.jfile'. When compiling a module, Bigloo checks if
a `.jfile' exists in the current directory, if it exists, the file is
read. The compilation option `-jfile' may be used to specify an
alternative jfile name. Example:

     $ cat > foo.scm
     (module foo (export (foo))) (define (foo) 'foo)
     $ cat > bar.scm
     (module bar (export (bar))) (define (bar) 'bar)
     $ cat > hux.scm
     (module hux (export (hux))) (define (hux) 'hux)
     $ cat > main.scm
     (module main (main main) (import foo bar hux)
     (define (main argv)
        (print (foo))
        (print (bar))
        (print (fhux)))
     $ afile *.scm > .afile
     $ jfile *.scm > .jfile
     $ bigloo -jvm -c foo.scm
     $ bigloo -jvm -c bar.scm
     $ bigloo -jvm -c hux.scm
     $ bigloo -jvm main.scm foo.class bar.class hux.class

  For an explanation about the `.afile', *note Modules::.


File: bigloo.info,  Node: JVM back-end and SRFI-0,  Next: Limitation of the JVM back-end,  Prev: Compiling with the JVM back-end,  Up: Java Interface

22.2 JVM back-end and SRFI-0
============================

The currently running back-end may be tested by the means of the SRFI-0
`cond-expand' form (*note SRFIs::). That is, when the JVM is ran, the
`bigloo-jvm' clause is true. Otherwise, the `bigloo-c' is true. Example:

     $ cat > foo.scm
     (module foo (main main))
     (define (main argv)
        (cond-expand
           (bigloo-jvm (print "JVM back-end"))
           (bigloo-c (print "C back-end"))
           (else (error "main" "unsupported back-end" #unspecified))))
     $ bigloo -jvm foo.scm
     $ a.out
       -| JVM back-end
     $ bigloo foo.scm
     $ a.out
       -| C back-end


File: bigloo.info,  Node: Limitation of the JVM back-end,  Next: Connecting Scheme and Java code,  Prev: JVM back-end and SRFI-0,  Up: Java Interface

22.3 Limitation of the JVM back-end
===================================

The JVM back-end supports the entire Bigloo source language but the
`call/cc' function. More precisely, using the JVM back-end, the
continuation reified in a `call/cc' form can only be invoked in the
dynamic extent of that form.

  The other restrictions of the C back-end apply to the JVM back-end.
Mainly,

   * Bigloo is not able to compile all the tail recursive call without
     stack consumption (however, most of the tail recursive calls are
     optimized by Bigloo and don't use stack activation frames).

   * Bigloo compiled applications do not check for arithmetic overflow.

   * When compiling to Jvm, the `extern' module clauses are not used.

   * Jvm runtime system does support the following function `chdir'.

   * Jvm runtime system support for `chmod' is restricted.

   * In order to read a shell variable from a Bigloo compiled Jvm
     program,       you have to use the Bigloo link option `-jvm-env'
     _when_       linking that program. However, some shell variables
     are       automatically defined (`HOME', `USER', `CLASSPATH' and
        `TMPDIR'.

   * JVM code generation does not support `pragma' forms.



File: bigloo.info,  Node: Connecting Scheme and Java code,  Next: Performance of the JVM back-end,  Prev: Limitation of the JVM back-end,  Up: Java Interface

22.4 Connecting Scheme and Java code
====================================

When compiling and linking with the JVM back-end, Bigloo source code may
use the Java API. That is, Bigloo Scheme source code may use (refer or
set) Java static variables, Bigloo source code may call static or
virtual Java methods. In addition, Bigloo variables and functions may
be exported to Java, that is use, set or called in Java source code.
Java module clauses are enabled (read and parsed) only when compiling
to JVM byte code.

  Java definitions are declared in Bigloo modules by the mean of a
Bigloo module clause: the _java_ module clause. The syntax of a _Java_
clause is defined by:

     <java> ==> <declare-class-clause>
          | <declare-abstract-class-clause>
          | <extend-class-clause>
          | <array-clause>
          | <export-clause>

  As for the _extern_ clause, _java_ clauses are automatically
"transmitted" by the importation process.  That is, if module `module1'
imports a module `module2', `module' treats the `java' clauses of
`module2' as though they were included in its own module declaration.
Redefinition of a variable or a function already defined in an java
clause is an error. However, the definition of a Java class or an Java
abstract class may be enriched from module to module.

* Menu:

* Automatic Java clauses generation::
* Declaring Java classes::
* Declaring abstract Java classes::
* Extending Java classes::
* Declaring Java arrays::
* Exporting Scheme variables::
* Bigloo runtime customization::
* Bigloo module initialization::


File: bigloo.info,  Node: Automatic Java clauses generation,  Next: Declaring Java classes,  Prev: Connecting Scheme and Java code,  Up: Connecting Scheme and Java code

22.4.1 Automatic Java clauses generation
----------------------------------------

Java clauses can be automatically generated using the Jigloo program
which is distributed in the same package as Bigloo. Using Jigloo may be
a good way to understand how Java classes, methods, and variables have
to be declared in Bigloo. Jigloo reads Java _class_ files and generate
the Bigloo java clauses for that classes.


File: bigloo.info,  Node: Declaring Java classes,  Next: Declaring abstract Java classes,  Prev: Automatic Java clauses generation,  Up: Connecting Scheme and Java code

22.4.2 Declaring Java classes
-----------------------------

The <declare-class-clause> clause denotes importation of Java classes.

     <declare-class-clause> ==> `('class <typed-ident> <slot>* <string>`)'
     <slot> ==> <field> | <method> | <constructor>
     <field> ==> `(field' <modifier> <typed-ident> <string>`)'
     <method> ==> `(field' <modifier> <typed-ident> `('<typed-ident>*`)' <string>`)'
     <constructor> ==> `(constructor' <ident> `('<typed-ident>*`))'
     <modifier> ==> `public' | `private' | `protected'
          | `static' | `final' | `synchronized' | `abstract'

  When the compiler encounters a Java class declaration, it
automatically creates a predicate. If the class identifier is `id', the
predicate is named `id?'. In addition, the compiler generates functions
that fetch and set the field values. For a field named `f', these
functions are named `id-f' and `id-f-set!'. Methods and constructors are
also always prefixed the name of the class. That is, for a method named
`m' of a class `k', the Scheme name of the method is `k-m'.

  Example:

     (module java-example
        (java (class point
                 (constructor new-default ())
                 (field x::int "x")
                 (method show::void (::point) "show")
                 (method static statistics::int () "PointStatistics")
                 "Point")
              (class point-3d::point
                 "Point3D")))

     (let ((p (point-new-default)))
        (print (point? p))   -| `#t'
        (point-x-set! p 3)
        (print (point-x p))) -| `3'


File: bigloo.info,  Node: Declaring abstract Java classes,  Next: Extending Java classes,  Prev: Declaring Java classes,  Up: Connecting Scheme and Java code

22.4.3 Declaring abstract Java classes
--------------------------------------

A Bigloo abstract Java class declaration corresponds to a Java
interface.  It cannot be instantiate but regular classes may inherit
from it.

     <declare-abstract-class-clause> ==> `('abstract-class <typed-ident> <slot>* <string>`)'


File: bigloo.info,  Node: Extending Java classes,  Next: Declaring Java arrays,  Prev: Declaring abstract Java classes,  Up: Connecting Scheme and Java code

22.4.4 Extending Java classes
-----------------------------

A class definition may be split into several pieces. One class
declaration (see <declare-class-clause>) and several extensions. The
syntax for a Java class extension is:

     <extend-class-clause> ==> `('class <typed-ident> <slot>*`)'

  Example:

     (module java-example2
        (import java-example)
        (java (class point
                 (field y::int "y")
                 (field static num::int "point_num")
                 (constructor new (::int ::int)))))


File: bigloo.info,  Node: Declaring Java arrays,  Next: Exporting Scheme variables,  Prev: Extending Java classes,  Up: Connecting Scheme and Java code

22.4.5 Declaring Java arrays
----------------------------

Java arrays may be allocated and used inside Scheme code. The syntax of
a Java array module clause is:

     <array-clause> ==> `(array' <ident> <typed-ident>`)'

  The <typed-ident> must refer to the name of an existing type (i.e., a
primitive Bigloo type, a Bigloo class, an already defined Java class or
an already defined Java array). For an array named `ar', Bigloo
generates:

   * a creator named `make-ar' which is a function of one integer
     argument.

   * a predicate named `ar?'.

   * a getter named `ar-ref' which is a function of one integer
     argument.

   * a setter named `ar-set!' which is a function of two arguments, an
         integer and a value of the array item types.

   * a length named `ar-length'.


  Example:

     (module foo
        (java (array int* ::int)
              (class bar
                 (method static hello::int (::int*) "hello")
                 "bar"))
        (main main))

     (define (main argv)
        (let ((tab (make-int* 2)))
           (int*-set! tab 0 3)
           (int*-set! tab 1 6)
           (print (bar-hello tab))))


File: bigloo.info,  Node: Exporting Scheme variables,  Next: Bigloo runtime customization,  Prev: Declaring Java arrays,  Up: Connecting Scheme and Java code

22.4.6 Exporting Scheme variables
---------------------------------

As for the C connection, a Scheme variable (or function) can be exported
to the Java world if and only if it is also exported using an `export'
Java clause. Type information is given in the Scheme exportation, thus,
the only requirement for a variable to be Java exported is to be given
a Java name. The Java <export-clause> does this:

     <export-clause> ==> `(export' <ident> <string>`)'

  Here is an example of exportation:

     (module example
        (export (fib::long ::long))
        (java (export fib "scheme_fib")))

     (define (fib x) (if (< x 2) 1 ...))


File: bigloo.info,  Node: Bigloo runtime customization,  Next: Bigloo module initialization,  Prev: Exporting Scheme variables,  Up: Connecting Scheme and Java code

22.4.7 Bigloo runtime customization
-----------------------------------

When the Scheme program completes normally, that is when the last
expression of the Bigloo main is executed without error, the Bigloo
runtime system explicitly call the Java function `System.exit'. In some
situation, it may be useful to disable this call. For this, one must
set the `boolean' Java static variable `bigloo.foreign.must_exitp' to
`false'. This can be implemented in Java or in Scheme. Here is a Scheme
module that sets the variable to `false'.

     (module no-exit
       (java (class bigloo
                (field static must-exitp::bool "must_exitp")
                "bigloo.foreign")))

     (cond-expand
       (bigloo-jvm (set! bigloo-must-exitp #f)))


File: bigloo.info,  Node: Bigloo module initialization,  Prev: Bigloo runtime customization,  Up: Connecting Scheme and Java code

22.4.8 Bigloo module initialization
-----------------------------------

By default Bigloo modules are initialized when the application starts.
It might be convenient to initialize the module when the Java classes
implementing the Bigloo modules are loaded. It is possible to drive the
Bigloo compiler to introduce code inside the Java class constructors
for initializing the modules. This is the role of the
`-jvm-cinit-module' compiler option.


File: bigloo.info,  Node: Performance of the JVM back-end,  Prev: Connecting Scheme and Java code,  Up: Java Interface

22.5 Performance of the JVM back-end
====================================

We are currently improving and investigating about the performance of
the JVM back-end. JVM performance is extremely sensitive to the host
platform (for instance, very unfortunately, Linux seems to be a poor
platform to run JVM code). Currently, it seems that the JVM back-end
produces codes that are in between 4 times and 10 times slower than
codes produced by the C back-end. The ratio between JVM and C is subject
to changes. The gap between JVM and C code is bound to bridge because
of the huge amount of efforts applied to efficiently implement Java
virtual machines.


File: bigloo.info,  Node: Bigloo Libraries,  Next: Extending the Runtime System,  Prev: SRFIs,  Up: Top

23 Bigloo Libraries
*******************

Bigloo libraries are collections of global bindings (global variables
and global functions). Bigloo libraries are build on the top of the host
operating system (e.g. Unix) libraries. Because Bigloo uses modules, a
library is not only a bundle of compiled codes and memory locations. A
Bigloo library is split into several files:

   * one _heap_ that describes the locations of the library.

   * several host library files.

   * possibly, C header files.

   * possibly, an initialization file.

  Let's consider, for example, a library that implements the `format'
Common Lisp facility. Let's suppose we name this library `bformat' and
let's suppose that the library number is `1.0'. Using a Unix machine,
the Bigloo library will consist of the following files:

   * `bformat.heap': the heap file.

   * `bformat.init': the initialization file.

   * `libbformat_s-1.0.a', `libbformat_s-1.0.so',
     `libbformat_u-1.0.a', `libbformat_u-1.0.so': the Unix library
     files. The file names with a `_u' are libraries compiled in
     _unsafe_ and _optimized_ mode. By convention the library using the
     `_s' suffix are _safe_ libraries, `_p' are profiling libraries,
     `_d' debug libraries, and `_e' eval libraries.

   * `bformat.h': an include file.

23.1 Compiling and linking with a library
=========================================

From the user stand point, using a library can be made two ways:

   * Using the Bigloo `-library LIB-NAME' option where LIB-NAME is the
     name of the Bigloo library (not the name of one of the Unix files
     implementing the library). The name of the library must be _lower
     case_. For instance:

          $ bigloo foo.scm -library bformat

   * Using the module clause `library'. This second solution prevent
     from using a special compilation option. For instance, this module
     will automatically compile and link with the `bformat' library:

          (module foo
             (library bformat))

          ...
          (format ...)

  When a Bigloo library `lib' is used, Bigloo automatically searches if
a file called `lib.init' exists. If such a file exits, it is loaded at
compile-time. For instance, that file may be used to specify
compilation flags. The initialization file may affect any of the global
parameters of the Bigloo compiler. A Bigloo user library might be
needing additional system library. For instance, a Bigloo library
supporting SSL connections is likely to be needing the a native
library. Setting the compiler variable `*ld-port-options*' has this
effect. For instance, one may define an initialization file such as:

     (cond-expand
        (bigloo-compile
         (set! *ld-post-options* (string-append "-lssl " *ld-post-options*)))
        (bigloo-eval
         #unspecified))

  When a Bigloo library `lib' is used, the Bigloo linker automatically
looks at a library to be linked against the application. The name of
the file containing the library depends on the operating system and the
back-end used. For instance, under Unix, for a library called _NAME_,
the Bigloo linker searches for a file called
`lib_NAME__[s|u]-_VERSION_.a' or
`lib_NAME__[s|u]-_VERSION_._DYNLIB-SUFFIX_' in the compilation linker
path when using the native back-end. It searches for a file
`_NAME__[s|u]-_VERSION_.zip' when the JVM back-end is used.

  This default _NAME_ can be overridden in the initialization file. The
function `declare-library!' associates a Bigloo library name and a
system name.

 -- library procedure: declare-library! ident [attributes]
     All the attributes are optional.

        * `version:' the version number of the library. This defaults
          to the Bigloo version number.

        * `basename:' the base of the filename containing the library.
          This default to the library name.

        * `srfi:' a list of symbols denoting the SRFI 0 features
          implemented  by this library. Registered SRFIs may be tested
          by the `cond-expand'  form (*note SRFIs::). This defaults to
          an empty list.

        * `dlopen-init:' a function to be invoked when the library is
          dynamically loaded using the function `dynamic-load'. This
          defaults to `#f'.

        * `module-init:' a module to be initialized when the library is
          loaded. This defaults to `#f'.

        * `eval-init:' a module to be initialized for binding the
          library  exports in the interpreter. This defaults to `#f'.

        * `class-init:' the JVM or .NET class name containing the module
          to be initialized. This defaults to `#f'.

        * `eval-init:' the JVM or .NET class name containing the module
          to be initialized for eval. This defaults to `#f'.

        * `init:' a function to be invoked when a library is loaded.
          This defaults to `#f'.

        * `eval:' a function to be invoked when a library is loaded for
          the interpreter. This defaults to `#f'.

     Examples:

        * The following declares a library named `foo'. When loaded the
          Bigloo runtime system will seek file named `libfoo_s-3.1a.so',
          `libfoo_u-3.1a.so', and `libfoo_e-3.1a.so'.
               (declare-library! 'foo)

        * The following declares a library named `pthread'. When loaded
          the Bigloo runtime system will seek file named
          `libbigloopth_s-1.1a.so', `libbigloopth_u-1.1a.so', and
          `libbigloopth_e-1.1a.so'. Once the library loaded, the SRFI-0
          features `pthread' and `srfi-18' will be bound. When loading
          the library, the two modules `__pth_thread' and
          `__pth_makelib' will be initialized. In the JVM version these
          modules are compiled in the classes `"bigloo.pthread.pthread"'
          and `"bigloo.pthread.make-lib"'.

               (declare-library! 'pthread
                                 :basename "bigloopth"
                                 :version "1.1a"
                                 :srfi '(pthread srfi-18)
                                 :module-init '__pth_thread
                                 :module-eval '__pth_makelib
                                 :class-init "bigloo.pthread.pthread"
               		  :class-eval "bigloo.pthread.make-lib")



 -- library procedure: library-translation-table-add! ident name
 -- library procedure: library-translation-table-add! ident name version
 -- library procedure: library-translation-table-add! ident name
          version :dlopen-init initsym
     The function `library-translation-table-add!' is obsolete. It
     should no longer be used in new code. It is totally subsumed by
     `declare-library!'. The function `library-translation-table-add!'
     is still documented for enabling readers to understand old Bigloo
     source code.

     This function register a NAME for the library ID. An optional
     VERSION can be specified. The optional named argument `dlopen-init'
     gives the base name of the initialization entry point of a library.

     Imagine that we would like to name our `bformat' library
     `bigloobformat'. This can be achieved by adding the following
     expression in the initialization file.

          (library-translation-table-add! 'bformat "bigloobformat")

     Using this translation, on a Unix platform, the library used during
     the linking will be named:
     `libbigloobformat_s-<BIGLOO-VERSION>.a'. In order to change the
     `<BIGLOO-VERSION>' to another suffix, such as `1.0', one may use:

          (library-translation-table-add! 'bformat "bigloobformat" "1.0")

     In such a case, the library searched will be named
     `libbigloobformat_s-1.0.a'.

     Specifying a `#f' prevents the insertion of any suffix. Hence,

          (library-translation-table-add! 'bformat "bigloobformat" #f)

     Instruments the compiler to look at a library named
     `libbigloobformat_s.a'.


23.2 Library and inline functions
=================================

It is illegal for libraries to include inline functions that make use of
new foreign types. By new foreign type, we mean foreign types that are
defined inside the library. A library may contains inline functions but
that inline functions must not even call function using foreign types in
their prototypes. Including inline functions making use of foreign C
type will make the compiler to fail when compiling user code. The
compiler will fail prompting type errors. A library may contains
non-inline functions that make use of new foreign types.

23.3 library and eval
=====================

The function `library-load' loads a library in the interpreter.

 -- library procedure: library-exists? ident . path
     Checks if the library IDENT exists for the current back-end.

     The regular Bigloo library paths are scanned unless optional PATHs
     are sent to the function.

 -- library procedure: library-load ident . path
     Loads a library in the interpreter. In addition to dynamically
     loading the library, this function tries to the `_e' version of
     the library.

     Libraries are searched in regular Bigloo library paths unless
     optional PATHs are sent to the function.

     This version may be used for automatically exporting binding to the
     interpreter. In general, the `_e' library is a simple library that
     contains only one module, the module that is used to build the
     heap-file. For instance, let's consider an implementation of a
     library for SSL programming. This library is composed of a single
     implementation module `__ssl_ssl'. The library is build using a
     heap file:

          (module __ssl_makelib
             (import __ssl_ssl))

     Changing this file for:

          (module __ssl_makelib
             (import __ssl_ssl)
             (eval   (export-all)))

     Enables the construction of a `_e' library.

     When the system loads a dynamic library, it _initializes_ it.  For
     that it expects to find _initialization entry points_ in the
     dynamic libraries that are named after the libraries name. More
     precisely, for the `LIB_s' library, the loader seeks the entry
     point named `"LIB_s"' and for the `LIB_e', it seeks `"LIB_e"'.
     The name of the initialization entry of a library can be changed
     using the `declare-library!' function. If that named is changed,
     one module of the library must contain an `option' module clause
     that sets the variable `*dlopen-init*' with the name of the
     initialization entry point.

     Since Bigloo 3.1a, the runtime system supports a better way for
     initializing libraries. _Initialization_ modules can be associated
     with a library. When loaded, these modules are automatically
     initialized.  This new method fits harmoniously with the Bigloo
     initialization process and it prevents users from annotating the
     source code of the library.

     For instance, if a library initialization file contains the
     following declaration:

          (declare-library! 'foo :module-init 'foo)

     Then, the library must implement the `foo' module.

          (module foo
            (import ...)
            ...)

     In addition if the library binds variables, functions, or classes
     in the interpreter then, an `eval-init' clause must be added to the
     class declaration:

          (declare-library! 'foo :module-init 'foo :eval-init 'foo-eval)

     Then, the module `foo-eval' must be implemented in the `libfoo_e'
     library.

          (module foo-eval
            (import ...)
            (eval (export-all)))

  The standard distribution contains examples of such construction. In
particular, the multi-threading libraries `pthread' and `fthread' use
this facility.

23.4 library and repl
=====================

It is possible to implement a "read-eval-print-loop" that is extended
with the facilities implemented inside a library. In order to make the
variables, functions, and classes of a library visible from the
interpreter, the eval `library' module clause has to be used.  (*note
Module Declaration::) For instance, here is a module that implements a
"repl" with the `format' facility available:

     (module format-repl
        (eval (library bformat))
        (library bformat))

     ;; a dummy reference to a facility of the format library
     (let ((dummy format))
        (repl)

23.5 Building a library
=======================

Bigloo libraries require several steps before being completed.

   * The first step is to build a _library heap_. This is achieved
     using a special compilation mode: `-mkaddheap -mkaddlib -addheap
     -heap-library <ident>'.   That is, for your library you have to
     create a heap associated source file  that imports all the binding
     you want in your library. The heap source file  must be _excluded_
     from the source files that will be used to build  the host library.

     Suppose we have a unique source file for the `bformat' library.
     The module clause of this source file is:

          (module __bformat
             (export (format . args)
                     format:version
                     ...
             (eval   (export format)
                     (export format:version)
                     ...

     Prior to compiling the library, we have to create the heap
     associated file (let's name it `make-lib.scm'). This file could be:

          (module __make-lib
             (import (__bformat "bformat.scm")))

     Building it is simple:

          bigloo -unsafe -q -mkaddheap -mkaddlib -heap-library bformat \
               make-lib.scm -addheap bformat.heap

     The options `-mkaddheap' and `-mkaddlib' tell Bigloo that it is
     compiling an heap associated file. The option `-addheap' tells
     Bigloo the name of the heap file to be produced. The option
     `-heap-library' instructs the compiler for the library name to be
     included inside the heap file. This name is used for checking
     versions at run-time.

   * The second step is to compile all the library source file. These
     compilation must be done using the `-mkaddlib' compilation mode.
     For example:

          bigloo -O3 -unsafe -mkaddlib              \
             -cc gcc -fsharing -q -rm               \
             -unsafev bformat.scm -o bformat_u.o -c
          bigloo -O3 -mkaddlib -g -cg -cc gcc       \
             -fsharing -q -rm                       \
             -unsafev bformat.scm -o bformat.o -c

     The first compilation produces the _unsafe_ version the second the
     produced the _debugging_ version.

   * The third step is to build the host operating system libraries.
     There is no portable way to do this. This operation may looks like:

          ar qcv libbiglooformat_s.a bformat.o
          ranlib libbiglooformat_s.a
          ld -G -o libbiglooformat_s.so bformat.o -lm -lc
          ar qcv libbiglooformat_u.a bformat_u.o
          ranlib libbiglooformat_u.a
          ld -G -o libbiglooformat_u.so bformat_u.o -lm -lc

  The last step is to create an initialization file `bformat.init':

     (declare-library! 'bformat :basename "bigloobformat" :version #f)

  At this time, you are ready to use your library. The Bigloo
distribution contains library exemplar. Considering these examples as a
departure point for new libraries is probably a good idea.

23.6 A complete library example
===============================

For the means of an example let's suppose we want to design a Bigloo
library for 2d points. That library is made of three implementation
files: two C files, `point.h' and `point.c' and one Scheme file
`scm-point.scm'. Here are defined the three files:

`point.h':
     struct point_2d {
        double x, y;
     };

`point.c':
     #include <stdio.h>
     #include "point.h"

     int print_point_2d( struct point_2d *pt ) {
        printf( "<point-2d: %g, %g>", pt->x, pt->y );
     }

`scm-point.scm':
     (module point
        (include "point.sch")
        (extern  (include "point.h"))
        (export  (make-point::s-point_2d* ::double ::double)
                 (print-point             ::s-point_2d*)
                 (point?                  ::obj))
        (eval    (export-all)))

     (define (make-point::s-point_2d* x::double y::double)
        (s-point_2d* x y))

     (define (print-point p::s-point_2d*)
        (print_point_2d p))

     (define (point? obj::obj)
        (s-point_2d*? obj)
        obj)

  We want our library to be composed of the whole exported Scheme
functions. Thus the file to build the heap library could look like:

`make-lib.scm':
     (module __make-point-lib
        (import (point "scm-point.scm"))
        (eval (export-all)))

  Let's suppose that the `point' library requires the `libposix'
library. This means that any file linked with the `point' library needs
to be also linked with the `posix' library. Furthermore, programs
making use of the `point' library needs to include the `point.sch'
file. That Scheme file needs in turn the C file `point.h' otherwise the
produced C files won't compile. The need for the `libposix' library and
for the `point.h' file may be specified inside the `point.init' file.
For our current library, the `point.init' file could look like:

     (declare-library! 'point
                       :basename "point"
                       :srfi '(point)
                       :eval-init '__make-point-lib)

     (set! *ld-options*
           (string-append "-L/usr/lib " *ld-options*))

     (set! *bigloo-user-lib*
           (cons "-lposix" *bigloo-user-lib*))

     (set! *additional-include-foreign*
           (cons "point.h" *additional-include-foreign*))

     (define-macro (point x y)
        `(make-point ,x ,y))

  This file updates some compilation variables (`*ld-options*',
`*bigloo-user-lib*', `*additional-include-foreign*') and defines a
macro: `point'. Because the `point.init' file will be loaded each time
a compilation require the `point' library is spawned, user code are
allowed to use the `point' macro. Here is an example file making use of
the `point' library:

     (module example)

     (let ((p (point 2.9 3.5)))
        (print "point?: " (point? p))
        (print "point?: " (point? 4))
        (print-point p)
        (print (eval `(point? ,p)))
        (eval `(print-point ,p))
        (print "done..."))

  To conclude that example here is the `Makefile' used to compile the
`point' library, heap file and one example.

     # bigloo flags
     BIGLOO          = bigloo
     RELEASE		= `$(BIGLOO) -eval '(begin (print *bigloo-version*) (exit 0))'`
     BHEAPFLAGS      = -unsafe -q -mkaddheap -mkaddlib -v2 -heap-library point
     BCOMMONFLAGGS   = -mkaddlib -fsharing -q $(VERBOSE)        \
                       -copt '$(CCOMMONFLAGS)' -cc $(CC)
     BSAFEFLAGS      = $(BCOMMONFLAGGS) -cg -O3 -g -cg -unsafev \
                       -eval '(set! *indent* 4)' -rm
     BUNSAFEFLAGS    = $(BCOMMONFLAGS) -O4 -unsafe

     # cigloo flags
     CIGLOO          = cigloo

     # cflags
     CC              = gcc
     CCOMMONFLAGS    = -I.
     CSAFEFLAGS      = $(CCOMMONFLAGS)
     CUNSAFEFLAGS    = $(CCOMMONFLAGS) -O2

     # library objects
     SAFE_OBJECT     = olib/scm-point.o olib/point.o
     UNSAFE_OBJECT   = olib_u/scm-point.o olib_u/point.o

     all: heap lib example

     heap: point.heap

     point.heap: point.sch scm-point.scm
             $(BIGLOO) $(BHEAPFLAGS) make-lib.scm -addheap point.heap

     lib: lib_u lib.a

     lib.a: olib $(SAFE_OBJECT)
             ar qcv libpoint_s-$(RELEASE).a $(SAFE_OBJECT)

     lib_u: olib_u $(UNSAFE_OBJECT)
             ar qcv libpoint_u-$(RELEASE).a $(UNSAFE_OBJECT)

     olib:
             mkdir olib

     olib_u:
             mkdir olib_u

     olib_u/scm-point.o olib/scm-point.o: scm-point.scm
             $(BIGLOO) $(BSAFEFLAGS) $(<F) -o $*.o -c

     olib_u/point.o olib/point.o: point.c
             $(CC) $(CSAFEFLAGS) $(<F) -o $*.o -c

     point.sch: point.h point.c
             cigloo $^ > point.sch

     example: heap lib
             $(BIGLOO) -v2 -L . -library point \
                 -static-bigloo example.scm -o example

     clean:
             -/bin/rm -f point.heap
             -/bin/rm -f point.sch scm-point.c
             -/bin/rm -fr olib olib_u
             -/bin/rm -f example example.c example.o
             -/bin/rm -f libpoint_s-$(RELEASE).a libpoint_u-$(RELEASE).a

23.7 Library and modules
========================

A Bigloo library may be composed of several Bigloo modules (even if in
our example only one module was used). The modules composing the library
are free to import each other. Nevertheless, someone designing a Bigloo
library should be aware that Bigloo importation creates dependences
between modules. A module `mod1' that imports a module `mod2' depends
on `mod2' because `mod1' requires `mod2' to be initialized (i.e. `mod1'
calls to the initialization function of `mod2'). The result is that
using `import' clauses inside modules composing a library may create a
lot of dependencies between the object files that are used to build the
associated Unix library. Dependencies should be avoided because they
make the Unix linkers unable to produce small stand-alone programs.
Instead of `import' clauses, `use' clauses should be preferred. `Use'
clauses do not create dependencies because a module `mod1' that `use's
a second module `mod2' does not require `mod2' to be initialized. Of
course, it may happen situations where the initialization is mandatory
and thus, the `import' must not be replaced with a `use' clause. The
source code of the Bigloo library makes use of `import' and `use'
clauses. The Bigloo standard library should be studied as an example.


File: bigloo.info,  Node: Extending the Runtime System,  Next: DSSSL Support,  Prev: Bigloo Libraries,  Up: Top

24 Extending the Runtime System
*******************************

_Custom Types_ types are not documented yet. This facility enables
extension to the standard Bigloo runtime system. The current
implementation of custom types is subject to change. It will be
documented in coming releases.


File: bigloo.info,  Node: SRFIs,  Next: Bigloo Libraries,  Prev: Java Interface,  Up: Top

25 SRFIs
********

Bigloo supports various SRFIs (Scheme Request For Implementation). Some
of them are integrated in the Bigloo core libraries. Some others are
implemented by the means of Bigloo libraries (*note Bigloo
Libraries::). Only the first ones are described in the manual.

  The current Bigloo core library support the following SRFIs:

   * `srfi-0' (Conditional execution).

   * `srfi-2' (AND-LET*: an AND with local bindings, a guarded LET*
     special form).

   * `srfi-6' (Basic String Ports).

   * `srfi-8' (Binding to multiple values).

   * `srfi-9' (_Records_ specification).

   * `srfi-18' (Multithreading support).

   * `srfi-22' (Script interpreter invocation).

   * `srfi-28' (Basic Format Strings).

   * `srfi-30' (Multi-line comments).

   * `srfi-34' (Exception Handling for Programs).

25.1 SRFI 0
===========

 -- bigloo syntax: cond-expand [clause]
     The `cond-expand' form tests for the existence of features at
     macro-expansion time. It either expands into the body of one of its
     clauses or signals and error during syntactic processing.
     `cond-expand' expands into the body of the first clause whose
     feature requirement is currently satisfied (the `else' clause, if
     present, is selected if none of the previous clauses is selected).

     A feature requirement has an obvious interpretation as a logical
     formula, where the variables have meaning _true_ is the feature
     corresponding to the feature identifier, as specified in the _SRFI_
     registry, is in effect at the location of the `cond-expand' form,
     and _false_ otherwise. A feature requirement is satisfied it its
     formula is true under this interpretation. The formula may make
     use of identifier, `and', `or' and `not' operators.

     Examples:

          (write (cond-expand
                    (srfi-0 (* 1 2))
                    (else (+ 3 4))))
             -| 2

          (cond-expand
             (bigloo (define (command-line-arguments) (command-line)))
             (else (define (command-line-arguments) '())))

     The second example assumes that `bigloo' is an alias for the SRFI
     associated with the specification of Bigloo (i.e. the
     documentation for that Scheme system).

     When writing portable code, the case used for the feature
     identifier should match the one in the SRFI registry. This is to
     ensure that the feature identifier will be correctly recognized
     whether or not the Scheme system is case-sensitive. To support
     case-insensitive Scheme systems, the feature identifiers in the
     SRFI registry are guaranteed to be unique even when ignoring the
     case.

     In order to distinguish Bigloo versions, the following symbols are
     recognized in `cond-expand' forms.

        * `bigloo'

        * `bigloo<branch-release>'

        * `bigloo<major-release>'

        * `bigloo<major-release><minor-release>'

     When finalizers have been configured, the two following symbols are
     recognized by `cond-expand':

        * `bigloo-finalizer'

        * `bigloo-weakptr'

     Bigloo implements differents SRFI for the compiler and the
     interpreter.  Thus, their are two Bigloo SRFI registers. One for
     the compiler and one for the interpreter. Bigloo compiler SRFI
     register contains at least the following symbols:

        * `srfi-0'

        * `srfi-1'

        * `srfi-2'

        * `srfi-6'

        * `srfi-8'

        * `srfi-9'

        * `srfi-22'

        * `srfi-28'

        * `srfi-30'

     With respect to the currently used Bigloo back-end, one of these
     symbols is registered:

        * `bigloo-c'

        * `bigloo-jvm'

     Bigloo compiler implements the following SRFI:

        * `bigloo'

        * `bigloo-compile'

        * `bigloo<major-release>'

        * `bigloo<major-release><minor-release>'

     Bigloo interpreter implements the following SRFI:

        * `srfi-0'

        * `srfi-1'

        * `srfi-6'

        * `srfi-8'

        * `srfi-9'

        * `srfi-22'

        * `srfi-28'

        * `srfi-30'

        * `bigloo'

        * `bigloo-eval'

        * `bigloo<major-release>'

        * `bigloo<major-release><minor-release>'

     When a library is used, the name of the library is added to the
     compiler SRFI register. That is:

          (module foo
             (library srfi1))

          (print (cond-expand (srfi1 'with-srfi1) (else 'nothing)))
             -| 'with-srfi1
          (print (eval '(cond-expand (srfi1 'with-srfi1) (else 'nothing))))
             -| 'with-srfi1

 -- bigloo procedure: register-eval-srfi! srfi-name
     This argument SRFI-NAME is a symbol. It registers SRFI-NAME in the
     Bigloo interpreter SRFI register. This function must only be used
     when implementing a library. The code of that library must contain
     one unique call to `register-eval-srfi!'. Let's suppose, for
     instance, a `format' library. The implementation for that library
     must contain an expression like:

          (register-eval-srfi! 'format)

     Calling `(register-eval-srfi! name)' makes `name' supported by
     interpreted `cond-expand' forms.

     _Note:_ There is no `register-compiler-srfi!' because the compiler
     automatically registers SRFI when the `-library' flags are used.
     However, it exists several ways to tell the compiler that it
     actually supports some srfis when compiling some modules.

        * The first way is to insert calls to `register-eval-srfi!' in
          the `.bigloorc' file (*note Compiler Description::).

        * The second, is to use `option' (*note Module Declaration::)
          module clause, such as:

               (module example
                  ...
                  (option (register-srfi! 'srfi-foobar)))

               ...

        * The last way is to use the command line option `-srfi' (*note
          Compiler Description::).


25.2 SRFI 1
===========

The SRFI 1 is implemented as a Bigloo library. Hence, in order to use
the functions it provides, a module must import it.

     (module ex
        (library srfi1))

     (print (find-tail even? '(3 1 37 -8 -5 0 0)))
      => '(-8 -5 0 0))

25.3 SRFI 22
============

The SRFI 22 describes basic prerequisites for running Scheme programs as
Unix scripts in a uniform way. A file (henceforth a _scipt_) conforming
SRFI 22 has the following syntax:

     <script>         ==> <script prelude>? <program>
     <script prelude> ==> `#!' <space> <all but linebreak>* <linebreak>

  A Scheme script interpreter loads the `<script>'. It ignores the
script prelude and interprets the rest of the file according to the
language dialect specified by the name of the interpreter.

  The Scheme script interpreter may also load a different file after
making a reasonable check that loading it is semantically equivalent to
loading `<script>'. For example, the script interpreter may assume that
a file with a related name (say, with an additional extension) is a
compiled version of `<script>'.

25.3.1 An example of SRFI-22 script
-----------------------------------

Let us consider the following Bigloo script located in a file `foo.scm':

     #! /usr/bin/env ./execute
     (module foo
        (main main))

     (define (main argv)
        (print "foo: " argv))

  Let us consider the following `execute' shell script:

     $ cat > execute
     #!/bin/sh
     bigloo -i $*

  Provided that `foo.scm' as the execute flag switched on, it is
possible to _execute_ it:

     $ chmod u+x foo.scm
     $ ./foo.scm
       -| foo: (./foo.scm)

  The same Bigloo module can be compiled and executed such as:

     $ bigloo foo.scm
     $ ./a.out
       -| foo: (a.out)

25.3.2 Lazy compilation with SRFI-22
------------------------------------

SRFI-22 can be used to implement _lazy_ compilation. For instance, let
us consider the following shell script:

     $ cat > bgl
     #!/bin/sh
     SOURCEFILE=$1
     case $SOURCEFILE in
         *.scm)
             OUTFILE=${SOURCEFILE%.scm}
             if ( bigloo -s -o $OUTFILE $SOURCEFILE ); then
                 /bin/rm $OUTFILE.o
                 shift
                 ./$OUTFILE $@
             fi
             ;;
         *)
             echo Error: need a \*.scm file!
             ;;
     esac

  And the following Bigloo script:

     #! /usr/bin/env ./bgl
     (module foo
        (main main))

     (define (main argv)
        (print "foo: " argv))

  When executed in the following way:

     $ chmod u+x foo.scm
     $ ./foo.scm
       -| foo: (./foo.scm)

  The Bigloo module `foo.scm' will first be compiled and then executed.
Of course, one may consider more complex compiler drivers where it is
first checked that the module is not already compiled.


File: bigloo.info,  Node: DSSSL Support,  Next: Compiler Description,  Prev: Extending the Runtime System,  Up: Top

26 DSSSL support
****************

Bigloo supports extensions for the DSSSL expression language [Dsssl96]:

   * Keywords. Bigloo supports full Dsssl keywords.

   * Named constants. Bigloo implements the three DSSSL named constants:
     `#!optional', `#!rest' and `#!key'.

   * Dsssl formal argument lists.

26.1 DSSSL formal argument lists
================================

DSSSL formal argument lists are defined by the following grammar:

     <formal-argument-list> ==> <required-formal-argument>*
       [`(#!optional' <optional-formal-argument>*`)']
       [`(#!rest' <rest-formal-argument>`)']
       [`(#!key' <key-formal-argument>*`)']
     <required-formal-argument> ==> <ieee-ident>
     <optional-formal-argument> ==> <ieee-ident>
          | `('<ieee-ident> <initializer>`)'
     <rest-formal-argument> ==> <ieee-ident>
     <key-formal-argument> ==> <ieee-ident>
          | `('<ieee-ident> <initializer>`)'
     <initializer> ==> <expr>

  When a procedure is applied to a list of actual arguments, the formal
and actual arguments are processed from left to right as follows:

   * _Variables_ in _required-formal-arguments_ are bound to successive
     actual arguments starting with the first actual argument. It shall
     be an error if there are fewer actual arguments than
     _required-formal-arguments_.

   * Next, _variables_ in _optional-formal-arguments_ are bound to any
     remaining actual arguments. If there are fewer remaining actual
     arguments than _optional-formal-arguments_, then variables are
     bound to the result of the evaluation of _initializer_, if one was
     specified, and otherwise to `#f'. The _initializer_ is evaluated
     in an environment in which all previous optional formal arguments
     have been bound.

   * If there is a _rest-formal-argument_, then it is bound to a list
     of all remaining actual arguments. The remaining actual arguments
     are also eligible to be bound to _keyword-formal-arguments_.  If
     there is no _rest-formal-argument_ and there are no
     _keyword-formal-arguments_, the it shall be an error if there are
     any remaining actual arguments.

   * If `#!key' was specified in the _formal-argument-list_, there
     shall be an even number of remaining actual arguments. These are
     interpreted as a series of pairs, where the first member of each
     pair is a keyword specifying the argument name, and the second is
     the corresponding value. It shall be an error if the first member
     of a pair is not a keyword. It shall be an error if the argument
     name is not the same as a variable in a _keyword-formal-argument_,
     unless there  is a _rest-formal-argument_. If the same argument
     name occurs more than once in the list of actual arguments, then
     the first value is used. If there is no actual argument for a
     particular _keyword-formal-argument_, then the variable is bound
     to the result of evaluating _initializer_ if one was specified,
     and otherwise `#f'. The _initializer_ is evaluated in an
     environment in which all previous formal key arguments have been
     bound.

  It shall be an error for an <ieee-ident> to appear more than once in
a _formal-argument-list_.

  Example:

     ((lambda (x y) x) 3 4 5 6)   =>(3 4 5 6)
     ((lambda (x y #!rest z) z)
      3 4 5 6)                    => (5 6)
     ((lambda (x y #!optional z #!rest r #!key i (j 1))
         (list x y z i: i j: j))
      3 4 5 i: 6 i: 7)            => (3 4 5 i: 6 j: 1)

26.2 Modules and DSSSL formal argument lists
============================================

Functions using DSSSL formal argument lists can be exported or imported
in the same way as all regular Bigloo functions. When exporting such a
Dsssl function the exact prototype of the function must be duplicated
in the export clause. That is, for instance, the exportation prototype
for the function:

     (define (foo x y #!optional z #!key i (j 1)) ...)

is:

     (export (foo x y #!optional z #!key i (j 1)))


File: bigloo.info,  Node: Compiler Description,  Next: User Extensions,  Prev: DSSSL Support,  Up: Top

27 Compiler description
***********************

27.1 C requirement
==================

Instead of producing assembly code, Bigloo produces C code.  This C
code is ISO-C compliant [IsoC]. So, it is necessary to have an ISO-C
compiler. The current version has been developed with `gcc'
[Stallman95].

27.2 JVM requirement
====================

In order to compile the Bigloo JVM back-end, you have to be provided
with a JDK 1.2 or more recent (available at `http://www.javasoft.com').
The JVM must support for `-noverify' option because, by default, Bigloo
produces JVM code that is not conform to the rules enforced by the Java
byte code verifiers.

27.3 Running .NET programs on Microsoft .NET platforms
======================================================

Bigloo uses Portable.NET assembler and linker to produce .NET binaries.
As such, produced binaries are linked and signed against Portable.NET
runtime libraries and are rejected by Microsoft .NET platforms.  In
order to run Bigloo .NET binaries on Microsoft .NET platforms, binaries
must first be disassembled and then reassembled and linked against
Microsoft runtime libraries.

  The pnet2ms utility automates this process. Before the first use of
pnet2ms, a public+private key pair must first be registered to the
"Bigloo" container. You may either use the provided pair in the
bigloo.dotnetkey file or generate your own using:
               sn -k bigloo.dotnetkey
  The pair must be registered using:
               sn -i bigloo.dotnetkey Bigloo

  The pnet2ms program can be ran with:
       pnet2ms myprogram.exe

  Additional command-line options are:
       -initlocals     force all local variables to be initialized to their
                       default value upon function entrance
                       (for PEVerify to succeed)
       -k              Keep intermediate files
       -register       Register DLLs in the Global Assembly Cache
       -v              Enable verbose mode
       -v2             Enable very verbose mode
       -v3             Enable very very verbose mode

27.4 Linking
============

It is easier to use Bigloo for linking object files which have been
compiled by Bigloo. An easy way to perform this operation is, after
having compiled all the files using the `-c' option, to invoke Bigloo
with the name of the compiled files.

  When Bigloo is only given object file name as argument, it searches
in the current directory and the directory named in the `*load-path*'
list the Scheme source file in order to perform a correct link. Scheme
source files are supposed to be ended by the suffix `.scm'. Additional
suffixes can be added using the `-suffix' option. Hence, if source
files are named foo1.sc and foo2.sc, a link command line could look
like:

     bigloo -suffix sc foo1.o foo2.o -o foo

  Note: In order to understand how the Bigloo linkers operates and which
libraries it uses, it might be useful to  use the `-v2' option which
unveil all the details of the compilation and the link.

27.5 The compiler environment and options
=========================================

There are four ways to change the behaviour of Bigloo. Flags on the
command line, the `option' module clause runtime-command file and
environment variables *Note Modules::. When the compiler is invoked, it
first gets the environment variables, then it scans the runtime-command
file and, at end, it parses the command line.  If the same option is
set many times, Bigloo uses the last one.

27.5.1 Efficiency
-----------------

In order to get maximum speed, compile with the `-Obench' option.  This
will enable all compiler optimization options and disable dynamic type
checks. To improve arithmetic performance see next section.

27.5.2 Stack allocation
-----------------------

When the `-fstack' flag is enabled, the compiler may automatically
replace some heap allocations with stack allocations. This may improve
performance because stack allocations are handled more efficiently than
heap allocations. On some cases, `-fstack' may also cause slow down or
memory extra retentions. In this last case, when compile using
`-fstack' the program will consume more memory. Unfortunately, this is
nasty phenomenon is unpredictable (it depends on the nature of the
source file).

27.5.3 Genericity of arithmetic procedures
------------------------------------------

By default, arithmetic procedures are generic. This means that it is
allowed to use them with flonum and fixnum. This feature, of course,
implies performances penalty. To improve performance, you may use
specialized procedures (such as `+fx', `=fx', ... or `+fl', `=fl', ...)
but, it is possible to suppress the genericity and to make all generic
arithmetic procedures (`=' for example) fixnum ones. For this you must
use the compiler option `-farithmetic', or add the following module
clause `(option (set! *genericity* #f))' in your module declaration.

27.5.4 Safety
-------------

It is possible to generate _safe_ or _unsafe_ code.  The safety's scope
is `type', `arity', `version' and `range'.  Let's see an example:

     (define (foo f v indice)
        (car (f (vector-ref v indice))))

  In safe mode, the result of the compilation will be:

     (define (foo f v indice)
       (let ((pair
             (if (and (procedure? f)
                   ;; type check
                   (= (procedure-arity f) 1))
                   ;; arity check
                (if (vector? v)
                   ;; type check
                   (if (and (integer? k)
                         ;; type check
                         (>= k 0)
                         ;; range check
                         (< k (vector-length v)))
                         ;; range check
                     (f (vector-ref v indice))
                     (error ...))
                   (error ...))
                (error ...))))
         (if (pair? pair)
            ;; type check
            (car pair)
            (error ...))))

  It is possible to remove some or all safe checks. For example, here is
the result of the compilation where safe check on types have been
removed:

     (define (foo f v indice)
       (let ((pair (if (= (procedure-arity f) 1)
                  ;; arity check
                  (if (and (>= k 0)
                        ;; range check
                        (< k (vector-length v)))
                        ;; range check
                     (f (vector-ref v indice))
                     (error ...))
                  (error ...))))
          (car pair)))

27.5.5 The runtime-command file
-------------------------------

Each Bigloo's user can use a special configuration file. This file must
be named "`.bigloorc'" or "`~/.bigloorc'". Bigloo tries to load one of
these in this order. This file is a Scheme file. Bigloo exports
variables which allow the user to change the behavior of the compiler.
All these variables can be checked using the -help2 option.

  The Bigloo's runtime command file is read before the arguments are
parsed.

27.5.6 The Bigloo command line
------------------------------

If no input file is specified, Bigloo enters its interpreter.  Here is
the exhaustive list of Bigloo options and configuration variables:


     usage: bigloo [options] [name.suf]


     Misc:
        -                          Read source code on current input channel
        -help,-help               This help message
        -help2                     The exhaustive help message
        -help-manual               The help message formatted for the manual
        -o FILE                    Name the output FILE
        -to-stdout                Write C code on current output channel
        -c                         Suppress linking and produce a .o file
        -suffix SUFFIX             Recognize suffix as Scheme source
        -afile FILE                Name of the access file
        -access MODULE FILE        Set access between module and file
        -jfile FILE                Name of the Jvm package file
        -jadd MODULE QTYPE         Set JVM qualifed type name for module
        -main FUN                  Set the main function
        -with MODULE               Import addition module
        -multiple-inclusion        Enables multiple inclusions of the Bigloo includes
        -library LIBRARY           Compile/link with additional Bigloo library
        -srfi SRFI                 Declares srfi support
        -dload-sym                 Emit a Bigloo dynamic loading entry point
        -dload-init-sym NAME       Emit a Bigloo dynamic loading entry point, named NAME
        -heapsize SIZE             Set the initial heap size value (in megabyte)

     Configuration and path:
        -version                   The current release
        -revision                  The current release (short format)
        -query                     Dump the current configuration
        -q                         Do not load any rc file
        -eval STRING               Evaluate STRING before compiling
        -load FILE                 Load FILE before compiling
        -I DIR                     Add DIR to the load path
        -lib-dir DIR               Set lib-path to DIR
        -L NAME                    Set additional library path
        -lib-version VERSION       Set the Bigloo library version
        -libgc-version VERSION     Set the Bigloo GC library version

     Back-end:
        -native                    Compile module to native object file (via C)
        -jvm                       Compile module to JVM .class files
        -dotnet                    Compile module to .NET object files
        -saw                       Cut the AST in the saw-mill
        -no-saw                    Disable saw back-ends
        -i                         Interprete module

     Dialect:
        -snow                      Compiles a snow source code
        -scmpkg,-spi               Compiles a ScmPkg source code
        -nil                       Evaluate '() as #f in `if' expression
        -call/cc                   Enable call/cc function
        -hygien                    Obsolete (R5rs macros are always supported)
        -fno-reflection            Disable reflection code production
        +fno-reflection            Enable reflection code production
        -fclass-nil                Enables generation of "class-nil" function
        -fno-class-nil             Disables generation of "class-nil" function
        -farithmetic               Suppress genericity of arithmetic operators
        -fcase-sensitive           Case sensitive reader (default)
        -fcase-insensitive         Case insensitive reader (downcase symbols)
        -fallow-type-redefinition  allow type redifinition

     Optimization:
        -Obench                    Benchmarking mode
        -O[2..6]                   Optimization modes
        -fcfa-arithmetic           Enable arithmetic spec. (enabled from -O2)
        -fno-cfa-arithmetic        Disable arithmetic spec.
        -funroll-loop              Enable loop unrolling (enabled from -O3)
        -fno-unroll-loop           Disable loop unrolling
        -fno-loop-inlining         Disable loop inlining
        -floop-inlining            Enable loop inlining (default)
        -fno-inlining              Disable inline optimization
        -fno-user-inlining         Disable user inline optimization
        -fbeta-reduce              Enable simple beta reduction (enable from -O2)
        -fno-beta-reduce           Disable simple beta reduction
        -fdataflow                 Enable dataflow optimizations (enable from -O)
        -fno-dataflow              Disable dataflow optimizations
        -fdataflow-for-errors      Enable dataflow optimizations for improviing type error messages
        -fno-dataflow-for-errors   Disable dataflow optimizations for improviing type error messages
        -fO-macro                  Enable Optimization macro (default)
        -fno-O-macro               Disable Optimization macro
        -fglobal-tailc             Enable global tail-call optimization
        -fno-global-tailc          Disable global tail-call optimization
        -fold-closure-integration  Enable old closure integration technique
        -fsaw-realloc              Enable saw register re-allocation
        -fsaw-regalloc             Enable saw register allocation
        -fno-saw-regalloc          Disable saw register allocation
        -fsaw-regalloc-msize SIZE  Set the register allocation body size limit
        -fsaw-regalloc-fun NAME    Allocate registers on this very function
        -fno-saw-regalloc-fun NAME Don't allocate registers on this very function
        -fsaw-regalloc-onexpr      Allocate registers on expressions
        -fno-saw-regalloc-onexpr   Don't allocate registers on expressions

     Safety:
        -unsafe[atrsvle]           Don't check [type/arity/range/struct/version/library/eval]
        -safe[atrsvle]             Enforce check [type/arity/range/struct/version/library/eval]

     Debug:
        -glines                    Emit # line directives
        -gbdb-no-line              Don't emit # line directives
        -gbdb[23]                  Compile with bdb debug informations
        -gself                     Enables self compiler debug options
        -gmodule                   Debug module initialization
        -gerror-localization       Localize error calls in the source code
        -gno-error-localization    Don't localize error calls in the source code
        -gjvm                      Annote JVM classes for debug
        -g[234]                    Produce Bigloo debug informations
        -cg                        Compile C files with debug option
        -export-all                Eval export-all all routines
        -export-exports            Eval export-exports all routines
        -export-mutable            Enables Eval redefinition of all "::obj" routines

     Profiling:
        -p[2]                      Compile files for profiling
        -pg                        Compile files with profiling option

     Verbosity:
        -s                         Be silent and inhibit all warning messages
        -v[23]                     Be verbose
        -hello                     Say hello
        -no-hello                  Dont' say hello even in verbose mode
        -w                         Inhibit all warning messages
        -wslots                    Inhibit overriden slots warning messages
        -Wvariables                Enable overriden variable warning messages
        -Wall                      warn about all possible type errors

     Compilation modes:
        <-/+>rm                    Don't or force removing .c or .il files
        -extend NAME               Extend the compiler
        -fsharing                  Attempt to share constant data
        -fno-sharing               Do not attempt to share constant data
        -fmco                      Produce an .mco file
        -fmco-include-path DIR     Add dir to mco C include path

     Native specific options:
        -cc COMPILER               Specify the C compiler
        -stdc                      Generate strict ISO C code
        -copt STRING               Invoke cc with STRING
        -cheader STRING            C header
        -cfoot STRING              C foot
        -ldopt STRING              Invoke ld with STRING
        -ldpostopt STRING          Invoke ld with STRING (end of arguments)
        -force-cc-o               Force the C compiler to use -o instead of mv
        -ld-relative               Link using -l notation for libraries (default)
        -ld-absolute               Link using absolute path names for libraries
        -static-bigloo             Link with the static bigloo library
        -static-all-bigloo         Link with static version of all bigloo libraries
        -ld-libs1                  Add once user libraries when linking
        -ld-libs2                  Add twice user libraries when linking (default)
        -lLIBRARY                  Link with host library

     Jvm specific options:
        -jvm-shell SHELL           Shell for JVM scripts ("sh", "msdos")
        -jvm-purify                Produce byte code verifier compliant JVM code (default)
        -no-jvm-purify             Don't care about JVM code verifier
        -jvm-mainclass CLASS       JVM main class
        -jvm-classpath PATH        JVM application classpath
        -jvm-bigloo-classpath P    JVM Bigloo rts classpath
        -jvm-path-separator SEP    Set the JVM classpath separator
        -jvm-directory NAME        Directory where to store class files.
        -jvm-catch-errors          Catch internal JVM errors
        -no-jvm-catch-errors       Don't catch internal JVM errors
        -jvm-jarpath NAME          Set the JVM classpath for the produced jar file
        -jvm-cinit-module          Enable JVM class constructors to initiliaze bigloo modules
        -no-jvm-cinit-module       Disable JVM class constructors to initiliaze bigloo modules
        -jvm-char-info             Generate char info for the debugger (in addition to line info)
        -no-jvm-char-info          Do not generate char info for the debugger
        -fjvm-inlining             Enable JVM back-end inlining
        -fjvm-constr-inlining      Enable JVM back-end inlining for constructors
        -fno-jvm-inlining          Disable JVM back-end inlining
        -fno-jvm-constr-inlining   Disable JVM back-end inlining for constructors
        -fjvm-peephole             Enable JVM back-end peephole
        -fno-jvm-peephole          Disable JVM back-end peephole
        -fjvm-branch               Enable JVM back-end branch
        -fno-jvm-branch            Disable JVM back-end branch
        -fjvm-fasteq               EQ? no longer works on integers (use =FX)
        -fno-jvm-fasteq            Disable JVM back-end fasteq transformation
        -jvm-env VAR               Make the shell variable visible to GETENV
        -jvm-jar                   Enable JVM jar files generation
        -no-jvm-jar                Disable JVM jar files generation (default)
        -jvm-java FILE             Use FILE as JVM
        -jvm-opt STRING            JVM invocation option

     .NET specific options:
        -dotnet-managed            Produce byte code verifier compliant .NET code (default)
        -dotnet-unmanaged          Don't care about .NET code verifier
        -dotnet-linux-mono         Compile for Mono on a Linux
        -dotnet-clr FILE           Use FILE as .NET CLR
        -dotnet-clr-style STYLE    Use CLR invokation style
        -dotnet-clr-opt S          Set the .NET CLR options
        -dotnet-ld FILE            Use FILE as .NET LD
        -dotnet-ld-style STYLE     Use LD invokation style
        -dotnet-dll-path NAME      Set the .NET DLL search path
        -dotnet-external-asm       Enable external assembler (default)
        -no-dotnet-external-asm    Disable external assembler
        -ilasm ASM                 Specify external IL assembler
        -fdotnet-tailc             Flag tail calls for inside module calls
        -fno-dotnet-tailc          Don't flag tail calls
        -fdotnet-tailc-full        Flag tail calls everywhere
        -fdotnet-tailc-module      Flag tail calls across modules
        -fno-dotnet-tailc-module   Don't flag tail calls across modules
        -fdotnet-tailc-funcall     Flag tail calls for funcalls
        -fno-dotnet-tailc-funcall  Don't flag tail call for funcalls
        -dotnet-mono-workaround    Workaround Mono .NET buts (switch)
        -no-dotnet-mono-workaround Disable workaround Mono .NET buts (switch)
        -dotnet-pnet-workaround    Workaround pnet swich bug
        -no-dotnet-pnet-workaround Disable Workaround pnet swich bug

     Traces:
        -t[2|3|4]                  Generate a trace file (*)
        +tPASS                     Force pass to be traced
        -shape[mktTalu]            Some debugging tools (private)

     Compilation stages:
        -mco                       Stop after .mco production
        -syntax                    Stop after the syntax stage (see -hygiene)
        -expand                    Stop after the preprocessing stage
        -expand-module             Produce the expanded module clause
        -ast                       Stop after the ast construction stage
        -bdb-spread-obj            Stop after the bdb obj spread stage
        -trace                     Stop after the trace pass
        -callcc                    Stop after the callcc pass
        -bivalue                   Stop after the bivaluation stage
        -inline                    Stop after the inlining stage
        -inline+                   Stop after the 2nd inlining stage
        -beta                      Stop after the constant beta reduction stage
        -fail                      Stop after the failure replacement stage
        -fuse                      Stop after the fuse stage
        -user                      Stop after the user pass
        -coerce                    Stop after the type coercing stage
        -effect                    Stop after the effect stage
        -effect+                   Stop after the 2nd effect stage
        -reduce                    Stop after the reduction opt. stage
        -reduce+                   Stop after the 2nd reduction opt. stage
        -reduce-                   Stop after the very first reduction stage
        -assert                    Stop after the assertions stage
        -cfa                       Stop after the cfa stage
        -closure                   Stop after the globalization stage
        -recovery                  Stop after the type recovery stage
        -bdb                       Stop after the Bdb code production
        -cnst                      Stop after the constant allocation
        -integrate                 Stop after the integration stage
        -tailc                     Stop after the tailc stage
        -init                      Stop after the initialization construction stage
        -egen                      Produce an include file for effects (requires -saw)
        -hgen                      Produce a C header file with class definitions
        -cgen                      Do not C compile and produce a .c file
        -indent                    Produce an indented .c file
        -jvmas                     Produce a JVM .jas file
        -il                        Produce a .NET .asm file

     Constant initialization:
        -init-[lib|read|intern]    Constants initialization mode

     Bootstrap and setup:
        -mklib                     Compile a library module
        -mkaddlib                  Compile an additional library module
        -mkheap                    Build an heap file
        -mkaddheap                 Build an additional heap file
        -mkdistrib                 Compile a main file for a distribution
        -license                  Display the Bigloo license and exit
        -LICENSE                   Add the license to the generated C files
        -heap NAME                 Specify an heap file (or #f to not load heap)
        -heap-library LIB          The library the heap belongs to
        -dump-heap NAME            Dump the content of a heap
        -addheap NAME              Specify an additional heap file
        -fread-internal            Read source from binary interned file
        -fread-plain               Read source from plain text file
        -target LANG               DON'T USE, (see -native, -jvm, -dotnet)

     Shell Variables:
        - TMPDIR
          tmp directory (default "/tmp")
        - BIGLOOLIB
          libraries' directory
        - BIGLOOHEAP
          the initial heap size in megabytes (4 MB by default)
        - BIGLOOSTACKDEPTH
          the error stack depth printing
        - BIGLOOLIVEPROCESS
          the maximum number of Bigloo live processes

     Runtime Command file:
        - ~/.bigloorc


     -----------
      * : only available in developing mode
      . : option enabled from -O3 mode


     Bigloo Control Variables:
        All the Bigloo control variables can be changed from the
        interpreter, by the means of the `-eval' option, or using
        the module clause `option'. For instance the option
        "-eval '(set! *strip* #t)'" will set the variable
        `*strip*' to the value `#t'.
        These variables are:

        - *access-file-default* :
          The default access file name
          default: ".afile"
        - *access-files* :
          The access file names
          default: ()
        - *additional-bigloo-libraries* :
          The user extra Bigloo libraries
          default: ()
        - *additional-bigloo-zips* :
          The user extra Bigloo Zip files
          default: ()
        - *additional-heap-name* :
          A name of an additional heap file name to be build
          default: #f
        - *additional-heap-names* :
          A list of Bigloo additional heap file name
          default: ()
        - *additional-include-foreign* :
          The additional C included files
          default: ()
        - *allow-type-redefinition* :
          If true, allow type redefinitions
          default: #f
        - *ast-case-sensitive* :
          Case sensitivity
          default: #t
        - *auto-mode* :
          auto-mode (extend mode) list
          default: (("ml" . "caml") ("mli" . "caml") ("oon" . "meroon") ("snow" . "snow") ("spi" . "pkgcomp"))
        - *bdb-debug* :
          Bdb debugging mode
          default: 0
        - *bigloo-abort?* :
          Do we have the bigloo-abort function in executables?
          default: #f
        - *bigloo-lib* :
          The Bigloo library
          default: bigloo
        - *bigloo-libraries-c-setup* :
          A list of C functions to be called when starting the application
          default: ()
        - *bigloo-licensing?* :
          Add the Bigloo license ?
          default: #f
        - *bigloo-name* :
          The Bigloo name
          default: "Bigloo (3.1a)"
        - *bigloo-specific-version* :
          The Bigloo specific version
          default: ""
        - *bigloo-tmp* :
          The tmp directory name
          default: "/tmp"
        - *bigloo-user-lib* :
          The user extra C libraries
          default: ("-ldl" "-lgmp" "-lm")
        - *bigloo-version* :
          The Bigloo major release number
          default: "3.1a"
        - *c-debug* :
          C debugging mode?
          default: #f
        - *c-debug-lines-info* :
          Emit # line directives
          default: #f
        - *c-debug-option* :
          cc debugging option
          default: "-g"
        - *c-files* :
          The C source files
          default: ()
        - *c-object-file-extension* :
          The C object file extension
          default: "o"
        - *c-split-string* :
          C split long strings
          default: #f
        - *c-suffix* :
          C legal suffixes
          default: ("c")
        - *c-user-foot* :
          C foot
          default: ()
        - *c-user-header* :
          C header
          default: ()
        - *call/cc?* :
          Shall we enable call/cc?
          default: #f
        - *cc* :
          The C compiler
          default: "gcc"
        - *cc-move* :
          Use mv or -o when C compiling
          default: #t
        - *cc-o-option* :
          The C compiler -o option
          default: "-o "
        - *cc-options* :
          cc options
          default: " -Wpointer-arith -Wswitch -Wtrigraphs -DBGL_BOOTCONFIG"
        - *cc-style* :
          The C compiler style
          default: "gcc"
        - *cflags* :
          The C compiler option
          default: " -Wpointer-arith -Wswitch -Wtrigraphs -DBGL_BOOTCONFIG"
        - *cflags-optim* :
          The C compiler optimization option
          default: "-O3  -Wpointer-arith -Wswitch -Wtrigraphs -DBGL_BOOTCONFIG"
        - *cflags-prof* :
          The C compiler profiling option
          default: "-pg -fno-inline  -Wpointer-arith -Wswitch -Wtrigraphs -DBGL_BOOTCONFIG"
        - *class-nil?* :
          Shall we produce class-nil function for classes
          default: #t
        - *compiler-debug* :
          Debugging level
          default: 0
        - *compiler-sharing-debug?* :
          Compiler self sharing debug
          default: #f
        - *csharp-suffix* :
          C# legal suffixes
          default: ("cs")
        - *debug-module* :
          Module initilazation debugging
          default: 0
        - *default-lib-dir* :
          The default lib dir path (without version)
          default: "/users/serrano/prgm/project/bigloo/lib/3.1a"
        - *dest* :
          The target name
          default: #f
        - *dlopen-init* :
          Emit a standard Bigloo dynamic loading init entry point
          default: #f
        - *dotnet-clr* :
          CLR to be used to run .NET programs
          default: "mono"
        - *dotnet-clr-opt* :
          CLR extra options to be used to run .NET programs
          default: ""
        - *dotnet-clr-style* :
          CLR style to be used to run .NET programs
          default: "mono"
        - *dotnet-dll-path* :
          Bigloo.dll path
          default: #f
        - *dotnet-external-asm* :
          Force using and external assembler for .NET code
          default: "ilasm.pnet"
        - *dotnet-external-asm-style* :
          Force using and external assembler for .NET code
          default: pnet
        - *dotnet-ld* :
          .NET object file linker
          default: "cscc"
        - *dotnet-ld-style* :
          .NET object file linker style
          default: "mono"
        - *dotnet-mono-workaround-switch* :
          Workaround mono 0.23..0.30 bug
          default: #t
        - *dotnet-pnet-workaround-switch* :
          Workaround pnet switch bug
          default: #t
        - *dotnet-shell* :
          .NET object file linker
          default: "sh"
        - *dotnet-tail* :
          Enable/disable tail call generations
          default: #f
        - *dotnet-tail-across-modules* :
          Enable/disable tail call generations across modules
          default: #f
        - *dotnet-tail-funcall* :
          Enable/disable tail call generations for funcall
          default: #f
        - *dotnet-use-external-asm* :
          Force using and external assembler for .NET code
          default: #t
        - *double-ld-libs?* :
          Do we include twice the additional user libraries
          default: #t
        - *error-localization* :
          Localize error calls in the source code
          default: #f
        - *eval-options* :
          A user variable to store dynamic command line options
          default: ()
        - *extend-entry* :
          Extend entry
          default: #f
        - *garbage-collector* :
          The garbage collector
          default: boehm
        - *gc-custom?* :
          Are we using a custom GC library?
          default: #t
        - *gc-lib* :
          The Gc library
          default: bigloogc
        - *global-tail-call?* :
          Do we apply the self-global-tail-call stage?
          default: #f
        - *globalize-integrate-28c* :
          Enable the old closure integration technique (deprecated)
          default: #f
        - *heap-base-name* :
          The Bigloo heap base name
          default: "bigloo"
        - *heap-dump-names* :
          The name of the heap to be dumped
          default: ()
        - *heap-jvm-name* :
          The Bigloo heap file name for the JVM backend
          default: "bigloo.jheap"
        - *heap-library* :
          The library the heap belongs to
          default: bigloo
        - *heap-name* :
          The Bigloo heap file name
          default: "bigloo.heap"
        - *hello* :
          Say hello (when verbose)
          default: #f
        - *include-foreign* :
          The C included files
          default: ("bigloo.h")
        - *include-multiple* :
          Enable/disable multiple inclusion of same file
          default: #f
        - *indent* :
          The name of the C beautifier
          default: "indent -npro -bap -bad -nbc -bl -ncdb -nce -nfc1 -ip0 -nlp -npcs -nsc -nsob -cli0.5 -di0 -l80 -d1 -c0 -ts2 -st"
        - *init-mode* :
          Module initialization mode
          default: read
        - *inlining-kfactor* :
          Inlining growth factor
          default: #<procedure:804d340.1>
        - *inlining-reduce-kfactor* :
          Inlinine growth factor reductor
          default: #<procedure:804d2a0.1>
        - *inlining?* :
          Inlining optimization
          default: #t
        - *interpreter* :
          Shall we interprete the source file?
          default: #f
        - *jvm-bigloo-classpath* :
          JVM Bigloo classpath
          default: #f
        - *jvm-catch* :
          Catch internal errors
          default: #t
        - *jvm-cinit-module* :
          Enable JVM class constructors to initiliaze bigloo modules
          default: #f
        - *jvm-classpath* :
          JVM classpath
          default: "."
        - *jvm-debug* :
          JVM debugging mode?
          default: #f
        - *jvm-directory* :
          JVM object directory
          default: #f
        - *jvm-env* :
          List of environment variables to be available in the compiled code
          default: ()
        - *jvm-foreign-class-id* :
          The identifier of the Jlib foreign class
          default: foreign
        - *jvm-foreign-class-name* :
          The name of the Jlib foreign class
          default: "bigloo.foreign"
        - *jvm-jar?* :
          Enable/disable a JAR file production for the JVM back-end
          default: #f
        - *jvm-jarpath* :
          JVM jarpath
          default: #f
        - *jvm-java* :
          JVM to be used to run Java programs
          default: "java"
        - *jvm-mainclass* :
          JVM main class
          default: #f
        - *jvm-options* :
          JVM options
          default: ""
        - *jvm-path-separator* :
          JVM classpath
          default: #f
        - *jvm-shell* :
          Shell to be used when producing JVM run scripts
          default: "sh"
        - *ld-debug-option* :
          The C linker debugging option
          default: "-g "
        - *ld-library-dir* :
          The ld lib dir path (without version)
          default: "/users/serrano/prgm/project/bigloo/lib"
        - *ld-o-option* :
          The C linker -o option
          default: "-o "
        - *ld-optim-flags* :
          The C linker optimization flags
          default: ""
        - *ld-options* :
          ld options
          default: ""
        - *ld-post-options* :
          ld post options
          default: ""
        - *ld-relative* :
          Relative or absolute path names for libraries
          default: #t
        - *ld-style* :
          ld style
          default: "gcc"
        - *lib-dir* :
          The lib dir path
          default: ("." "/users/serrano/prgm/project/bigloo/lib/3.1a")
        - *lib-mode* :
          Lib-mode compilation?
          default: #f
        - *lib-src-dir* :
          The lib dir path
          default: "runtime"
        - *load-path* :
          The load path
          default: ("." "/users/serrano/prgm/project/bigloo/lib/3.1a")
        - *max-c-foreign-arity* :
          Max C function arity
          default: 16
        - *max-c-token-length* :
          Max C token length
          default: 1024
        - *mco-include-path* :
          Module checksum C include path
          default: (".")
        - *mco-suffix* :
          Module checksum object legal suffixes
          default: ("mco")
        - *module-checksum-object?* :
          Produce a module checksum object (.mco)
          default: #f
        - *multi-threaded-gc?* :
          Are we using a multi-threaded GC?
          default: #f
        - *o-files* :
          The additional obect files
          default: ()
        - *obj-suffix* :
          Object legal suffixes
          default: ("o" "a" "so")
        - *optim* :
          Optimization level
          default: 0
        - *optim-O-macro?* :
          Enable optimization by macro-expansion
          default: #f
        - *optim-cfa-arithmetic?* :
          Enable refined arithmetic specialization
          default: #f
        - *optim-dataflow-for-errors?* :
          Enable simple dataflow optimization for eliminating bad error messages
          default: #t
        - *optim-dataflow?* :
          Enable simple dataflow optimization
          default: #f
        - *optim-integrate?* :
          Enable function integration (closure analysis)
          default: #t
        - *optim-jvm* :
          Enable optimization by inlining jvm code
          default: 0
        - *optim-jvm-branch* :
          Enable JVM branch tensioning
          default: 0
        - *optim-jvm-constructor-inlining* :
          Enable JVM inlining for constructors
          default: 0
        - *optim-jvm-fasteq* :
          EQ? no longer works on integers (use =FX instead)
          default: #f
        - *optim-jvm-inlining* :
          Enable JVM inlining
          default: 0
        - *optim-jvm-peephole* :
          Enable JVM peephole optimization
          default: 0
        - *optim-loop-inlining?* :
          Loop inlining optimization
          default: #t
        - *optim-reduce-beta?* :
          Enable simple beta reduction
          default: #f
        - *optim-symbol-case* :
          Optimize case forms descrimining on symbols only
          default: #f
        - *optim-unroll-loop?* :
          Loop unrolling optimization
          default: #unspecified
        - *pass* :
          Stop after the pass
          default: ld
        - *pre-processor* :
          An optional function that pre-processes the source file
          default: #<procedure:804d270.1>
        - *prof-table-name* :
          Bprof translation table file name
          default: "bmon.out"
        - *profile-library* :
          Use the profiled library version
          default: #f
        - *profile-mode* :
          Bigloo profile mode
          default: 0
        - *purify* :
          Produce byte code verifier compliant JVM code
          default: #t
        - *qualified-type-file* :
          The qualifed-type association file name
          default: #f
        - *qualified-type-file-default* :
          The qualifed-type association file name
          default: ".jfile"
        - *reader* :
          The way the reader reads input file ('plain or 'intern)
          default: plain
        - *reflection?* :
          Shall we produce reflection code for classes
          default: #t
        - *rm-tmp-files* :
          Shall the .c and .il produced files be removed?
          default: #t
        - *saw* :
          Do we go to the saw-mill?
          default: #f
        - *saw-no-register-allocation-functions* :
          The list of functions disabling register allocation
          default: ()
        - *saw-register-allocation-functions* :
          The list of functions allowing register allocation
          default: ()
        - *saw-register-allocation-max-size* :
          Max function size for optimizing the register allocation
          default: 4000
        - *saw-register-allocation-onexpression?* :
          Enable/disable saw register allocation on expression
          default: #f
        - *saw-register-allocation?* :
          Enable/disable saw register allocation
          default: #f
        - *saw-register-reallocation?* :
          Enable/disable saw register re-allocation
          default: #f
        - *shared-cnst?* :
          Shared constant compilation?
          default: #t
        - *shell* :
          The shell to exec C compilations
          default: "/bin/sh"
        - *src-files* :
          The sources files
          default: ()
        - *src-suffix* :
          Scheme legal suffixes
          default: ("scm" "bgl")
        - *startup-file* :
          A startup file for the interpreter
          default: #f
        - *static-all-bigloo?* :
          Do we use the static version of all Bigloo libraries
          default: #f
        - *static-bigloo?* :
          Do we use the static Bigloo library
          default: #f
        - *stdc* :
          Shall we produced ISO C?
          default: #f
        - *strip* :
          Shall we strip the executable?
          default: #t
        - *target-language* :
          The target language (either c, c-saw, jvm, or .net)
          default: native
        - *trace-name* :
          Trace file name
          default: "trace"
        - *trace-write-length* :
          Trace dumping max level
          default: 80
        - *unsafe-arity* :
          Runtime type arity safety
          default: #f
        - *unsafe-eval* :
          Disable type check for eval functions
          default: #f
        - *unsafe-library* :
          Use the unsafe library version
          default: #f
        - *unsafe-range* :
          Runtime range safety
          default: #f
        - *unsafe-struct* :
          Runtime struct range safety
          default: #f
        - *unsafe-type* :
          Runtime type safety
          default: #f
        - *unsafe-version* :
          Module version safety
          default: #f
        - *user-heap-size* :
          Heap size (in MegaByte) or #f for default value
          default: #f
        - *user-inlining?* :
          User inlining optimization
          default: #t
        - *user-pass* :
          The user specific compilation pass
          default: #unspecified
        - *verbose* :
          The verbosity level
          default: 0
        - *warning-overriden-slots* :
          Set to #t to warn about virtual slot overriding
          default: #t
        - *warning-overriden-variables* :
          Set to #t to warn about variable overriding
          default: #f
        - *with-files* :
          The additional modules
          default: ()


File: bigloo.info,  Node: User Extensions,  Next: Bee,  Prev: Compiler Description,  Up: Top

28 User Extensions
******************

The extension package system allows the language compiled by Bigloo to
be extended and this is achieved by associating an _extension file_
with a suffix. The _extension file_ is loaded at the beginning of a
compilation and it can do three things: call extern programs (unix
programs); define macros; modify the values of some of the compiler's
variables (for example, the list of the libraries to be linked with).
The Bigloo's initializing procedure is the following:

   * If it exists, Bigloo loads the runtime-command file, see Section
     *note Compiler Description::.

   * It then parses the command line to find the source file to compile.

   * It extracts the source file suffix and looks it up in its
     `*auto-mode*' variable.  

   * If the suffix is found, the associated file is loaded. This file
     could contain a function named `*extend-entry*' which must accept
     a list as argument. It is invoked with the Bigloo's unparsed
     arguments.  

   * The result of the `*extend-entry*' application has to be a regular
     list of arguments and these are parsed by Bigloo.

  For now, two extension packages exist: the Meroon package which is a
native version of the Christian Queinnec object language; the Camloo
[SerranoWeis94] package which is a front end compiler for the Caml
language [Caml-light]

  Furthermore, Bigloo supports the `-extend' option which forces the
usage of an extension file. When Bigloo encounters this option, it
immediately loads the extension file, invoking the function
`*extend-entry*' with the list of arguments which have not been parsed
yet.

  The extension files are always sought in the directory containing the
Bigloo's libraries.

28.1 User pass
==============

Bigloo allows the user to add a special pass to the regular compilation,
this pass taking place _before_ macro expansion. There are two ways to
add a user pass.

   * Add a compiled pass: The module `user_user' (in the
     "comptime/User/user.scm" file) is the user entry pass point.  To
     add a compiled pass, put the code of the pass in this directory,
     import your new modules in `user_user' and modify the `user-walk'
     function.

   * Add an interpreted pass: Set the value of `*user-pass*', which has
     to be a unary function, in your `.bigloorc' file and Bigloo will
     invoke it with the code as argument.  


File: bigloo.info,  Node: Bee,  Next: Global Index,  Prev: User Extensions,  Up: Top

29 Bigloo Development Environment
*********************************

Bigloo release 2.0 or more recent contains an Integrated Development
Environment. This environment proposes some services:

   * Automatic Makefile creation and update.

   * Code browsing.

   * Revision control.

   * Symbol debugging.

   * Profiling.

   * On-line documentation.

   * Source code interpretation.

   * Source code expansion.

   * Literate programming.

  The environment relies on Bigloo tools:
   * `bglafile': a Module access file generator (*note Module Access
     File::).

   * `bglmake': a Makefile creator.

   * `bgldepend': a that creates Bigloo dependencies in makefiles.

   * `bglpp': a pretty printer.

   * `bglprof': a profiler

   * `bgltags': a generator of tag file for Emacs.

  Each of these tools comes with a dedicated manual page and are not
described in this documentation.

  Extra tools are required for the environment to go its full speed:
   * `Emacs' version 21 (or more recent) (`http://www.emacs.org/') or
     `Xemacs' version 20.4 (or more recent) (`http://www.xemacs.org/').

   * `prcs' version 1.2.1 or more recent
     (`http://prcs.sourceforge.net/').

   * `gdb' version 4.17 or more recent (`http://www.cygnus.com/gdb/').

   * `gprof' (`ftp:/prep.ai.mit.edu:pub/gnu/').

   * `texinfo' (`ftp:/prep.ai.mit.edu:pub/gnu/').

   * `gmake' (`ftp:/prep.ai.mit.edu:pub/gnu/').

  The following document describes the BEE, the Bigloo Emacs
Environment.

* Menu:

* Installing the Bee::
* Entering the Bee::
* The Bee Root Directory::
* Building a Makefile::
* Compiling::
* Interpreting::
* Pretty Printing::
* Expansing::
* On-line documentation::
* Searching for source code::
* Importing and Exporting::
* Debugging::
* Profiling::
* Revision control::
* Literate Programming::


File: bigloo.info,  Node: Installing the Bee,  Next: Entering the Bee,  Prev: Bee,  Up: Bee

29.1 Installing the BEE
=======================

The standard procedure for installing Bigloo handles the compilation of
all tools required by the BEE. Additional Emacs-lisp code have to be
appended to your `.emacs' file:

     (autoload 'bdb "bdb" "bdb mode" t)
     (autoload 'bee-mode "bee-mode" "bee mode" t)

     (setq auto-mode-alist
           (append '(("\\.scm$" . bee-mode)
                     ("\\.sch$" . bee-mode)
                     ("\\.scme$" . bee-mode)
                     ("\\.bgl$" . bee-mode)
                     ("\\.bee$" . bee-mode))
                   auto-mode-alist))

  This code will force `emacs' to switch to BEE mode when editing
Scheme source files.


File: bigloo.info,  Node: Entering the Bee,  Next: The Bee Root Directory,  Prev: Installing the Bee,  Up: Bee

29.2 Entering the Bee
=====================

Once, your `.emacs' is updated, to start the BEE you just need to edit
a file suffixed with one of the suffix listed in AUTO-MODE-ALIST with
Emacs. You may either enter the Bee within Emacs with `ESC-X: bee-mode'.


File: bigloo.info,  Node: The Bee Root Directory,  Next: Building a Makefile,  Prev: Entering the Bee,  Up: Bee

29.3 The _Bee Root Directory_
=============================

The _Bee Root Directory_ is the directory that contains information
files that describe a project. When editing a file, the BEE tries to
automatically setup the _Bee Root Directory_. For that, it seeks one of
the following file: `Makefile', `.afile' or `.etags'.  This search
unwind directories until the root directory is reached or until the
number of scanned directories is more than the value of the list
variable `bee-root-search-depth'.

  An alternative _Bee Root Directory_ may be set. This is done clicking
on the `Root' of the tool bar icon.


File: bigloo.info,  Node: Building a Makefile,  Next: Compiling,  Prev: The Bee Root Directory,  Up: Bee

29.4 Building a Makefile
========================

Once, the _Bee Root Directory_ has been setup (it is printed on the
left part to the Emacs modeline), a `Makefile' can be automatically
produced. It can be achieved clicking on the `Mkmf' icon of the tool
bar, using the popup menu (`button-3') entries, or using one of the two
keyboard bindings `C-c C-c C-a' or `C-c C-c C-l'.  When creating a
`Makefile', you will be asked to give a file name.  This file must be
the one that is the main entry point of your program or the one that
implements an library heap file.

  When the `Makefile' already exists, using the same bindings update
Makefile, re-generate `.afile' and `.etags' files.


File: bigloo.info,  Node: Compiling,  Next: Interpreting,  Prev: Building a Makefile,  Up: Bee

29.5 Compiling
==============

Once a `Makefile' exists, it is possible to compile a program (or a
library). Use either the tool bar icon `Compile', the popup menu entry
or `C-c C-c C-c'. If no `Makefile' exists, the BEE will emit a single
file compilation.


File: bigloo.info,  Node: Interpreting,  Next: Pretty Printing,  Prev: Compiling,  Up: Bee

29.6 Interpreting
=================

Scheme source code may be interpreted within the BEE instead of been
compiled prior to be executed. This facility could be convenient for
fast prototyping. A _Read eval print_ loop (henceforth _Repl_) could be
spawned using the `Repl' icon of the tool bar, using the popup menu
entry or using the `C-c C-r C-r' binding.

  Parts or the whole buffer may be sent to _repl_.

   * `C-c C-r b' sends the whole buffer.

   * `C-c C-r d' sends the define form the cursor is in.

   * `C-c C-r l' sends the s-expression that preceeds the cursor.

   * `C-c C-r t' sends the top level s-expression the cursor is in.

   * `C-c C-r r' sends the marked region.


File: bigloo.info,  Node: Pretty Printing,  Next: Expansing,  Prev: Interpreting,  Up: Bee

29.7 Pretty Printing
====================

The whole buffer may be pretty printed (long source lines are split)
using the `Lisp' icon of the tool bar, using the popup menu entry of
using `C-c C-i <tab>'.

  Parts or the buffer may be indented (no line is split).

   * `C-c C-i d' indents the define form the cursor is in.

   * `C-c C-i l' indents the s-expression that preceeds the cursor.

   * `C-c C-i t' indents the top level s-expression the cursor is in.


File: bigloo.info,  Node: Expansing,  Next: On-line documentation,  Prev: Pretty Printing,  Up: Bee

29.8 Expansing
==============

For debug purposes, result of the source code macro expansion may be
checked within the BEE.

  Parts or the whole buffer may be sent to _repl_.

   * `C-c C-e C-e' expands the whole buffer.

   * `C-c C-e C-d' expands the define form the cursor is in.

   * `C-c C-e C-l' expands the s-expression that preceeds the cursor.

   * `C-c C-e C-t' expands the top level s-expression the cursor is in.

   * `C-c C-e C-r' expands the marked region.

  When a part of the buffer is expanded (by opposition to the whole
buffer), the buffer is scan for macro definitions. These macros will be
used for expanding the requested form.


File: bigloo.info,  Node: On-line documentation,  Next: Searching for source code,  Prev: Expansing,  Up: Bee

29.9 On-line Documentation
==========================

On-line documentation may be popped up. This is always done, clicking on
the `Info' icon of the tool bar or `C-c C-d i'. If an emacs region is
active, the documentation about that region will be popped up.  If the
cursor is at a Scheme identifier, the documentation of that identifier
will be printed. Otherwise, the user will be prompted for the Section
of the documentation to be printed.

  Clicking on the `?' icon tool bar, pops up a short description of the
Bigloo compiler options.

  The BEE uses `info' files for printing On-line documentation. It
always search the standard documentation and the standard definition of
Scheme. It is possible to add extra `info' files to be searched.  The
BEE always checks for a directory `info' in the _Bee Root Directory_.
If such a directory exists, contained file will be considered for the
search of a document.


File: bigloo.info,  Node: Searching for source code,  Next: Importing and Exporting,  Prev: On-line documentation,  Up: Bee

29.10 Searching for Source Code
===============================

Searching for source (variable declaration, module definition, variable
usage) is supported by the BEE. Clicking on the `Find' icon of the tool
bar will pops up the definition of the variable the cursor is in or the
definition of the module the cursor is in. These two operations may be
requested using `C-x 5 .' for searching a variable definition, `C-c C-d
m' for a module definition.

  Information and usages of a variable may be printed using either the
`Doc' icon of the tool bar or the `C-c C-d u' key binding.


File: bigloo.info,  Node: Importing and Exporting,  Next: Debugging,  Prev: Searching for source code,  Up: Bee

29.11 Importing and Exporting
=============================

Bigloo bindings (functions and variables) may be automatically inserted
in an export module clause (*note Modules::). Bring the cursor to an
identifier of a binding that has to be exported then, either click on
the `Export' tool bar icon or use the `C-c C-m b' key binding.

  Bigloo bindings may be automatically inserted in an import module
clause.  Bring the cursor to an identifier of a binding that has to be
imported.  Either click on the `Import' tool bar icon or use the `C-c
C-m i' key binding. The BEE, will search the modules for the wanted
binding.

  Foreign bindings (e.g. C variables and C functions) may be
automatically inserted in the file module clause. Click on the `Extern'
tool bar icon or use the key binding `C-c C-m c' to import whole the
definition of an extern file. You will, be prompted an extern file name
to be imported.  This operation _automatically updates_ the `Makefile'
for reflecting that the extern file is required in the compilation.


File: bigloo.info,  Node: Debugging,  Next: Profiling,  Prev: Importing and Exporting,  Up: Bee

29.12 Debugging
===============

The Bigloo symbolic Debugger may be spawned either clicking on the
`Bdb' tool bar icon or using the key binding `C-c C-b C-b'.  Once the
debugger is not is possible to connect the current buffer to the
debugger. This is done using the tool bar icon `Connect' or the key
binding `C-c C-b c'. This enables breakpoints to be inserted using
mouse clicks.


File: bigloo.info,  Node: Profiling,  Next: Revision control,  Prev: Debugging,  Up: Bee

29.13 Profiling
===============

Automatically produced `Makefile' provides entry for profiling. In
order to get a profile you must first compile your application for
profiling.  This is done using a popup menu entry or the `C-c C-p c'
key binding. Once your program compiled you can run for profile using a
popup menu entry of the `C-c C-p r' key binding. This last will run
your program, run `bglprof' to get the profile and this will pops up a
window displaying the profile informations.


File: bigloo.info,  Node: Revision control,  Next: Literate Programming,  Prev: Profiling,  Up: Bee

29.14 Revision Control
======================

Submitting a new revision is done using `C-c C-v i' or using an menu
bar entry. This builds an new revision for the entire project.  The
file that compose the project are listed in the `pop' entry of the _Bee
Root Directory_ `Makefile'.

  Checking out an older version of the file currently edited is done
using the key binding `C-c C-v C-o'. This is not a retrieval of the
entire project. Global check out may be performed manually.

  Comparing the version of the file currently edited with older one is
done using `C-c C-v d'. A _diff_ of the two buffers will be popped up.

  With both checking out and comparison of versions. A window presenting
all the available version will be popped up to let you choose which
version you would like to inspect.


File: bigloo.info,  Node: Literate Programming,  Prev: Revision control,  Up: Bee

29.15 Literate Programming
==========================

The BEE does not provide real _Literate Programming_. The reason is
that we think that when editing documentation we want to benefit the
full power of context-sensitive editors and we don't want to edit the
documentation is the same editor _mode_ as the one we use when editing
source code. Nevertheless it is possible to place anchors within the
source file to the corresponding documentation file. Then, by the means
of simple mouse clicks, it becomes possible to edit the documentation
of peace of codes. The current BEE literate programming system only
supports the _Texinfo_ file format.

  For that purpose three anchors are available: `path', `node' and
`deffn'. All anchor have to be delimited with `@' characters.

   * `path': this anchor set the path to the file containing the
     documentation. Thus,

          (module foo
             ;; @path manuals/foo.texi@
             ...)

     Tells the BEE that the documentation for the module `foo' is
     located in the file named `manuals/foo.texi'.

   * `node': sets the name of the node that documents this particular
     source file code.

          (module foo
             ;; @path manuals/foo.texi@
             ;; @node Foo@
             ...)

   * `deffn': each variable binding may point to its documentation.
     For that, it suffices to use the `deffn' anchor just before the
     variable definition or within the s-expression that defines the
     variable.

          ;; @deffn foo@
          (define (foo . chars)
             ...)
     or
          (define (foo . chars)
             ;; @deffn foo@
             ...)

     When clicking on that anchor, the BEE will search the
     documentation file named by the `path' anchor and within that
     file, will search for a _texinfo_ `deffn' command that defines the
     variable named in the anchor.

