\input texinfo.tex      @c -*-texinfo-*-
@c %**start of header
@setfilename kawa.info
@settitle Kawa, the Java-based Scheme system
@setchapternewpage off
@syncodeindex fn cp
@syncodeindex vr cp
@c version: %W% %G%
@c %**end of header

@include version.texi

@iftex
@finalout
@end iftex
@titlepage
@title Kawa, the Java-based Scheme system
@subtitle @value{UPDATED}
@sp 1
@author Per Bothner
@page
@end titlepage

@ifinfo
@format
START-INFO-DIR-ENTRY
* kawa: (kawa).         Kawa, the Java-based Scheme system
END-INFO-DIR-ENTRY
@end format
@end ifinfo

@ifnottex
@node Top, Features, (dir), (dir)
@top
@unnumbered The Kawa Scheme system, by Per Bothner
@end ifnottex

Kawa is a Scheme environment, written in Java,
and that compiles Scheme code into Java byte-codes.

This documents version @value{VERSION}, updated @value{UPDATED}.

See the summary
of @uref{http://www.gnu.org/software/kawa/NEWS,recent changes}.

The author of Kawa is
@uref{http://www.bothner.com/per/,Per Bothner}
@email{per@@bothner.com}.
Kawa is a re-write of Kawa 0.2, which was written by
R. Alexander Milowski @email{alex@@milowski.com}.

The Kawa home page (which is currently just an on-line
version of this document) is @uref{http://www.gnu.org/software/kawa/}.

The
@uref{http://www.cs.indiana.edu/scheme-repository/home.html,Scheme repository}
has various useful information on Scheme.
but it is not very actively updated.
A new repository has been started at
@uref{http://www.schemers.org/,www.schemers.org}.
It includes pointer to an online copy of
@uref{http://www.schemers.org/Documents/Standards/,R5RS}.

A nice quick introduction to Scheme can be found in
@uref{http://www.cs.washington.edu/education/courses/341/99su/lectures/scheme/,Greg Badros's lecture notes}.  A more in-depth tutorial which also
discusses Scheme implementation is
@uref{http://www.cs.utexas.edu/users/wilson/schintro/schintro_toc.html, Paul Wilson's "An Introduction to Scheme and its Implementation"}.

Javadoc generated @uref{http://www.gnu.org/software/kawa/api/,documentation of the Kawa classes} is also available.
The packages
@uref{http://www.gnu.org/software/kawa/api/gnu/bytecode/package-summary.html,@code{gnu.bytecode}},
@uref{http://www.gnu.org/software/kawa/api/gnu/math/package-summary.html,@code{gnu.math}},
@uref{http://www.gnu.org/software/kawa/api/gnu/lists/package-summary.html,@code{gnu.lists}},
@uref{http://www.gnu.org/software/kawa/api/gnu/xml/package-summary.html,@code{gnu.xml}},
@uref{http://www.gnu.org/software/kawa/api/gnu/expr/package-summary.html,@code{gnu.expr}},
@uref{http://www.gnu.org/software/kawa/api/gnu/mapping/package-summary.html,@code{gnu.mapping}},
and
@uref{http://www.gnu.org/software/kawa/api/gnu/text/package-summary.html,@code{gnu.text}},
are used by Kawa, and distributed with it, but may be independently useful.

For a technical overview of Kawa, see these
@uref{http://www.gnu.org/software/kawa/internals.html}.

For copyright information on the software and documentation,
see @ref{License}.

Kawa is partly sponsored by @uref{http://www.brainfood.com/,Brainfood}.

This package has nothing to do with the
@uref{http://www.macromedia.com/software/kawa/,Kawa commercial Java IDE}.

@menu
* Features::
* Getting Kawa::
* Installation::         Building and installing Kawa
* Running::              How to start up and run Kawa
* Restrictions::         Features of R5RS not implemented
* Compiling::            Compiling Scheme code to byte-code or an executable
* Extensions::           Various Kawa features not in standard Scheme
* Input-Output::         Input, output, and file handling
* Types::
* Objects Classes and Modules::
* Low-level functions::  The Scheme-Java interface
* XML tools::            Tools for working with XML and HTML
* KRL::                  The Kawa Report Language for generating XML/HTML
* Mailing lists::        Where to report bugs, discuss changes, etc
* Support::              Technical support for Kawa
* Projects::             Projects using Kawa
* License::
* Overall Index::	 Index of functions, macros, concepts, and more.
@end menu

@node Features, Getting Kawa, Top, Top
@chapter Features

Kawa is a full Scheme implementation.  It implements almost
all of R5RS (for exceptions @pxref{Restrictions}), plus some extensions.
By default, symbols are case sensitive.

It is completely written in Java.  Scheme functions and files
are automatically compiled into Java byte-codes.  Kawa does some
optimizations, and the compiled code runs at reasonable speed.

Kawa uses Unicode internally, and uses the Java facilities to convert
files using other character encodings.

Kawa provides the usual read-eval-print loop, as well as batch modes.

Kawa provides a framework for implementing other progressing languages,
and comes with incomplete support for CommonLisp, Emacs Lisp, and
EcmaScript, and the
draft @uref{http://www.gnu.org/software/qexo/,XML Query language}.

Kawa is written in an object-oriented style.

Kawa has builtin pretty-printer support, and fancy formatting.

Kawa supports class-definition facilities, and separately-compiled modules.

Kawa implements the full numeric tower, including infinite-precision
rational numbers and complex numbers.  It also supports "quantities"
with units, such as @code{3cm}.

You can optionally declare the types of variables.

You can conveniently access Java objects, methods, fields, and classes.

Kawa implements most of the features of the expression language of DSSSL,
the Scheme-derived ISO-standard Document Style Semantics and Specification
Language for SGML.  Of the core expression language, the only features
missing are character properties, @code{external-procedure},
the time-relationed procedures, and character name escapes in
string literals.  Also, Kawa is not generally tail-recursive.
From the full expression language, Kawa additionally is missing
@code{format-number}, @code{format-number-list}, and language objects.
Quantities, keyword values, and the expanded @code{lambda} form
(with optional and keyword parameters) are supported.

Kawa implements the following semi-standard SRFIs
(@uref{http://srfi.schemers.org/,Scheme Request for Implementation}):
@itemize
@item
SRFI 0: Feature-based conditional expansion construct,
using @code{cond-expand} - @pxref{Syntax and conditional compilation}.
@item
SRFI 1: @uref{http://srfi.schemers.org/srfi-1/srfi-1.html,List Library}, if @code{(require 'list-lib)}.
@item
SRFI 4: Homogeneous numeric vector datatypes - @pxref{Uniform vectors}..
@item
SRFI 6: Basic String Ports - @pxref{Ports}.
@item
SRFI 8: @code{receive}: Binding to multiple values - @pxref{Multiple values}.
@item
SRFI 9: Defining Record Types, using @code{define-record-type}
- @pxref{Record types}.
@item
SRFI 11: Syntax for receiving multiple values,
using @code{let-values} and @code{let*-value} - @pxref{Multiple values}.
@item
SRFI 17: Generalized @code{set!} - @pxref{Locations}.
@item
SRFI 23: Error reporting mechanism, using @code{error} - @pxref{Exceptions}.
@item
SRFI 25: Multi-dimensional Array Primitives - @pxref{Arrays}.
@item
SRFI 26: Notation for Specializing Parameters without Currying - @pxref{Procedures}. 
@item
SRFI 28: Basic Format Strings - @pxref{Format}.
@item
SRFI 30: Nested Multi-line Comments.
@end itemize

@node Getting Kawa, Installation, Features, Top
@chapter Getting Kawa

You can get Kawa sources and binaries from the Kawa ftp site
@uref{ftp://ftp.gnu.org/pub/gnu/kawa/},
or from a @uref{http://www.gnu.org/order/ftp.html,mirror site}.

The latest release of the Kawa source code is
@uref{ftp://ftp.gnu.org/pub/gnu/kawa/kawa-@value{VERSION}.tar.gz}.
The same sources are available as a zip file
@uref{ftp://ftp.gnu.org/pub/gnu/kawa/kawa-@value{VERSION}-src.zip}.

A ready-to-run @code{.jar} archive of the pre-compiled classes is in
@uref{ftp://ftp.gnu.org/pub/gnu/kawa/kawa-@value{VERSION}.jar}.

You can also check out the very latest version via anonymous cvs.
@example
cvs -d :pserver:anoncvs@@sources.redhat.com:/cvs/kawa login
     (password is ``anoncvs'')
cvs -d :pserver:anoncvs@@sources.redhat.com:/cvs/kawa co kawa
@end example

Once you have it checked out, you can update it with @code{cvs update}.

You can also
@uref{http://sources.redhat.com/cgi-bin/cvsweb.cgi/kawa/?cvsroot=kawa,view
the cvs archive} via cvsweb.

@node Installation, Running, Getting Kawa, Top
@chapter Building and installing Kawa

Before installing Kawa, you must have Java working on your
system.

You can compile Kawa from the source distribution.
Alternatively, you can install the pre-compiled binary distribution.

@menu
* Running Java::                Getting and running Java
* Binary distribution::         Installing and using the binary distribution
* Source distribution::         Installing and using the source distribution
@end menu

@node Running Java, Binary distribution, , Installation
@section Getting and running Java

You will need a working Java system.  Kawa has been reported to
work with JDK from 1.1 through 1.4.x, Kaffe, Symantec Cafe, J++, and GCJ.

The discussion below assumes you are using the Java Developer's Kit
(JDK) from JavaSoft (Sun).  You can download free copies of
@uref{http://java.sun.com/j2se/1.4/, JDK 1.4} for various platforms.

If you want to run Kawa on a Macintosh, see
@uref{http://home.earthlink.net/%7Eathene/scheme/mackawa.html}.

The program @code{java} is the Java interpreter.
The program @code{javac} is the Java compiler,
and is needed if you want to compile the source release yourself.
Both programs must be in your @code{PATH}.
If you have the JDK in directory @code{$JDK},
and you are using a Bourne-shell compatible shell
(/bin/sh, ksh, bash, and some others) you can set @code{PATH} thus:
@example
PATH=$JDK/bin:$PATH
export PATH
@end example

@node Binary distribution, Source distribution, Running Java, Installation
@section Installing and using the binary distribution

The binary release includes only the binary compiled @samp{.class}
versions of the same @samp{.java} source files in the source release.
It does not include any documentation, so you probably want the
source release in addition to the binary release.  The purpose
of the binary release is just to save you time and trouble of
compiling the sources.

The binary release depends on certain "Java 2" features, such as
collections.  If you have an older Java implementation (including
JDK 1.1.x) you will need to get the source distribution.

The binary release comes as a @code{.jar} archive
@samp{kawa-@value{VERSION}.jar}.

You can unzip the archive, or you can use it as is.
Assuming the latter, copy the archive to some suitable location,
such as @code{/usr/local/lib/kawa.jar}.

Then, before you can actually run Kawa, you need to set @code{CLASSPATH}
so it includes the Kawa archive.  On Unix, using a Bourne-style shell:
@example
CLASSPATH=/usr/local/lib/kawa.jar
export CLASSPATH
@end example

On Windows you need to set @code{classpath} in a DOS console.
For example:
@example
set classpath=\kawa\kawa-@value{VERSION}.jar
@end example

Then to run Kawa do:
@example
java kawa.repl
@end example

To run Kawa in a fresh window, you can do:
@example
java kawa.repl -w
@end example

@node Source distribution,  , Binary distribution, Installation
@section Installing and using the source distribution
The Kawa release normally comes as a gzip-compressed tar file named
@samp{kawa-@value{VERSION}.tar.gz}.
The same sources are available as a zip file
@samp{kawa-@value{VERSION}-src.zip}.
Two methods are supporting for compiling the Kawa sources;
choose whichever is most convenient for you.

One method uses the traditional GNU @code{configure} script,
followed by running @code{make}.  This works well on Unix-like
systems, such as GNU/Linux.  It does not work well under
Microsoft Windows. (Even when using the CygWin Unix-emulation
package there are some problems with file paths.)

The other method uses the @code{ant} command, a Java-based
build system released by Apache's Jakarta project.  This uses
an @code{build.xml} file in place of @code{Makefile}s, and
works on non-Unix systems such as Microsoft Windows.  However,
the @code{ant} method does not support all
the features of the @code{configure}+@code{make} method.

@subsection Build Kawa using @code{configure} and @code{make}

In your build directory do:
@example
tar xzf kawa-@value{VERSION}.tar.gz
cd kawa-@value{VERSION}
@end example

Then you must configure the sources.  This you can do
the same way you configure most other GNU software.  Normally
you can just run the configure script with no arguments:

@example
./configure
@end example

This will specify that a later @code{make install} will install the
compiled @samp{.class} files into @code{/usr/local/share/java}.
If you want them
to be installed someplace else, such as @code{$PREFIX/share/java}, then
specify that when you run configure:
@example
./configure --prefix $PREFIX
@end example

If you have the GNU @samp{readline} library installed, you might try
adding the @samp{--enable-kawa-frontend} flag.  This will build the
@samp{kawa} front-end program, which provides input-line editing
and an input history.  You can get @samp{readline} from archives
of GNU programs, including @uref{ftp://www.gnu.org/}.

If you have Swing installed, and want to use JEmacs (Emacs in Java),
also pass the @code{--with-swing} flag to @code{configure}.

If you have installed Kawa before, make sure your @code{CLASSPATH}
does not include old versions of Kawa, or other classes that may
conflict with the new ones.

If you use a very old or bare-bones Java implementation that not have
certain "Java 2" features
(such as @code{java.util.List}, @code{java.lang.ref}, or @code{ThreadLocal})
then you need to convert the Kawa source-code so it doesn't depend
on those features.
You do this with the following command:
@example
make select-java1
@end example
Most people should not need to do this.  (You don't need to if you're
using GCJ, even though it doesn't implement all of Java 2.)  (If you
need to convert the code back to the default, do: @code{make select-java2}.)

Then you need to compile all the .java source files.
Just run make:
@example
make
@end example
This assumes that @samp{java} and @samp{javac} are the java interpreter
and compiler, respectively.
For example, if you are using the Kaffe Java interpreter,
you need to instead say:
@example
make JAVA=kaffe
@end example

You can now test the system by running Kawa in place:
@example
java kawa.repl
@end example

or you can run the test suite:
@example
make check
@end example

or you can install the compiled files:
@example
make install
@end example

This will install your classes into @code{$PREFIX/share/java} (and its
sub-directories).  Here @code{$PREFIX} is the directory you specified
to configure with the @code{--prefix} option, or @code{/usr/local} if you
did not specify a @code{--prefix} option.

To use the installed files, you need to set @code{CLASSPATH} so
that @code{$PREFIX/share/java/kawa.jar} is in the path:
@example
CLASSPATH=$PREFIX/share/java/kawa.jar
export CLASSPATH
@end example
This is done automatically if you use the @samp{kawa} script.

@subsection Build Kawa using @code{ant}

Kawa now includes an Ant buildfile (@code{build.xml}).
@uref{http://jakarta.apache.org/ant/, Ant} is a part of the Apache
Jakarta project.
If you don't hava Ant installed,
get it from @uref{http://ant.apache.org/bindownload.cgi}.
The buildfile should work with Ant 1.3, and has been
tested with 1.4.1. and 1.5.1.
The build is entirely Java based and works equally well on *nix, Windows,
and presumably most any other operating system.

Once Ant has been installed and configured (you may need to set the
@code{JAVA_HOME}, and @code{ANT_HOME} environment variables), you should
be able to change to the directory containing the @code{build.xml} file,
and invoke the @samp{ant} command.  With the default settings, a
successful build will result in a @code{kawa-@value{VERSION}.jar} in the
current directory

There are a few Ant "targets" of interest (they can be supplied on the
Ant command line):

@table @code
@item all
This is the default, it does @code{classes} and @code{jar}.
@item classes
Compiles all the files into @code{*.class} files into the directory
specified by the @code{build.dir} property.
@item jar
Builds a jar into into the directory
specified by the @code{dist.dir} property.
@item runw
Run Kawa in a GUI window.
@item clean
Deletes all files generated by the build, including the jar.
@end table

There is not yet a @code{test} target for running the testsuite.

The are various "properties" that control what @code{ant} does.  You can
override the on the command line or by editing the
@code{build.properties} file in the same directory as @code{build.xml}.
For example the @code{build.dir} directory tells @code{ant} where to
build temporary files, and where to leave the resulting @code{.jar}
file.  For example, to leave the generated files in the sub-directory
named @code{BUILD} do:
@example
ant -Dbuild.dir=BUILD
@end example
A sample @code{build.properties} is provided and it contains
comments explaining many of the options.

Here are a few general properties that help to customize your build:
@table @code
@item build.dir
Path to put the temporary files used for building.
@item dist.dir
Path to put the resulting jar file.
@item version.local
A suffix to add to the version label for your customized version.
@item debug
Whether (true/false) the Javac "-g" option is enabled.
@item optimize
Whether (true/false) the Javac "-O" option is enabled.
@end table

Here are some Kawa-specific ones (all @code{true}/@code{false}):
@code{with-collections}, @code{with-references}, @code{with-awt},
@code{with-swing}, @code{enable-jemacs}, and @code{enable-servlet}>
See the sample @code{build.properties} for more information on these.

If you change any of the build properties, you will generally want to do
an @samp{ant clean} before building again as the build is often not able to
notice that kind of change.  In the case of changing a directory path,
you would want to do the @code{clean} before changing the path.

A special note for NetBeans users:
For some reason the build-tools target which compiles an Ant task won't
compile with the classpath provided by NetBeans.
You may do @samp{ant build-tools} from the command line outside of NetBeans,
in which case you will not want to use the @code{clean} target as that
will delete the tool files as well.
You can use the @code{clean-build} and/or @code{clean-dist}
targets as appropriate.  Alternatively you can add @code{ant.jar} to the
@code{build-tools} classpath by copying or linking it into a @code{lib/ext}
directory in Kawa's source directory (the one containing the @code{build.xml}
file).

@subsection Using the Jikes compiler

@uref{http://oss.software.ibm.com/developerworks/opensource/jikes/project/,Jikes}
is a Java source-to-bytecode compiler that is much faster than Sun's
@code{javac}.  (Note that this only speeds up building Kawa from source, not
actually running Kawa.)
The instructions for using jikes are as above, except that you
need to specify Jikes at @code{configure} time, setting the @code{JAVAC}
environment variable.  If @code{jikes} is in your execution path, do:
@example
JAVAC=jikes ./configure
@end example

You also need to inform Jikes where it should find the standard Java classes
(since Jikes is a compiler only).  For example:
@example
CLASSPATH=.:/opt/jdk1.3/jre/lib/rt.jar
export CLASSPATH
@end example

@subsection Compiling Kawa to native code with GCJ

The GNU Compiler for the Java(tm) Programming Language
(@uref{http://gcc.gnu.org/java/,GCJ}) is part of the
GNU Compiler Collection (@uref{http://gcc.gnu.org/,GCC}).
It can compile Java source or bytecode
files into native code on supported systems.
Version 3.3 or later of GCC is recommended,
and only Intel x86-based Linux/GNU system have been tested with Kawa.

First, get and install GCC 3.3.  Set @code{PREFIX} to where
you want to install GCJ, and configure it with these options:
@example
./configure --enable-threads --enable-languages=c++,java --prefix $PREFIX
make bootstrap
make install
@end example
Make sure @code{gcj} is in your path and refers to the newly-installed
version, and if needed, set @code{LD_LIBRARY_PATH} to point to the
directory where @code{libgcj.so} was installed:
@example
PATH=$PREFIX/bin:$PATH
LD_LIBRARY_PATH=$PREFIX/lib
export LD_LIBRARY_PATH
@end example

To build Kawa, you need to specify @code{--with-gcj} to
@code{configure} which tells it to use GCJ.  Currently you also
need to specify @code{--without-awt --without-swing} because
GCJ does not yet support AWT or Swing:
@example
./configure --with-gcj --without-awt --without-swing --prefix $PREFIX
@end example
Then as before:
@example
make
make install
@end example

@subsection Building Kawa under MS-Windows

Using the @code{ant} method is recommended for building
Kawa under Microsoft Windows.
You may get an error message "@code{Out of environment space}."
See @uref{http://support.microsoft.com/support/kb/articles/Q230/2/05.ASP}
for a solution.  Alternatively you can run
the class @code{org.apache.tools.ant.Main} directly from the Ant jar.

The Kawa @code{configure} and @code{make} process assumes a Unix-like
environment.  If you want to build Kawa from source under Windows
(95, 98, or NT), you could use a Unix empulation package, such
as the free @uref{http://sources.redhat.com/cygwin/,Cygwin}.
However, there are some problems with filenames that make this
more complicated than it should be.  It should be possible
to build Kawa under Cygwin using @code{gcj} as descibed above.

@node Running, Restrictions, Installation, Top
@chapter How to start up and run Kawa

The easiest way to start up Kawa is to run the @samp{kawa} program.
This finds your java interpreter, and sets up @samp{CLASSPATH} correctly.
If you have installed Kawa such @code{$PREFIX/bin} is in your @code{$PATH},
just do:
@example
kawa
@end example
However, @samp{kawa} only works if you have a Unix-like environment.
On some platforms, @samp{kawa} is a program that uses the GNU
@samp{readline} library to provide input line editing.

To run Kawa manually, you must start a Java interpreter.
How you do this depends on the Java interpreter.
For JavaSoft's JDK, you must have the Java interpreter
in your @code{PATH}.
You must also make sure that the @code{kawa/repl.class} file,
the rest of the Kawa packages, and the standard Java
packages can be found by searching CLASSPATH.
@xref{Running Java}.

Then you do:
@example
java kawa.repl
@end example

In either case, you will then get the @samp{#|kawa:1|#} prompt,
which means you are
in the Kawa read-eval-print-loop.  If you type a Scheme
expression, Kawa will evaluate it.  Kawa will then print the
result (if there is a non-"void" result).

@menu
* Options::      Command-line arguments
* Scripts::      Running Command Scripts
* New-Window::   Running a Command Interpreter in a new Window
* Exiting::      Exiting Kawa
@end menu

@node Options, Scripts, Running, Running
@section Command-line arguments

@cindex options
You can pass various flags to Kawa, for example:
@example
kawa -e '(display (+ 12 4))(newline)'
@end example
or:
@example
java kawa.repl -e '(display (+ 12 4))(newline)'
@end example
Either causes Kawa to print @samp{16}, and then exit.

At startup, Kawa executes an init file from the user's home
directory.
The init file is named @code{.kawarc.scm} on Unix-like systems
(those for which the file separator is @code{'/'}),
and @code{kawarc.scm} on other systems.
This is done before the read-eval-print loop
or before the first @code{-f} or @code{-c} argument.  (It is not run
for a @code{-e} command, to allow you to set options to override
the defaults.)

@table @samp
@item -e @var{expr}
Kawa evaluates @var{expr}, which contains one or more Scheme expressions.
Does not cause the @code{~/.kawarc.scm} init file to be run.
@item -c @var{expr}
Same as @samp{-e @var{expr}}, except that it
does cause the @code{~/.kawarc.scm} init file to be run.
@item -f @var{filename-or-url}
Kawa reads and evaluates expressions from the file named
by @var{filename-or-url}.  If the latter is @samp{-},
standard input is read (with no prompting).  Otherwise,
it is equivalent to evaluating @samp{(load "@var{filename-or-url}")}.
The @var{filename-or-url} is interpreted as a URL
if it is absolute - it starts with a "URI scheme" like @code{http:}.
@item -s
@itemx --
The global variable @samp{command-line-arguments} is set to the remaining
arguments (if any), and an interactive read-eval-print loop is started.
This uses the same "console" as where you started up Kawa;
use @samp{-w} to get a new window.
@item -w
Creates a new top-level window, and runs an interactive read-eval-print
in the new window.  See @ref{New-Window}.
Same as @code{-e (scheme-window #t)}.
You can specify multiple @samp{-w} options, and also use @samp{-s}.
@item --help
Prints out some help.
@item --version
Prints out the Kawa version number, and then exits.
@item --server @var{portnum}
Start a server listening from connections on the specified @var{portnum}.
Each connection using the Telnet protocol causes a new read-eval-print-loop
to started.  This option allows you to connect using any
Telnet client program to a remote "Kawa server".
@item --scheme
Set the default language to Scheme.
(This is the default unless you select another language,
or you name a file with a known extension on the command-line.)
@item --elisp
@itemx --emacs
@itemx --emacs-lisp
Set the default language to Emacs Lisp.
(The implementation is quite incomplete.)
@item --lisp
@itemx --clisp
@itemx --clisp
@itemx --commonlisp
@itemx --common-lisp
Set the default language to CommonLisp.
(The implementation is @emph{very} incomplete.)
@item --krl
Set the default language to KRL.  See @ref{KRL}.
@item --brl
Set the default language to KRL, in BRL-compatibility mode.  See @ref{KRL}.
@item --xquery
Set the default language to the draft XML Query language.
See the @uref{http://www.gnu.org/software/qexo/,Kawa-XQuery page}
for more information.
@item --xslt
Set the default language to XSLT (XML Stylesheet Language Transformations).
(The implementation is @emph{very} incomplete.)
See the @uref{http://www.gnu.org/software/qexo/xslt.html,Kawa-XSLT page}
for more information.
@item --output-format @var{format}
@itemx --format @var{format}
Change the default output format to that specified by @var{format}.
See @ref{Named output formats} for more information and a list.
@end table

The following options control which calling conventions are used:
@table @samp
@item --full-tailcalls
Use a calling convention that supports proper tail recursion.
@item --no-full-tailcalls
Use a calling convention that does not support proper tail recursion.
Self-tail-recursion (i.e. a recursive call to the current function)
is still implemented correctly, assuming that the called function
is known at compile time.
@end table

The default is currently @code{--no-full-tailcalls} because I believe it is
faster (though I have not done any measurements yet).
It is also closer to the Java call model, so may be better for people
primarily interested in using Kawa for scripting Java systems.

Both calling conventions can co-exist:  Code compiled
with @code{--full-tailcalls} can call code compiled
with @code{--no-full-tailcalls} and vice versa.

The options @samp{-C}, @samp{-d}, @samp{-T}, @samp{-P}, @samp{--main}
@samp{--applet}, and @code{--servlet} are used to compile a Scheme file;
see @ref{Files compilation}.
The option @samp{--connect @var{portnum}} is only used by
the @samp{kawa} front-end program.

The following options are useful if you want to debug or understand
how Kawa works.
@table @samp
@item --debug-dump-zip
Normally, when Kawa loads a soyrce file, or evaluates a non-trivial expression,
it generates new internal Java classes but does not write them out.  This
option asks it to write out generated classes in a @samp{.zip} archive
whose name has the prefix @samp{kawa-zip-dump-}.
@item --debug-print-expr
Kawa translates source language forms into an internal @code{Expression}
data structure.  This option causes that data structure to be written out
in a readable format to the standard output.
@item --debug-print-final-expr
Similar to the previous option, but prints out the @code{Expression} after
various transformations and optimizations have been done, and just before
code generation.
@end table

If there are further command-line arguments after the options
have been processed, then the first remaining argument names a
file that is read and evaluated.  If there is no such argument,
then Kawa enters an interactive read-eval-print loop,
but only if none of the @samp{-c}, @samp{-e}, @samp{-f}, @samp{-s},
@samp{-C}, or @samp{--} options were specified.

@node Scripts, New-Window, Options, Running
@section Running Command Scripts

Unix-like systems support a mechanism where a @dfn{script} can
specify a programs that should execute it.  The convention
is that the first line of the file should start with the two characters
@samp{#!} followed by the absolute path of the program that should
process (interpret) the script.

This is convention works well for script languages that use @samp{#}
to indicate the start of a comment, since the interpreter will
automatically ignore the line specifying the interpreter filename.
Scheme, however, uses @samp{#} for various special objects,
and Kawa specifically uses @samp{#!} as a prefix for
various @ref{Special named constants} such as @code{#!optional}.

Kawa does recognize the three-character sequence @samp{#!/} at the
beginning of a file as special, and ignores it.  So you can
specify command interpreters, as long as you don't put a space
between the @samp{#!} and the interpreter filename.
Here is an example:
@example
#!/usr/local/bin/kawa
(format #t "The time is ~s~%" (make <java.util.Date>))
@end example

If this file has the execute permission set and is in your @code{PATH},
then you can execute it just my naming it on command line.  The
system kernel will automatically execute @code{kawa}, passing it the
filename as an argument.

Note that the full path-name of the @code{kawa} interpreter
must be hard-wired into the script.  This means you may have to edit
the script depending on where Kawa is installed on your system.
Another possible problem is that the interpreter must be an
actual program, not a shell script. Depending on how you configure
and install Kawa, @code{kawa} can be a real program or a script.
You can avoid both problems by the @code{env} program, available on
most modern Unix-like systems:

@example
#!/usr/bin/env kawa
(format #t "The time is ~s~%" (make <java.util.Date>))
@end example

@node New-Window, Exiting, Scripts, Running
@section Running a Command Interpreter in a new Window

An alternative interface runs the Java read-eval-print-loop
inside a new window. This is in some ways nicer.  One reason
is that it provides better editing.  You can also create
new windows.  They can either have different top-level
environments or they can share environments.  To try it, do:
@example
java kawa.repl -w
@end example

@node Exiting,  , New-Window, Running
@section Exiting Kawa
Kawa normally keeps running as long as there is an active
read-eval-print loop still awaiting input or there is an unfinished
other computation (such as requested by a @samp{-e} of @samp{-f} option).

To close a read-eval-print-loop, you can type the special
literal @code{#!eof} at top level.  This is recognized as end-of-file.
Unfortunately, due to thread-related complications, just typing
an end-of-file character (normally ctrl/D until Unix), will not work.

If the read-eval-print-loop
is in a new window, you can select @samp{Close} from the @samp{File} menu.

To exit the entire Kawa session, call the
@code{exit} procedure (with 0 or 1 integer arguments).

@node Restrictions, Compiling, Running, Top
@chapter Features of R5RS not implemented

Kawa implements all the required and optional features of R5RS,
with the following exceptions.

The entire "numeric tower" is implemented.
However, some transcendental function only work on reals.
Integral function do not necessarily work on
inexact (floating-point) integers.
(The whole idea of "inexact integer" in R5RS seems rather pointless ...)

Also, @code{call-with-current-continuation} is only "upwards" (?).
I.e. once a continuation has been exited, it cannot be invoked.
These restricted continuations can be used to implement catch/throw
(such as the examples in R4RS), but not co-routines or backtracking.

Kawa now does general tail-call elimination, but only if
you use the flag @code{--full-tail-calls}.  (Currently, the
@code{eval} function itself is not fully tail-recursive, in violation
of R5RS.)   The @code{--full-tail-calls} flag is not on by default,
partly because it is noticably slower (though I have not measured how
much), and partly I think it is more useful for Kawa to be compilatible
with standard Java calling conventions and tools.
Code compiled with @code{--full-tail-calls} can call code
 compiled without it and vice versa.

Even without @code{--full-tail-calls}, if the
compiler can prove that the procedure being called is the current
function, then the tail call will be replaced by a jump.
This means the procedure must be defined using a letrec, not a
define (because the compiler does not know if someone might
re-define a global definition), and there must be no assignments
(using @code{set!}) to the procedure binding.

@node Compiling, Extensions, Restrictions, Top
@chapter Compiling Scheme code to byte-code or an executable

All Scheme functions and source files are invisibly compiled
into internal Java byte-codes.
A traditional evaluator is only used for top-level directly entered
expressions @emph{outside} a lambda.  (It would have been simpler
to also byte-compile top-level expressions by surrounding them
by a dummy lambda.  However, this would create a new Class object
in the Java VM for every top-level expression.  This is undesirable
unless you have a VM that can garbage collect Class objects.)

To save speed when loading large Scheme source files, you probably
want to pre-compile them and save them on your local disk.
There are two ways to do this.

You can compile a Scheme source file to a single archive file.
You do this using the @code{compile-file} function.
The result is a single file that you can move around and @code{load}
just like the @code{.scm} source file.  You just specify the name
of the archive file to the @code{load} procedure.
Currently, the archive is a "zip" archive and has extension ".zip";
a future release will probably use "Java Archive" (jar) files.
The advantage of compiling to an archive is that it is simple
and transparent.  A minor disadvantage is that it causes the
Java "verifier" to be run when functions are loaded from it,
which takes a little extra time.

Alternatively, you can compile a Scheme source file to a
collection of @samp{.class} files.
You then use the standard Java class loading mechanism to load the code.
The Java "verifier" does not need to get run, which makes
loading a little faster.
The compiled class files do have to be installed be installed somewhere
in the @code{CLASSPATH}.

You can also compile your Scheme program to native code using GCJ.

@menu
* Archive compilation::         Compiling Scheme to an archive file
* Files compilation::           Compiling Scheme to a set of .class files
* Compilation options::
* Application compilation::     Compiling Scheme to a standalone application
* Applet compilation::          Compiling Scheme to an applet
* Compiling to executable::     Compiling Scheme to a native executable
@end menu

@node Archive compilation, Files compilation, Compiling, Compiling
@section Compiling Scheme to an archive file

@defun compile-file source-file compiled-archive
Compile the @var{source-file}, producing a @code{.zip} archive
@var{compiled-file}.


For example, to byte-compile a file @samp{foo.scm} do:
@example
(compile-file "foo.scm" "foo")
@end example

This will create @samp{foo.zip}, which contains byte-compiled "j-code".
You can move this file around, without worrying about class paths.
To load the compiled file, you can later @code{load} the
named file, as in either @code{(load "foo")} or @code{(load "foo.zip")}.
This should have the same effect as
loading @samp{foo.scm}, except you will get the faster byte-compiled versions.
@end defun

@node Files compilation
@section Compiling Scheme to a set of .class files

Invoking @samp{kawa} (or @samp{java kawa.repl}) with
the @samp{-C} flag will compile
a @samp{.scm} source file into one or more @samp{.class} files:
@example
kawa --main -C myprog.scm
@end example

You run it as follows:
@example
kawa [-d @var{outdirectory}] [-P @var{prefix}] [-T @var{topname}] [--main | --applet | --servlet] -C @var{infile} ...
@end example

Note the @samp{-C} must come last, because @samp{Kawa} processes the
arguments and options in order,

Here:
@table @samp
@item -C @var{infile} ...
The Scheme source files we want to compile.
@item -d @var{outdirectory}
The directory under which the resulting @samp{.class} files will be.
The default is the current directory.
@item -P @var{prefix}
A string to prepend to the generated class names.
The default is the empty string.
@item -T @var{topname}
The name of the "top" class - i.e. the one that contains the code
for the top-level expressions and definitions.
The default is generated from the @var{infile} and @var{prefix}.
@item --main
Generate a @code{main} method so that the resulting "top" class can
be used as a stand-alone application. @xref{Application compilation}.
@item --applet
The resulting class inherits from @code{java.applet.Applet},
and can be used as an applet.  @xref{Applet compilation}.
@item --servlet
The resulting class implements @code{javax.servlet.http.HttpServlet},
and can be used as an servlet in a servlet container like Tomcat.
@end table

When you actually want to load the classes, the @var{outdirectory}
must be in your @samp{CLASSPATH}.
You can use the standard @code{load} function to load the code,
by specifying the top-level class, either as a file name
(relative to @var{outdirectory}) or a class name.
E.g. if you did:
@example
kawa -d /usr/local/share/java -P my.lib. -T foo -C foosrc.scm
@end example
you can use either:
@example
(load "my.lib.foo")
@end example
or:
@example
(load "my/lib/foo.class")
@end example

If you are compiling a Scheme source file (say @samp{foosrc.scm})
that uses macros defined in some other file (say @samp{macs.scm}),
you need to make sure the definitions are visible to the compiler.
One way to do that is with the @samp{-f}:
@example
kawa -f macs.scm -C foosrc.scm
@end example

@node Compilation options
@section Compilation options

Various named option control how Kawa compiles certain forms.

@table @samp
@item --module-static
If no @code{module-static} is specified, generate a static module
(as if @code{(module-static #t)} were specified). @xref{Module classes}.
@item --warn-invoke-unknown-method
Emit a warning if the @code{invoke} function calls a named method
for which there is no matching method in the compile-time type of the receiver.
This (currently) defaults to on;
to turn it off use the @code{--no-warn-invoke-unknown-method} flag.
@item --warn-undefined-variable
Emit a warning if the code references a variable which is neither in
lexical scope nor in the compile-time dynamic (global) environment.
This is useful for catching typos.
(A @code{define-variable} form can be used to silence warnings.
It declares to the compiler that a variable is to be resolved dynamically.)
@end table

An option can be followed by a value, as
in @code{--warn-invoke-unknown-method=no}.
For boolean options, the values @code{yes}, @code{true}, @code{on}, or @code{1}
enable the option, while @code{no}, @code{false}, @code{off},
or @code{0} disable it.
You can also negate an option by prefixing it with @code{no-}:
The option @code{--no-warn-invoke-unknown-method}
is the same as @code{--warn-invoke-unknown-method=no}.

You can set the same options (except, for now, @code{module-static})
within your Scheme source file.  (In that case they override the
options on the command line.)

@deffn Syntax module-compile-options [key: value] ...
This sets the value of the @code{key} option to @code{value}
for the current module (source file).  It takes effect as
soon it is seen during the first macro-expansion pass,
and is active thereafter (unless overridden by @code{with-compile-options}).

The @var{key} is one of the above option names.
(The following colon make it a Kawa keyword.)
The @var{value} must be a literal value: either a boolean
(@code{#t} or @code{#f}), a number, or a string,
depending on the @var{key}.
(All the options so far are boolean options.)

@example
(module-compile-options warn-undefined-variable: #t)
;; This causes a warning message that y is unknown.
(define (func x) (list x y))
@end example
@end deffn

@deffn Syntax with-compile-options [key: value] ... body
Similar to @code{module-compile-options}, but the option
is only active within @var{body}.
@example
(define (func x)
  (with-compile-options warn-invoke-unknown-method: #f
    (invoke x 'size)))
@end example
@end deffn

@node Application compilation
@section Compiling Scheme to a standalone application

A Java application is a Java class with a special method
(whose name is @code{main}).  The application can be invoked directly
by naming it in the Java command.
If you want to generate an application from a Scheme program,
create a Scheme source file with the definitions you need, plus
the top-level actions that you want the application to execute.
You can compile in the regular way decribed in the previous section, but add
the @code{--main} option.  For example,
assuming your Scheme file is @code{MyProgram.scm}:
@example
kawa --main -C MyProgram.scm
@end example
This will create a @code{MyProgram.class} which you can either @code{load}
(as decribed in the previous section), or invoke as an application:
@example
java MyProgram [@var{args}]
@end example
Your Scheme program can access the command-line arguments @var{args}
by using the global variable @samp{command-line-arguments}.

@node Applet compilation, Compiling to executable, Application compilation, Compiling
@section Compiling Scheme to an applet
An applet is a Java class that inherits from @code{java.applet.Applet}.
The applet can be downloaded and run in a Java-capable web-browser.
To generate an applet from a Scheme program, write the Scheme
program with appropriate definitions of the functions @samp{init},
@samp{start}, @samp{stop} and @samp{destroy}.  You must declare these
as zero-argument functions with a @code{<void>} return-type.

Here is an example, based on the scribble applet in Flanagan's
"Java Examples in a Nutshell" (O'Reilly, 1997):
@example
(define-private last-x 0)
(define-private last-y 0)

(define (init) <void>
  (let ((applet :: <java.applet.Applet> (this)))
    (invoke applet 'addMouseListener
	    (object (<java.awt.event.MouseAdapter>)
		    ((mousePressed (e :: <java.awt.event.MouseEvent>)) <void>
		     (set! last-x (invoke e 'getX))
		     (set! last-y (invoke e 'getY)))))
    (invoke applet 'addMouseMotionListener
	    (object (<java.awt.event.MouseMotionAdapter>)
		    ((mouseDragged (e :: <java.awt.event.MouseEvent>)) <void>
		     (let ((g :: <java.awt.Graphics>
			      (invoke applet 'getGraphics))
			   (x :: <int> (invoke e 'getX))
			   (y :: <int> (invoke e 'getY)))
		       (invoke g 'drawLine last-x last-y x y)
		       (set! last-x x)
		       (set! last-y y)))))))

(define (start) <void> (format #t "called start.~%~!"))
(define (stop) <void> (format #t "called stop.~%~!"))
(define (destroy) <void> (format #t "called destroy.~%~!"))
@end example

You compile the program with the @samp{--applet} flag in addition to the
normal @samp{-C} flag:
@example
java kawa.repl --applet -C scribble.scm
@end example

You can then create a @samp{.jar} archive containing your applet.
You also need to include the Kawa classes in the @samp{.jar},
or you can include a @code{MANIFEST} file that specifies @code{Class-Path}
to use a Java 2
@uref{http://java.sun.com/docs/books/tutorial/ext/basics/download.html,
download extension}.
@example
jar cf scribble.jar scribble*.class @i{other-classes ...}
@end example

Finally, you create an @samp{.html} page referencing your applet:
@example
<html><head><title>Scribble testapp</title></head>
<body><h1>Scribble testapp</h1>
You can scribble here:
<br>
<applet code="scribble.class" archive="scribble.jar" width=200 height=200>
Sorry, Java is needed.</applet>
</body></html>
@end example

@node Compiling to executable, , Applet compilation, Compiling
@section Compiling Scheme to a native executable

You can compile your Scheme program to native code using GCJ,
as long as you have built Kawa using GCJ.

First, you need to compile the Scheme code to a set of @code{.class} files;
see @ref{Files compilation}.
@example
kawa --main -C myprog.scm
@end example

Then to create an executable @code{myprog} do:
@example
gckawa --main=myprog myprog*.class -o myprog
@end example

The @code{gckawa} is a simple shell script that calls @code{gcj}.
The reason for the wildcard in @code{myprog*.class} is that sometimes
Kawa will generate some helper classes in addition to @code{myprog.class}.
The @code{--main} option tell @code{gcj} which class contains
the @code{main} method it should use.  The @code{-o} option names
the resulting executable program.  The @code{-lkawa} option tells
the linker it should link with the kawa shared library, and
the @code{-L$PREFIX/bin} option tells the linker where it can
find that library.

@node Extensions, Input-Output, Compiling, Top
@chapter Extensions

@menu
* Syntax and conditional compilation::
* Multiple values::
* Special named constants::
* Keywords::
* Procedures::
* Quantities::  Quantities and Numbers
* Logical Number Operations::
* Lists::
* Strings::
* Arrays::  Multi-dimensional Arrays
* Uniform vectors::
* Exceptions:: Signalling and recovering from exceptions
* Locations::
* Eval and Environments::
* Debugging::
* Threads::
* Processes::
* Miscellaneous::
@end menu

@node Syntax and conditional compilation, Multiple values, Extensions, Extensions
@section Syntax and conditional compilation

@deffn Syntax define-syntax ..
Pattern ...
@end deffn

@deffn Syntax defmacro name lambda-list form ...
Defines an old-style macro a la Common Lisp,
and installs @code{(lambda @var{lambda-list} @var{form} ...)}
as the expansion function for @var{name}.
When the translator sees an application of @var{name},
the expansion function is called with the rest of the application
as the actual arguments.  The resulting object must be a Scheme
source form that is futher processed (it may be repeatedly macro-expanded).

If you define a macro with @code{defmacro}, you (currently) cannot use
the macro in the same compilation as the definition.
This restriction does not apply to macros defined by @code{define-syntax}.
@end deffn

@defun gentemp
Returns a new (interned) symbol each time it is called.
The symbol names are implementation-dependent.
(This is not directly macro-related, but is often used in conjunction
with @code{defmacro} to get a fresh unique identifier.)
@end defun

@deffn Syntax cond-expand cond-expand-clause* [(else command-or-definition*)]
@display
@var{cond-expand-clause} ::= @code{(@var{feature-requirement} @var{command-or-definition}*)}
@var{feature-requirement} ::= @var{feature-identifier}
  | @code{(and @var{feature-requirement}*)}
  | @code{(or @var{feature-requirement}*)}
  | @code{(not @var{feature-requirement})}
@var{feature-identifier} ::= a symbol which is the name or alias of a SRFI
@end display

The @code{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 an error during syntactic
processing. @code{cond-expand} expands into the body of the first clause
whose feature requirement is currently satisfied; the @code{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 @var{feature-identifier} variables have meaning true if @c 
the feature corresponding to the feature identifier, as specified in the
SRFI registry, is in effect at the location of the @code{cond-expand} form, and
false otherwise. A feature requirement is satisfied if its formula is
true under this interpretation.

Examples:
@example
(cond-expand
    ((and srfi-1 srfi-10)
     (write 1))
    ((or srfi-1 srfi-10)
     (write 2))
    (else))
@end example

@example
(cond-expand
  (command-line
   (define (program-name) (car (argv)))))
@end example

The second example assumes that @code{command-line} is an alias for some
feature which gives access to command line arguments. Note that an error
will be signaled at macro-expansion time if this feature is not present.
@end deffn

@node Multiple values, Special named constants, Syntax and conditional compilation, Extensions
@section Multiple values

The multiple-value feature was added in R5RS.

@defun values object ...
Delivers all of its arguments to its continuation.
@end defun

@defun call-with-values thunk receiver
Call its @var{thunk} argument with a continuation that,
when passed some values, calls the @var{receiver} procedure
with those values as arguments.
@end defun

@deffn Syntax let-values ((formals expression) ...) body
Each @var{formals} should be a formal arguments list as for a @code{lambda},
cf section 4.1.4 of the R5RS.

The @var{expression}s are evaluated in the current environment, the
variables of the @var{formals} are bound to fresh locations, the return
values of the @var{expression}s are stored in the variables, the
@var{body} is evaluated in the extended environment, and the values of
the last expression of @var{body} are returned. The @var{body} is a
"tail body", cf section 3.5 of the R5RS.

The matching of each @var{formals} to values is as for the matching of
@var{formals} to arguments in a @code{lambda} expression, and it is an
error for an @var{expression} to return a number of values that does not
match its corresponding @var{formals}.
@example
(let-values ((a b . c) (values 1 2 3 4)))
  (list a b c))            --> (1 2 (3 4)) 

(let ((a 'a) (b 'b) (x 'x) (y 'y))
  (let-values (((a b) (values x y))
               ((x y) (values a b)))
    (list a b x y)))       --> (x y a b)
@end example
@end deffn

@deffn Syntax let*-values ((formals expression) ...) body

Each @var{formals} should be a formal arguments list as for a
@code{lambda} expression, cf section 4.1.4 of the R5RS.

@code{let*-values} is similar to @code{let-values}, but the bindings are
performed sequentially from left to right, and the region of a binding
indicated by (@var{formals} @var{expression}) is that part of the
@code{let*-values} expression to the right of the binding. Thus the
second binding is done in an environment in which the first binding is
visible, and so on.
@example
(let ((a 'a) (b 'b) (x 'x) (y 'y))
  (let*-values (((a b) (values x y))
                ((x y) (values a b)))
    (list a b x y)))       --> (x y x y)
@end example
@end deffn

@deffn Syntax receive formals expression body
The @var{formals}, @var{expression}, and @var{body} are as described in R5RS.
Specifically, @var{formals} can have any of three forms:
@table @samp
@item (@var{variable1} ... @var{variablen})
The environment in which the receive-expression is evaluated is extended
by binding @var{variable1}, ..., @var{variablen} to fresh locations. The
@var{expression} is evaluated, and its values are stored into those
locations. (It is an error if @var{expression} does not have exactly @var{n}
values.)
@item @var{variable}
The environment in which the receive-expression is evaluated is extended
by binding @var{variable} to a fresh location. The @var{expression} is
evaluated, its values are converted into a newly allocated list, and the
list is stored in the location bound to @var{variable}.
@item (@var{variable1} ... @var{variablen} . @var{variablen+1})
The environment in which the receive-expression is evaluated is extended
by binding @var{variable1}, ..., @var{variablen+1} to fresh
locations. The @var{expression} is evaluated. Its first @var{n} values
are stored into the locations bound to @var{variable1}
... @var{variablen}. Any remaining values are converted into a newly
allocated list, which is stored into the location bound to
@var{variablen+1} (It is an error if @var{expression} does not have at
least @var{n} values.)
@end table

In any case, the expressions in @var{body} are evaluated sequentially in the
extended environment. The results of the last expression in the body are
the values of the receive-expression.
@end deffn

@defun values-append arg1 ...
The values resulting from evaluating each argument are appended
together.
@end defun

@node Special named constants, Keywords, Multiple values, Extensions
@section Special named constants

@defvr Constant #!optional
Special self-evaluating literal used in lambda parameter lists
before optional parameters.
@end defvr

@defvr Constant #!rest
Special self-evaluating literal used in lambda parameter lists
before the rest parameter.
@end defvr

@defvr Constant #!key
Special self-evaluating literal used in lambda parameter lists
before keyword parameters.
@end defvr

@defvr Constant #!eof
The end-of-file object.

Note that if the Scheme reader sees this literal at top-level,
it is returned literally.  This is indistinguishable from
coming to the end of the input file.  If you do not want to end reading,
but want the actual value of @code{#!eof}, you should quote it.
@end defvr

@defvr Constant #!void
The void value.  Same as @code{(values)}.
If this is the value of an expression in a read-eval-print loop,
nothing is printed.
@end defvr

@defvr Constant #!null
The Java @code{null} value.  This is not really a Scheme value,
but is useful when interfacing to low-level Java code.
@end defvr

@node Keywords, Procedures, Special named constants, Extensions
@section Keywords

Keywords are similar to symbols.  The main difference is that keywords are
self-evaluating and therefore do not need to be quoted in expressions.
They are used mainly for specifying keyword arguments.

@display
@var{keyword} ::= @var{identifier}:
@end display

An alternative syntax, with the colon first, is supported for
compatibility with Common Lisp and some other Scheme implementations:

@display
@var{keyword} ::= :@var{identifier}
@end display

Putting the colon first has exactly the same effect as putting it last;
putting is last is recommended, and is how keywords are printed.

A keyword is a single token; therefore no whitespace is allowed between
the @var{identifier} and the colon (which is not considered part
of the name of the keyword).

@defun keyword? obj
Return @code{#t} if @var{obj} is a keyword, and otherwise returns @code{#f}.
@end defun

@defun keyword->string keyword
Returns the name of @var{keyword} as a string.
The name does not include the final @code{#\:}.
@end defun

@defun string->keyword string
Returns the keyword whose name is @var{string}.
(The @var{string} does not include a final @code{#\:}.)
@end defun

@node Procedures, Quantities, Keywords, Extensions
@section Procedures

@defun apply proc [arg1 ...] args
@var{Args} must be a sequence (list, vector, or string) or a
primitive Java array.
(This is an extension over standard Scheme, which requires that
@var{args} be a list.)
Calls the @var{proc} (which must be a procedure), using as arguments
the @var{arg1}... values plus all the elements of @var{args}.
@end defun

@deffn Syntax constant-fold proc arg1 ...
Same as @code{(@var{proc} @var{arg1} ...)}, unless @var{proc} and
all the following arguments are compile-time constants.
(That is:  They are either constant, or symbols that have a global
binding and no lexical binding.)  In that case, @var{proc}
is applied to the arguments at compile-time, and the result replaces
the @code{constant-fold} form.  If the application raises an exception,
a compile-time error is reported.
For example:
@example
(constant-fold vector 'a 'b 'c)
@end example
is equivalent to @code{(quote #(a b c))}, assuming @code{vector}
has not been re-bound.
@end deffn

@subsection Procedure properties

You can associate arbitrary @dfn{properties} with any procedure.
Each property is a (@var{key}, @var{value})-pair.  Usually the
@var{key} is a symbol, but it can be any object.

The system uses certain internal properties:
@code{'name} refers to the name used when a procedure is printed;
@code{'emacs-interactive} is used to implement Emacs @code{interactive}
specification;
@code{'setter} is used to associate a @code{setter} prcedure.

@defun procedure-property proc key [default]
Get the property value corresponding to the given @var{key}.
If @var{proc} has no property with the given @var{key},
return @var{default} (which defaults to @code{#f}) instead.
@end defun

@defun set-procedure-property! proc key value
Associate the given @var{value} with the @var{key} property of @var{proc}.
@end defun

To change the print name of the standard @code{+} procedure (probably
not a good idea!), you could do:
@example
(set-procedure-property! + 'name 'PLUS)
@end example
Note this @emph{only} changes the name property used for printing:
@example
+ => #<procedure PLUS>
(+ 2 3) => 5
(PLUS 3 4) => ERROR
@end example

As a matter of style, it is cleaner to use the @code{define-procedure}
form, as it is a more declarative interface.

@deffn Syntax define-procedure name [propname: propvalue] ... method ...
Defines @var{name} as a compound procedure consisting of the
specified @var{method}s, with the associated properties.
Applying @var{name} select the "best" @var{method}, and applies that.
See the following section on generic procedures.

For example, the standard @code{vector-ref} procedure specifies
one method, as well as the @code{setter} property:
@example
(define-procedure vector-ref
  setter: vector-set!
  (lambda ((vector :: <vector>) (k :: <int>))
    (invoke vector 'get k)))
@end example
@end deffn

@subsection Generic (dynamically overloaded) procedures

A @dfn{generic procedure} is a collection of @dfn{method procedures}.
(A "method procedure" is not the same as a Java method, but
the terms are related.)
You can call a generic procedure, which selects the "closest
match" among the component method procedures:  I.e. the most specific
method procedure that is applicable given the actual arguments.

@quotation
@strong{Note:} The current implementation of selecting the "best" method
is not reliable if there is more than one method.
It can select depending on argument count, and it can select between
primitive Java methods.  However, it cannot yet do what you probably
hope for: select between different Scheme procedures based on
parameter types.
@end quotation

@defun make-procedure [keyword: value]... method...
Create a generic procedure given the specific methods.
You can also specify property values for the result.

The @var{keyword}s specify how the arguments are used.
A @code{method:} keyword is optional and specifies that the following
argument is a method.
A @code{name:} keyword specifies the name of the resulting procedure,
when used for printing.
Unrecognized keywords are used to set the procedure properties of the result.
@example
(define plus10 (make-procedure foo: 33 name: 'Plus10
                            method: (lambda (x y) (+ x y 10))
                            method: (lambda () 10)))
@end example
@end defun

@subsection Extended Formal Arguments List

The formal arguments list of a lambda expression has two
extendsions over standard Scheme:
Kawa borrows the extended formal argument list of DSSSL,
and Kawa allows you to declare the type of the parameter.

@display
@var{lambda-expression} ::= (lambda @var{formals} [@var{rtype}] @var{body})
@end display
where
@display
@var{formals} ::= (@var{formal-arguments}) | @var{rest-arg}
@end display
You can of course also use the extended format in a @code{define}:
@display
(define (@var{name} @var{formal-arguments}) [@var{rtype}] @var{body})
@end display
@display
@var{formal-arguments} ::=
    @var{req-opt-args} (@var{rest-key-args} | . @var{rest-arg})
@end display
@display
@var{req-opt-args} ::= @var{req-arg} ... [#!optional @var{opt-arg} ...]
@var{rest-key-args} ::= [#!rest @var{rest-arg}] [#!key @var{key-arg} ...]
@var{req-arg} ::= @var{variable} [:: @var{type}] | (@var{variable} [[::] @var{type}] )
@var{opt-arg} ::= @var{arg-with-default}
@var{key-arg} ::=  @var{arg-with-default}
@var{arg-with-default} ::= @var{variable} [:: @var{type}]
    | ( @var{variable} [:: @var{type} [@var{initializer}] | @var{initializer} [[::] @var{type}]] )
@var{rest-arg} ::= @var{variable}
@end display

When the procedure is applied to a list of actual arguments, the formal and
actual arguments are processed from left to right as follows:

@itemize @bullet
@item
The @var{req-arg}s are bound to actual arguments starting with the
first actual argument.  It shall be an error if there are fewer actual
arguments then there are @var{req-arg}s.
@item
Next the @var{opt-arg}s are bound to remaining actual arguemnts.
If there are fewer remaining actual arguments than there are
@var{opt-arg}s, then the remaining @var{variable}s are bound
to the corresponding @var{initializer}, if one was specified, and
otherwise to @code{#f}.  The @var{initializer} is evaluated in an
environment in which all the previous formal parameters have been bound.
@item
If there is a @var{rest-arg}, it is bound to a list of all the
remaining actual arguments.  These remaining actual arguments are also
eligible to be bound to keyword arguments.   If there is no
@var{rest-arg} and there are no @var{key-arg}s, then it shall
be an error if there are any remaining actual arguments.
@item
If @code{#!key} was specified, then 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 @var{key-arg}s, unless there
is a @var{rest-arg}.  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 @var{key-arg},
then the variable is bound
to the corresponding @var{initializer}, if one was specified, and
otherwise to @code{#f}.  The @var{initializer} is evaluated in an
environment in which all the previous formal parameters have been bound.
@end itemize

If a @var{type} is specified, the corresponding actual argument (or
the @var{initializer} default value) is coerced to the specified @var{type}.
In the function body, the parameter has the specified type.

If @var{rtype} (the first form of the function body) is an unbound
identifier of the form @code{<TYPE>} (that is the first character
is @samp{<} and the last is @samp{>}), then tha specifies the
functions return type.  It is syntactic sugar for
@code{(as <TYPE> (begin BODY))}.

@deffn Syntax cut slot-or-expr slot-or-expr* [@code{<...>}]
where each @var{slot-or-expr} is either an @var{expression} or
the literal symbol @code{<>}.

It is frequently necessary to specialize some of the parameters of a
multi-parameter procedure. For example, from the binary operation @code{cons}
one might want to obtain the unary operation
@code{(lambda (x) (cons 1 x))}.
This specialization of parameters is also known
as @dfn{partial application}, @dfn{operator section}, or @dfn{projection}.
The macro @code{cut} specializes some of the parameters of its first
argument. The parameters that are to show up as formal variables of the
result are indicated by the symbol @code{<>}, pronouced as "slot".
In addition, the symbol @code{<...>}, pronounced as "rest-slot", matches all
residual arguments of a variable argument procedure.

A @code{cut}-expression is transformed into
a @var{lambda expression} with as many formal variables as there are
slots in the list @var{slot-or-expr}*.
The body of the resulting @var{lambda expression} calls
the first @var{slot-or-expr} with arguments from the @var{slot-or-expr}* list
in the order they appear. In case there is a rest-slot symbol, the resulting
procedure is also of variable arity, and the body calls the first
@var{slot-or-expr} with remaining arguments provided to the actual call of the
specialized procedure.

Here are some examples:@*
@code{(cut cons (+ a 1) <>)} is the same as @w{@code{(lambda (x2) (cons (+ a 1) x2))}}@*
@code{(cut list 1 <> 3 <> 5)} is the same as @w{@code{(lambda (x2 x4) (list 1 x2 3 x4 5))}}@*
@code{(cut list)} is the same as @w{@code{(lambda () (list))}}@*
@code{(cut list 1 <> 3 <...>)} is the same as @w{@code{(lambda (x2 . xs) (apply list 1 x2 3 xs))}}

The first argument can also be a slot, as one should expect in Scheme:@*
@code{(cut <> a b)} is the same as @w{@code{(lambda (f) (f a b))}}
@end deffn

@deffn Syntax cute slot-or-expr slot-or-expr* [@code{<...>}]
The macro @code{cute} (a mnemonic for "cut with evaluated non-slots") is
similar to @code{cut}, but it evaluates the non-slot expressions at the
time the procedure is specialized, not at the time the specialized
procedure is called.

For example:@*
@code{(cute cons (+ a 1) <>)} is the same as
@w{@code{(let ((a1 (+ a 1))) (lambda (x2) (cons a1 x2)))}}

As you see from comparing this example with the first example above, the
@code{cute}-variant will evaluate @code{(+ a 1)} once,
while the @code{cut}-variant will
evaluate it during every invocation of the resulting procedure.

@end deffn

@node Quantities, Logical Number Operations, Procedures, Extensions
@section Quantities and Numbers

As a super-class of numbers, Kawa also provides quantities.
A @dfn{quantity} is a product of a @dfn{unit} and a pure number.
The number part can be an arbitrary complex number.
The unit is a product of integer powers of base units,
such as meter or second.

Kawa quantities are a generalization of the quantities in DSSSL,
which only has length-derived quantities.

The precise syntax of quantity literals may change,
but some examples are @code{10pt} (10 points), @code{5s} (5 seconds),
and @code{4cm^2} (4 square centimeters).

@defun quantity? object
True iff @var{object} is a quantity.  Note that all numbers are
quantities, but not the other way round.
Currently, there are no quantities that re not numbers.
To distinguish a plain unit-less number from a quantity,
you can use @code{complex?}.
@end defun

@defun quantity->number q
Returns the pure number part of the quantity @var{q}, relative to
primitive (base) units.
If @var{q} is a number, returns @var{q}.
If @var{q} is a unit, yields the magitude of @var{q} relative to base units.
@end defun

@defun quantity->unit q
Returns the unit of the quantity @var{q}.
If @var{q} is a number, returns the empty unit.
@end defun

@defun make-quantity x unit
Returns the product of @var{x} (a pure number) and @var{unit}.
You can specify a string instead of @var{unit}, such as @code{"cm"}
or @code{"s"} (seconds).
@end defun

@deffn Syntax define-base-unit unit-name dimension
Define @var{unit-name} as a base (primitive) unit,
which is used to measure along the specified @var{dimension}.
@example
(define-base-unit dollar "Money")
@end example
@end deffn

@deffn Syntax define-unit unit-name expression
Define @var{unit-name} as a unit (that can be used in literals)
equal to the quantity @var{expression}.
@example
(define-unit cent 0.01dollar)
@end example
@end deffn

@defun quotient x y
Generalized to arbitrary real numbers, using the definition:
@code{(truncate (/ x y))}.
@end defun

@defun remainder x y
Generalized to arbitrary real numbers, using the definition:
@code{(- x (* y (truncate (/ x y))))}.
If @code{y} is @code{0}, the result is @code{x} - i.e. we take
@code{(* 0 (quotient x 0))} to be @code{0}.
The result is inexact if either argument is inexact,
even if @code{x} is exact and @code{y} is 0.
@end defun

@defun modulo x y
Generalized to arbitrary real numbers, using the definition:
@code{(- x (* y (floor (/ x y))))}.
If @code{y} is @code{0}, the result is @code{x}.
The result is inexact if either argument is inexact,
even if @code{x} is exact and @code{y} is 0.
@end defun

@node Logical Number Operations, Lists, Quantities, Extensions
@section Logical Number Operations

These functions operate on the 2's complement binary representation
of an exact integer.

@defun logand i ...
Returns the bit-wise logical "and" of the arguments.
If no argument is given, the result is -1.
@end defun

@defun logior i ...
Returns the bit-wise logical "(inclusive) or" of the arguments.
If no argument is given, the result is 0.
@end defun

@defun logxor i ...
Returns the bit-wise logical "exclusive or" of the arguments.
If no argument is given, the result is 0.
@end defun

@defun lognot i
Returns the bit-wise logical inverse of the argument.
@end defun

@defun logop op x y
Perform one of the 16 bitwise operations of @var{x} and @var{y},
depending on @var{op}.
@end defun

@defun logtest i j
Returns true if the arguments have any bits in common.
Same as @code{(not (zero? (logand @var{i} @var{j})))},
but is more efficient.
@end defun

@defun logbit? i pos
Returns @code{#t} iff the bit numbered @var{pos} in @var{i} is one.
@end defun

@defun arithmetic-shift i j
Shifts @var{i} by @var{j}.
It is a "left" shift if @code{@var{j}>0}, and
a "right" shift if @code{@var{j}<0}.

The result is equal to @code{(floor (* @var{i} (expt 2 @var{j})))}.
@end defun

@defun ash i j
Alias for @code{arithmetic-shift}.
@end defun

@defun logcount i
Count the number of 1-bits in @var{i}, if it is non-negative.
If @var{i} is negative, count number of 0-bits.
@end defun

@defun integer-length i
Return number of bits needed to represent @var{i} in an unsigned field.
Regardless of the sign of @var{i}, return one less than the number of bits
needed for a field that can represent @var{i} as a two's complement integer.
@end defun

@defun bit-extract n start end
Return the integer formed from the (unsigned) bit-field
starting at @var{start} and ending just before @var{end}.
Same as @code{(arithmetic-shift (bitand n (bitnot (arithmetic-shift -1 end))) (- start))}.
@end defun

@node Lists, Strings, Logical Number Operations, Extensions
@section Lists

The @uref{http://srfi.schemers.org/srfi-1/srfi-1.html, SRFI-1 List Library}
is available, though not enabled by default.  To use its functions you
must @code{(require 'list-lib)} or @code{(require 'srfi-1)}.
@example
(require 'list-lib)
(iota 5 0 -0.5) ;; => (0.0 -0.5 -1.0 -1.5 -2.0)
@end example

@defun reverse! list
The result is a list consisting of the elements of @var{list} in reverse order.
No new pairs are allocated, instead the pairs of @var{list} are re-used,
with @code{cdr} cells of @var{list} reversed in place.  Note that if @var{list}
was pair, it becomes the last pair of the reversed result.
@end defun

@node Strings, Arrays, Lists, Extensions
@section Strings

@defun string-upcase str
Return a new string where the letters in @var{str} are replaced
by their upper-case equivalents.
@end defun

@defun string-downcase str
Return a new string where the letters in @var{str} are replaced
by their lower-case equivalents.
@end defun

@defun string-capitalize str
Return a new string where the letters in @var{str} that start a new word
are replaced by their title-case equivalents, while non-initial letters
are replaced by their lower-case equivalents.
@end defun

@defun string-upcase! str
Destructively modify @var{str}, replacing the letters
by their upper-case equivalents.
@end defun

@defun string-downcase! str
Destructively modify @var{str}, replacing the letters
by their upper-lower equivalents.
@end defun

@defun string-capitalize! str
Destructively modify @var{str}, such that the letters that start a new word
are replaced by their title-case equivalents, while non-initial letters
are replaced by their lower-case equivalents.
@end defun

@node Arrays, Uniform vectors, Strings, Extensions
@section Multi-dimensional Arrays

Arrays are heterogeneous data structures whose elements are indexed by
integer sequences of fixed length.  The length of a valid index sequence
is the rank or the number of dimensions of an array. The shape of an
array consists of bounds for each index.

The lower bound @var{b} and the upper bound @var{e} of a dimension are
exact integers with @code{(<= @var{b} @var{e})}. A valid index along the
dimension is an exact integer @var{k} that satisfies both
@code{(<= @var{b} @var{k})} and @code{(< @var{k} @var{e})}.
The length of the array along the dimension is the difference
@code{(- @var{e} @var{b})}.
The size of an array is the product of the lengths of its dimensions.

A shape is specified as an even number of exact integers. These are
alternately the lower and upper bounds for the dimensions of an array.

@defun array? obj
Returns @code{#t} if @var{obj} is an array, otherwise returns @code{#f}.
@end defun

@defun shape bound ...
Returns a shape. The sequence @var{bound} ... must consist of an even number
of exact integers that are pairwise not decreasing. Each pair gives the
lower and upper bound of a dimension.
If the shape is used to specify the dimensions of an array
and @var{bound} ... is the sequence @var{b0} @var{e0} ... @var{bk} @var{ek}
... of @var{n} pairs of bounds, then a valid index to the array is any
sequence @var{j0} ... @var{jk} ... of @var{n} exact integers where
each @var{jk} satisfies @code{(<= @var{bk} @var{jk})}
and @code{(< @var{jk} @var{ek})}.

The shape of a @var{d}-dimensional array is a @var{d} × 2 array
where the element at @var{k 0} contains the lower bound for an index along
dimension @var{k} and the element at @var{k 1} contains the
corresponding upper bound, where @var{k} satisfies @code{(<=  0 @var{k})}
and @code{(< @var{k} @var{d})}.
@end defun

@defun make-array shape
@defunx make-array shape obj
Returns a newly allocated array whose shape is given by@var{ shape}.
If @var{obj} is provided, then each element is initialized to it.
Otherwise the initial contents of each element is unspecified.
The array does not retain a reference to @var{shape}.
@end defun

@defun array shape obj ...
Returns a new array whose shape is given by @var{shape} and the initial
contents of the elements are @var{obj} ... in row major order. The array does
not retain a reference to @var{shape}.
@end defun

@defun array-rank array
Returns the number of dimensions of @var{array}.
@example
(array-rank
  (make-array (shape 1 2 3 4)))
@end example
Returns 2.
@end defun

@defun array-start array k
Returns the lower bound for the index along dimension @var{k}.
@end defun

@defun array-end array k
Returns the upper bound for the index along dimension @var{k}.
@end defun

@defun array-ref array k ...
@defunx array-ref array index
Returns the contents of the element of @var{array} at index @var{k} ....
The sequence @var{k} ... must be a valid index to @var{array}.
In the second form, @var{index} must be either a vector or a
0-based 1-dimensional array containing @var{k} ....
@example
(array-ref (array (shape 0 2 0 3)
              'uno 'dos 'tres
              'cuatro 'cinco 'seis)
   1 0)
@end example
Returns @code{cuatro}.
@example
(let ((a (array (shape 4 7 1 2) 3 1 4)))
   (list (array-ref a 4 1)
         (array-ref a (vector 5 1))
         (array-ref a (array (shape 0 2)
                         6 1))))
@end example
Returns @code{(3 1 4)}.
@end defun

@defun array-set! array k ... obj
@defunx array-set! array index obj
Stores @var{obj} in the element of @var{array} at index @var{k} ....
Returns the void value.
The sequence @var{k} ... must be a valid index to @var{array}.
In the second form, @var{index} must be either a vector or a
0-based 1-dimensional array containing @var{k} ....

@example
(let ((a (make-array
            (shape 4 5 4 5 4 5))))
   (array-set! a 4 4 4 "huuhkaja")
   (array-ref a 4 4 4))
@end example
Returns @code{"huuhkaja"}.
@end defun

@defun share-array array shape proc
Returns a new array of @var{shape} shape that shares elements of @var{array}
through @var{proc}. The procedure @var{proc} must implement an affine
function that returns indices of @var{array} when given indices of the
array returned by @code{share-array}.
The array does not retain a reference to @var{shape}.
@example
(define i_4
   (let* ((i (make-array
                (shape 0 4 0 4)
                0))
          (d (share-array i
                (shape 0 4)
                (lambda (k)
                   (values k k)))))
      (do ((k 0 (+ k 1)))
          ((= k 4))
         (array-set! d k 1))
      i))
@end example

Note: the affinity requirement for @var{proc} means that each value must
be a sum of multiples of the arguments passed to @var{proc}, plus a constant.

Implementation note: arrays have to maintain an internal index mapping
from indices @var{k1} ... @var{kd} to a single index into a backing vector;
the composition of this mapping and @var{proc} can be recognised
as @code{(@var{+ n0} (* @var{n1} @var{k1}) ... (* @var{nd} @var{kd}))}
by setting each index in turn to 1 and others to 0,
and all to 0 for the constant term; the composition can then be compiled
away, together with any complexity that the user introduced in their
procedure.
@end defun

Multi-dimensional arrays are specified
by @uref{http://srfi.schemers.org/srfi-25/srfi-25.html,SRFI-25}.
In Kawa, a one-dimensional array whose lower bound is 0 is also a sequence.
Furthermore, if such an array is simple (not created @code{share-array})
it will be implemented using a @code{<vector>}.
Uniform vectors and strings are also arrays in Kawa.
For example:
@example
(share-array
 (f64vector 1.0 2.0 3.0 4.0 5.0 6.0)
 (shape 0 2 0 3)
 (lambda (i j) (+ (* 2 i) j)))
@end example
evaluates to a two-dimensionsal array of @code{<double>}:
@example
#2a((1.0 2.0 3.0) (3.0 4.0 5.0))
@end example

@node Uniform vectors, Exceptions, Arrays, Extensions
@section Uniform vectors

Uniform vectors are vectors whose elements are of the same numeric type.
The are defined by @uref{http://srfi.schemers.org/srfi-4/srfi-4.html,SRFI-4}.
However, the type names (such as @code{<s8vector>}) are a Kawa extension.

@defvar <s8vector>
The type of uniform vectors where each element can contain
a signed 8-bit integer.  Represented using an array of @code{<byte>}.
@end defvar

@defvar <u8vector>
The type of uniform vectors where each element can contain
an unsigned 8-bit integer.  Represented using an array of @code{<byte>},
but each element is treated as if unsigned.
@end defvar

@defvar <s16vector>
The type of uniform vectors where each element can contain
a signed 16-bit integer.  Represented using an array of @code{<short>}.
@end defvar

@defvar <u16vector>
The type of uniform vectors where each element can contain
an unsigned 16-bit integer.  Represented using an array of @code{<short>},
but each element is treated as if unsigned.
@end defvar

@defvar <s32vector>
The type of uniform vectors where each element can contain
a signed 32-bit integer.  Represented using an array of @code{<int>}.
@end defvar

@defvar <u32vector>
The type of uniform vectors where each element can contain
an unsigned 32-bit integer.  Represented using an array of @code{<int>},
but each element is treated as if unsigned.
@end defvar

@defvar <s64vector>
The type of uniform vectors where each element can contain
a signed 64-bit integer.  Represented using an array of @code{<long>}.
@end defvar

@defvar <u64vector>
The type of uniform vectors where each element can contain
an unsigned 64-bit integer.  Represented using an array of @code{<long>},
but each element is treated as if unsigned.
@end defvar

@defvar <f32vector>
The type of uniform vectors where each element can contain
a 32-bit floating-point real.  Represented using an array of @code{<float>}.
@end defvar

@defvar <f64vector>
The type of uniform vectors where each element can contain
a 64-bit floating-point real.  Represented using an array of @code{<double>}.
@end defvar

@defun s8vector? value
@defunx u8vector? value
@defunx s16vector? value
@defunx u16vector? value
@defunx s32vector? value
@defunx u32vector? value
@defunx s64vector? value
@defunx u64vector? value
@defunx f32vector? value
@defunx f64vector? value
Return true iff @var{value} is a uniform vector of the specified type.
@end defun

@defun make-s8vector n [value]
@defunx make-u8vector n [value]
@defunx make-s16vector n [value]
@defunx make-u16vector n [value]
@defunx make-s32vector n [value]
@defunx make-u32vector n [value]
@defunx make-s64vector n [value]
@defunx make-u64vector n [value]
@defunx make-f32vector n [value]
@defunx make-f64vector n [value]
Create a new uniform vector of the specified type,
having room for @var{n} elements.
Initialize each element to @var{value} if it is specified; zero otherwise.
@end defun

@defun s8vector value ...
@defunx u8vector value ...
@defunx s16vector value ..
@defunx u16vector value ...
@defunx s32vector value ...
@defunx u32vector value ...
@defunx s64vector value ...
@defunx u64vector value ...
@defunx f32vector value ...
@defunx f64vector value ...
Create a new uniform vector of the specified type,
whose length is the number of @var{value}s specified,
and initialize it using those @var{value}s.
@end defun

@defun s8vector-length v
@defunx u8vector-length v
@defunx s16vector-length v
@defunx u16vector-length v
@defunx s32vector-length v
@defunx u32vector-length v
@defunx s64vector-length v
@defunx u64vector-length v
@defunx f32vector-length v
@defunx f64vector-length v
Return the length (in number of elements) of the uniform vector @var{v}.
@end defun

@defun s8vector-ref v i
@defunx u8vector-ref v i
@defunx s16vector-ref v i
@defunx u16vector-ref v i
@defunx s32vector-ref v i
@defunx u32vector-ref v i
@defunx s64vector-ref v i
@defunx u64vector-ref v i
@defunx f32vector-ref v i
@defunx f64vector-ref v i
Return the element at index @var{i} of the uniform vector @var{v}.
@end defun

@defun s8vector-set! v i x
@defunx u8vector-set! v i x
@defunx s16vector-set! v i x
@defunx u16vector-set! v i x
@defunx s32vector-set! v i x
@defunx u32vector-set! v i x
@defunx s64vector-set! v i x
@defunx u64vector-set! v i x
@defunx f32vector-set! v i x
@defunx f64vector-set! v i x
Set the element at index @var{i} of uniform vector @var{v}
to the value @var{x}, which must be a number coercible
to the appropriate type.
@end defun

@defun s8vector->list v
@defunx u8vector->list v
@defunx s16vector->list v
@defunx u16vector->list v
@defunx s32vector->list v
@defunx u32vector->list v
@defunx s64vector->list v
@defunx u64vector->list v
@defunx f32vector->list v
@defunx f64vector->list v
Convert the uniform vetor @var{v} to a list containing the elments of @var{v}.
@end defun

@defun list->s8vector l
@defunx list->u8vector l
@defunx list->s16vector l
@defunx list->u16vector l
@defunx list->s32vector l
@defunx list->u32vector l
@defunx list->s64vector l
@defunx list->u64vector l
@defunx list->f32vector l
@defunx list->f64vector l
Create a uniform vector of the appropriate type, initializing it
with the elements of the list @var{l}.  The elements of @var{l}
must be numbers coercible the new vector's element type.
@end defun

@subsection Relationship with Java arrays

Each uniform array type is implemented as an @dfn{underlying Java array},
and a length field.
The underlying type is
@code{byte[]} for @code{<u8vector>} or @code{<s8vector>};
@code{short[]} for @code{<u16vector>} or @code{<u16vector>};
@code{int[]} for @code{<u32vector>} or @code{<s32vector>};
@code{long[]} for @code{<u64vector>} or @code{<s64vector>};
@code{<float[]} for @code{<f32vector>}; and
@code{<double[]} for @code{<f32vector>}.
The length field allows a uniform array to only use the
initial part of the underlying array.  (This can be used
to support Common Lisp's fill pointer feature.)
This also allows resizing a uniform vector.  There is no
Scheme function for this, but you can use the @code{setSize} method:
@example
(invoke some-vector 'setSize 200)
@end example

If you have a Java array, you can create a uniform vector
sharing with the Java array:
@example
(define arr :: <byte[]> ((primitive-array-new <byte>) 10))
(define vec :: <u8vector> (make <u8vector> arr))
@end example
At this point @code{vec} uses @code{arr} for its underlying storage,
so changes to one affect the other.
It @code{vec} is re-sized so it needs a larger underlying array,
then it will no longer use @code{arr}.

@node Exceptions, Locations, Uniform vectors, Extensions
@section Signalling and recovering from exceptions

@defun catch key thunk handler
Invoke @var{thunk} in the dynamic context of @var{handler} for
exceptions matching @var{key}.  If thunk throws to the symbol @var{key},
then @var{handler} is invoked this way:

@example
(handler key args ...)
@end example

@var{key} may be a symbol.  The @var{thunk} takes no
arguments.  If @var{thunk} returns normally, that is the return value of
@code{catch}.

Handler is invoked outside the scope of its own @code{catch}.  If
@var{handler} again throws to the same key, a new handler from further
up the call chain is invoked.

If the key is @code{#t}, then a throw to @emph{any} symbol will match
this call to @code{catch}.
@end defun

@defun throw key &rest args ...
Invoke the catch form matching @var{key}, passing @var{args} to the
@var{handler}.  

If the key is a symbol it will match catches of the same
symbol or of #t.

If there is no handler at all, an error is signaled.
@end defun

@deffn procedure error message args ...
Raise an error with key @code{misc-error} and a message constructed by
displaying @var{msg} and writing @var{args}.
This normally prints a stack trace, and brings you back to
the top level, or exits kawa if you are not running interactively.
This procedure is part of SRFI-23, and other Scheme implementations.
@end deffn

@defun primitive-throw exception
Throws the @var{exception}, which must be an instance of a sub-class
of @code{<java.lang.Throwable>}.
@end defun

@deffn Syntax try-finally body handler
Evaluate @var{body}, and return its result.
However, before it returns, evaluate @var{handler}.
Even if @var{body} returns abnormally (by throwing an exception),
@var{handler} is evaluated.

(This is implemented just like Java's @code{try}-@code{finally}.)
@end deffn

@deffn Syntax try-catch body handler ...
Evaluate @var{body}, in the context of the given @var{handler} specifications.
Each @var{handler} has the form:
@example
@var{var} @var{type} @var{exp} ...
@end example
If an exception is thrown in @var{body}, the first @var{handler}
is selected such that the thrown exception is an instance of
the @var{handler}'s @var{type}. If no @var{handler} is selected,
the exception is propagated through the dynamic execution context
until a matching @var{handler} is found.  (If no matching @var{handler}
is found, then an error message is printed, and the computation terminated.)

Once a @var{handler} is selected,
the @var{var} is bound to the thrown exception, and the @var{exp} in
the @var{handler} are executed.  The result of the @code{try-catch}
is the result of @var{body} if no exception is thrown, or the
value of the last @var{exp} in the selected @var{handler} if an
exception is thrown.

(This is implemented just like Java's @code{try}-@code{catch}.)
@end deffn

@defun dynamic-wind in-guard thunk out-guard
All three arguments must be 0-argument procedures.
First calls @var{in-guard}, then @var{thunk}, then @var{out-guard}.
The result of the expression is that of @var{thunk}.
If @var{thunk} is exited abnormally (by throwing an exception or
invoking a continuation), @var{out-guard} is called.

If the continuation of the dynamic-wind is re-entered (which
is not yet possible in Kawa), the @var{in-guard} is called again.

This function was added in R5RS.
@end defun

@node Locations, Eval and Environments, Exceptions, Extensions
@section Locations

A @dfn{location} is a place where a value can be stored.
An @dfn{lvalue} is an expression that refers to a location.
(The name "lvalue" refers to the fact that the left operand
of @code{set!} is an lvalue.)
The only kind of lvalue in standard Scheme is a @dfn{variable}.
Kawa also allows @dfn{computed lvalues}.  These are procedure
calls used in "lvalue context", such as the left operand of @code{set!}.

You can only use procedures that have an associated @dfn{setter}.
In that case, @code{(set! (f arg ...) value)}
is equivalent to @code{((setter f) arg ... value)}
Currently, only a few procedures have associated @code{setter}s,
and only builtin procedures written in Java can have @code{setter}s.

For example:
@example
(set! (car x) 10)
@end example
is equivalent to:
@example
((setter car) x 10)
@end example
which is equivalent to:
@example
(set-car! x 10)
@end example

@defun setter procedure
Gets the "setter procedure" associated with a "getter procedure".
Equivalent to @code{(procedure-property @var{procedure} 'setter)}.
By convention, a setter procedure takes the same parameters as
the "getter" procedure, plus an extra parameter that is the
new value to be stored in the location specified by the parameters.
The expectation is that following
@code{((setter @var{proc}) @var{args} ... @var{value})} then
the value of @code{(@var{proc} @var{args} ...)} will be @var{value}.

The @code{setter} of @code{setter} can be used to set the
@code{setter} property.
For example the Scheme prologue effectively does the following:
@example
(set! (setter vector-set) vector-set!)
@end example
@end defun

Kawa also gives you access to locations as first-class values:

@deffn Syntax location lvalue
Returns a location object for the given @var{lvalue}.
You can get its value (by applying it, as if it were a procedure),
and you can set its value (by using @code{set!} on the application).
The @var{lvalue} can be a local or global variable, or a procedure
call using a procedure that has a @code{setter}.
@example
(define x 100)
(define lx (location x))
(set! (lx) (cons 1 2)) ;; set x to (1 . 2)
(lx)  ;; returns (1 . 2)
(define lc (location (car x)))
(set! (lc) (+ 10 (lc)))
;; x is now (11 . 2)
@end example
@end deffn

@deffn Syntax define-alias variable lvalue
Define @var{variable} as an alias for @var{lvalue}.
In other words, makes it so that @code{(location @var{variable})}
is equivalent to @code{(location @var{lvalue})}.
This works both top-level and inside a function.
@end deffn

Some people might find it helpful to think of a location
as a settable @dfn{thunk}.  Others may find it useful to
think of the @code{location} syntax as similar to the C @samp{&} operator;
for the @samp{*} indirection operator, Kawa uses procedure application.

@node Eval and Environments, Debugging, Locations, Extensions
@section Eval and Environments

@defun eval expression [environment]
@code{eval} evaluates @var{expression} in the environment indicated
by @var{environment}.

The default for @var{environment} is the result
of @code{(interaction-environment)}.
@end defun

@defun null-environment version
This procedure returns an environment that contains no variable bindings,
but contains (syntactic) bindings for all the syntactic keywords.

The effect of assigning to a variable in this environment (such
as @code{let}) is undefined.
@end defun

@defun scheme-report-environment version
The @var{version} must be an exact non-negative inetger corresponding to
a version of one of the Revised@var{version} Reports on Scheme.
The procedure returns an environment that contains exactly the set of
bindings specified in the corresponding report.

This implementation supports @var{version} that is 4 or 5.

The effect of assigning to a variable in this environment (such
as @code{car}) is undefined.
@end defun

@defun interaction-environment
This procedure return an environment that contains implementation-defined
bindings, as well as top-level user bindings.
@end defun

@defun environment-bound? environment symbol
Return true @code{#t} if there is a binding for @var{symbol}
in @var{environment};  otherwise returns @code{#f}.
@end defun

@deffn Syntax fluid-let ((variable init) ...) body ...
Evaluate the @var{init} expressions.
Then modify the dynamic bindings for the @var{variables} to the
values of the @var{init} expressions, and evaluate the @var{body} expressions.
Return the result of the last expression in @var{body}.
Before returning, restore the original bindings.
The temporary bindings are only visible in the current thread, and its
descendent threads.
@end deffn

@defun base-uri [node]
If @var{node} is specified, returns the base-URI property
of the @var{node}.  If the @var{node} does not have the base-URI
property, returns @code{#f}.
(The XQuery version returns the empty sequence in that case.)

In the zero-argument case, returns the "base URI" of the current context.
By default the base URI is the current working directory (as a URL).
While a source file is @code{load}ed, the base URI is temporarily
set to the URL of the document.
@end defun

@defun load path
The @var{path} can be an (absolute) URL or a filename.
@end defun

@defun load-relative path
Same as @code{load}, except that @var{path} is a
URI that is relative to the context's current base URI.
@end defun

@node Debugging, Threads, Eval and Environments, Extensions
@section Debugging

@deffn Syntax trace procedure
Cause @var{procedure} to be "traced", that is debugging output will
be written to the standard error port every time @var{procedure}
is called, with the parameters and return value.
@end deffn

@deffn Syntax untrace procedure
Turn off tracing (debugging output) of @var{procedure}.
@end deffn

@node Threads, Processes, Debugging, Extensions
@section Threads

There is a very preliminary interface to create parallel threads.
The interface is similar to the standard @code{delay}/@code{force},
where a thread is basically the same as a promise, except that
evaluation may be in parallel.

So far, only modest effort has been made into making Kawa
thread-safe.

@deffn Syntax future expression
Creates a new thread that evaluates @var{expression}.
@end deffn

@defun force thread
The standard @code{force} function has generalized to also work
on threads.  If waits for the thread's @var{expression} to finish
executing, and returns the result.
@end defun

@defun sleep time
Suspends the current thread for the specified time.
The @var{time} can be either a pure number (in secords),
or a quantity whose unit is a time unit (such as @code{10s}).
@end defun

@node Processes, Miscellaneous, Threads, Extensions
@section Processes

@defun make-process command envp
Creates a @code{<java.lang.Process>} object, using the specified
@var{command} and @var{envp}.
The @var{command} is converted to an array of Java strings
(that is an object that has type @code{<java.lang.String[]>}.
It can be a Scheme vector or list (whose elements should be
Java strings or Scheme strings);  a Java array of Java strings;
or a Scheme string.  In the latter case, the command is converted
using @code{command-parse}.
The @var{envp} is process environment;  it should be either
a Java array of Java strings, or the special @code{#!null} value.
@end defun

@defun system command
Runs the specified @var{command}, and waits for it to finish.
Returns the return code from the command.  The return code is an integer,
where 0 conventionally means successful completion.
The @var{command} can be any of the types handled by @code{make-process}.
@end defun

@defvar command-parse
The value of this variable should be a one-argument procedure.
It is used to convert a command from a Scheme string to a Java
array of the constituent "words".
The default binding, on Unix-like systems, returns a new command to
invoke @code{"/bin/sh" "-c"} concatenated with the command string;
on non-Unix-systems, it is bound to @code{tokenize-string-to-string-array}.
@end defvar

@defun tokenize-string-to-string-array command
Uses a @code{java.util.StringTokenizer} to parse the @var{command} string
into an array of words.  This splits the @var{command} using spaces
to delimit words; there is no special processing for quotes or other
special characters.
(This is the same as what @code{java.lang.Runtime.exec(String)} does.)
@end defun

@node Miscellaneous,  , Processes, Extensions
@section Miscellaneous

@defun scheme-implementation-version
Returns the Kawa version number as a string.
@c (Compatible with slib.)
@end defun

@defvar command-line-arguments
Any command-line arguments (following flags processed by Kawa itself)
are assigned to the global variable @samp{command-line-arguments},
which is a vector of strings.
@end defvar

@defvar home-directory
A string containing the home directory of the user.
@end defvar

@defun exit [code]
Exits the Kawa interpreter, and ends the Java session.
The integer value @var{code} is returned to the operating
system.  If @var{code} is not specified, zero is returned,
indicating normal (non-error) termination.
@end defun

@defun scheme-window [shared]
Create a read-eval-print-loop in a new top-level window.
If @var{shared} is true, it uses the same environment as the
current @code{(interaction-environment)};  if not (the default),
a new top-level environment is created.

You can create multiple top-level window that can co-exist.
They run in separate threads.
@end defun

@deffn Syntax when condition form...
If @var{condition} is true, evaluate each @var{form} in order,
returning the value of the last one.
@end deffn

@deffn Syntax unless condition form...
If @var{condition} is false, evaluate each @var{form} in order,
returning the value of the last one.
@end deffn

@defun vector-append @var{arg}...
Creates a new vector, containing the elements from all the @var{arg}s
appended together.   Each @var{arg} may be a vector or a list.
@end defun

@defun instance? value type
Returns @code{#t} iff @var{value} is an instance of type @var{type}.
(Undefined if @var{type} is a primitive type, such as @code{<int>}.)
@end defun

@defun as type value
Converts or coerces @var{value} to a value of type @var{type}.
Throws an exception if that cannot be done.
Not supported for @var{type} to be a primitive type such as @code{<int>}.
@end defun

@deffn Syntax synchronized object form ...
Synchronize on the given @var{object}.  (This means getting an
exclusive lock on the object, by acquiring its @dfn{monitor}.)
Then execute the @var{form}s while holding the lock.
When the @var{form}s finish (normally or abnormally by throwing
an exception), the lock is released.
Returns the result of the last @var{form}.
Equivalent to the Java @code{synchronized} statement,
except that it may return a result.
@end deffn

@node Input-Output, Types, Extensions, Top
@chapter Input, output, and file handling

Kawa has a number of useful tools for controlling input and output:

A programmable reader.

A powerful pretty-printer.

@menu
* Named output formats::
* Files:: File System Interface
* Ports::
* Format:: Formatted Output (Common-Lisp-style)
@end menu

@node Named output formats, Files, , Input-Output

The @code{--output-format} (or @code{--format}) command-line switch
can be used to override the default format for how values are
printed on the standard output.  This format is used for values printed
by the read-eval-print interactive interface.  It is also used to
control how values are printed when Kawa evaluates a file named on the
command line (using the @code{-f} flag or a just a script name).
(It also effects applications compiled with the @code{--main} flag.)
It currently effects how values are printed by a @code{load},
though that may change.

The default format depends on the current programming language.
For Scheme, the default is @code{--scheme} for read-eval-print
interaction, and @code{--ignore} for files that are loaded.

The formats currently supported include the following:
@table @samp
@item scheme
Values are printed in a format matching the Scheme programming language,
as if using @code{display}.  "Groups" or "elements" are written as lists.
@item readable-scheme
Like @code{scheme}, as if using @code{write}:
Values are generally printed in a way that they can
be read back by a Scheme reader.  For example, strings have quotation marks,
and character values are written like @samp{#\A}.
@item elisp
Values are printed in a format matching the Emacs Lisp programming language.
Mostly the same as @code{scheme}.
@item readable-elisp
Like @code{elisp}, but values are generally printed in a way that they can
be read back by an Emacs Lisp reader.  For example, strings have quotation
marks, and character values are written like @samp{?A}.
@item clisp
@itemx commonlisp
Values are printed in a format matching the Common Lisp programming language,
as if written by @code{princ}.
Mostly the same as @code{scheme}.
@item readable-clisp
@itemx readable-commonlisp
Like @code{clisp}, but as if written by @code{prin1}: values are generally
printed in a way that they can be read back by a Common Lisp reader.
For example, strings have quotation marks, and character values are
written like @samp{#\A}.
@item xml
Values are printed in XML format.
"Groups" or "elements" are written as using xml element syntax.
Plain characters (such as @samp{<}) are escaped (such as @samp{&lt;}).
@item xhtml
Same as @code{xml}, but follows the xhtml compatibility guidelines.
@item html
Values are printed in HTML format.
Mostly same as @code{xml} format, but certain element without body,
are written without a closing tag.   For example @code{<img>} is written
without @code{</img>}, which would be illegal for html, but required for xml.
Plain characters (such as @samp{<}) are not escaped inside @code{<script>}
or @code{<style>} elements.
@item cgi
The output should be a follow the CGI standards.  I.e. assume that this
script is invoked by a web server as a CGI script/program, and that the
output should start with some response header,
followed by the actual response data.
To generate the response headers, use the @code{response-header} function.
If the @code{Content-type} response header has not been specified, and
it is required by the CGI standard, Kawa will attempt
to infer an appropriate @code{Content-ty[e} depending on the following value.
@item ignore
Top-level values are ignored, instead of printed.
@end table

@node Files, Ports, Named output formats, Input-Output
@section File System Interface

@defun file-exists? filename
Returns true iff the file named @var{filename} actually exists.
@end defun

@defun file-directory? filename
Returns true iff the file named @var{filename} actually exists
and is a directory.
@end defun

@defun file-readable? filename
Returns true iff the file named @var{filename} actually exists
and can be read from.
@end defun

@defun file-writable? filename
Returns true iff the file named @var{filename} actually exists
and can be writen to.
(Undefined if the @var{filename} does not exist,
but the file can be created in the directory.)
@end defun

@defun delete-file filename
Delete the file named @var{filename}.
@end defun

@defun rename-file oldname newname
Renames the file named @var{oldname} to @var{newname}.
@end defun

@defun copy-file oldname newname-from path-to
Copy the file named @var{oldname} to @var{newname}.
The return value is unspecified.
@end defun

@defun create-directory dirname
Create a new directory named @var{dirname}.
Unspecified what happens on error (such as exiting file with the same name).
(Currently returns @code{#f} on error, but may change to be more compatible
with scsh.)
@end defun

@defun system-tmpdir
Return the name of the default directory for temporary files.
@end defun

@defun make-temporary-file [format]
Return a file with a name that does not match any existing file.
Use @var{format} (which defaults to @code{"kawa~d.tmp"}) to generate
a unique filename in @code{(system-tmpdir)}.
The current implementation is @emph{not} safe from race conditions;
this will be fixed in a future release (using Java2 features).
@end defun

@node Ports, Format, Files, Input-Output
@section Ports

@defun current-error-port
Return the port to which errors and warnings should be sent
(the @dfn{standard error} in Unix and C terminology).
@end defun

@defun read-line [port [handle-newline]]
Reads a line of input from @var{port}.
The @var{handle-newline} parameter determines what is done with
terminating end-of-line delimiter.
The default, @code{'trim}, ignores the delimiter;
@code{'peek} leaves the delimiter in the input stream;
@code{'concat} appends the delimiter to the returned value;
and @code{'split} returns the delimiter as a second value.
You can use the last three options to tell if the string was
terminated by end-or-line or by end-of-file.
@end defun

@defun open-input-string string
Takes a string and returns an input port that delivers characters
from the string. The port can be closed by @code{close-input-port},
though its storage will be reclaimed by the
garbage collector if it becomes inaccessible. 

@example
(define p
  (open-input-string "(a . (b c . ())) 34"))

(input-port? p)                 -->  #t
(read p)                        -->  (a b c)
(read p)                        -->  34
(eof-object? (peek-char p))     -->  #t
@end example
@end defun

@defun open-output-string
Returns an output port that will accumulate characters
for retrieval by @code{get-output-string}.
The port can be closed by the procedure @code{close-output-port},
though its storage will be reclaimed by the garbage collector
if it becomes inaccessible. 
@example
(let ((q (open-output-string))
  (x '(a b c)))
    (write (car x) q)
    (write (cdr x) q)
    (get-output-string q))        -->  "a(b c)"
@end example
@end defun

@defun get-output-string output-port
Given an output port created by @code{open-output-string},
returns a string consisting of the characters that have been
output to the port so far. 
@end defun

@defun call-with-input-string string proc
Create an input port that gets its data from @var{string},
call @var{proc} with that port as its one argument, and return
the result from the call of @var{proc}
@end defun

@defun call-with-output-string proc
Create an output port that writes its data to a @var{string},
and call @var{proc} with that port as its one argument.
Return a string consisting of the data written to the port.
@end defun

@defun force-output [port]
Forces any pending output on @var{port} to be delivered to the output
device and returns an unspecified value.  If the @var{port} argument is
omitted it defaults to the value returned by @code{(current-output-port)}.
@end defun

An interactive input port has a prompt procedure associated with it.
The prompt procedure is called before a new line is read.  It is passed
the port as an argument, and returns a string, which gets printed as a prompt.

@defun input-port-prompter port
Get the prompt procedure associated with @var{port}.
@end defun

@defun set-input-port-prompter! port prompter
Set the prompt procedure associated with @var{port} to @var{prompter},
which must be a one-argument procedure taking an input port,
and returning a string.
@end defun

@defun default-prompter port
The default prompt procedure.  It returns @code{"#|kawa:@var{L}|# "}, where
@var{L} is the current line number of @var{port}.
When reading a continuation line, the result
is @code{"#|@var{C}---:@var{L}|# "}, where @code{C} is the character returned
by @code{(input-port-read-state @var{port})}.
The prompt has the form of a comment to make it easier to cut-and-paste.
@end defun

@deffn Function port-column input-port
@deffnx Function port-line input-port
Return the current column number or line number of @var{input-port},
using the current input port if none is specified.
If the number is unknown, the result is @code{#f}.  Otherwise,
the result is a 0-origin integer - i.e. the first character
of the first line is line 0, column 0.  (However, when you
display a file position, for example in an error message,
we recommend you add 1 to get 1-origin integers.  This is
because lines and column numbers traditionally start with
1, and that is what non-programmers will find most natural.)
@end deffn

@defun set-port-line! port line
Set (0-origin) line number of the current line of @var{port} to @var{num}.
@end defun

@defun input-port-line-number port
Get the line number of the current line of @var{port},
which must be a (non-binary) input port.
The initial line is line 1.
Deprecated; replaced by @code{(+ 1 (port-line @var{port}))}.
@end defun

@defun set-input-port-line-number! port num
Set line number of the current line of @var{port} to @var{num}.
Deprecated;  replaced by @code{(set-port-line! @var{port} (- @var{num} 1))}.
@end defun

@defun input-port-column-number port 
Get the column number of the current line of @var{port}, 
which must be a (non-binary) input port.
The initial column is column 1.
Deprecated; replaced by @code{(+ 1 (port-column @var{port}))}.
@end defun

@defun input-port-read-state port
Returns a character indicating the current @code{read} state of the @var{port}.
Returns @code{#\Return} if not current doing a @var{read},
@code{#\"} if reading a string;  @code{#\|} if reading a comment;  @code{#\(}
if inside a list; and @code{#\Space} when otherwise in a @code{read}.
The result is intended for use by prompt prcedures, and is not necessarily
correct except when reading a new-line.
@end defun

@defvar symbol-read-case
A symbol that controls how @code{read} handles letters when reading a symbol.
If the first letter is @samp{U}, then letters in symbols are upper-cased.
If the first letter is @samp{D} or @samp{L}, then letters
in symbols are down-cased.
If the first letter is @samp{I}, then the case of letters in symbols
is inverted.
Otherwise (the default), the letter is not changed.
(Letters following a @samp{\} are always unchanged.)
@end defvar

@defvar port-char-encoding
Controls how bytes in external files are converted to/from internal
Unicode characters.  Can be either a symbol or a boolean.
If @code{port-char-encoding} is @code{#f}, the file is assumed
to be a binary file and no conversion is done.
Otherwise, the file is a text file.  The default is @code{#t}, which
uses a locale-dependent conversion.  If @code{port-char-encoding}
is a symbol, it must be the name of a character encoding known to Java.
For all text files (that is if @code{port-char-encoding} is not @code{#f}),
on input a @code{#\Return} character or
a @code{#\Return} followed by @code{#\Newline}
are converted into plain @code{#\Newline}.

This variable is checked when the file is opened;  not when actually
reading or writing.  Here is an example of how you can safely
change the encoding temporarily:
@example
(define (open-binary-input-file name)
  (fluid-let ((port-char-encoding #f)) (open-input-file name)))
@end example
@end defvar

@node Format, , Ports, Input-Output
@section Formatted Output (Common-Lisp-style)

@defun format destination fmt . arguments
An almost complete implementation of Common LISP format description
according to the CL reference book @cite{Common LISP} from Guy L.
Steele, Digital Press.  Backward compatible to most of the available
Scheme format implementations.

Returns @code{#t}, @code{#f} or a string; has side effect of printing
according to @var{fmt}.  If @var{destination} is @code{#t},
the output is to the current output port and @code{#!void} is returned.  If
@var{destination} is @code{#f}, a formatted string is returned as the
result of the call.  If @var{destination} is a string,
@var{destination} is regarded as the format string; @var{fmt} is
then the first argument and the output is returned as a string. If
@var{destination} is a number, the output is to the current error port
if available by the implementation. Otherwise @var{destination} must be
an output port and @code{#!void} is returned.@refill

@var{fmt} must be a string or an instance of @code{gnu.text.MessageFormat}
or @code{java.text.MessageFormat}.  If @var{fmt} is a string,
it is parsed as if by @code{parse-format}.
@end defun

@defun parse-format format-string
Parses @code{format-string}, which is a string of the form of a Common LISP
format description.  Returns an instance of @code{gnu.text.ReportFormat},
which can be passed to the @code{format} function.
@end defun

A format string passed to @code{format} or @code{parse-format}
consists of format directives (that start with @samp{~}),
and regular characters (that are written directly to the destination).
Most of the Common Lisp (and Slib) format directives are implemented.
Neither justification, nor pretty-printing are supported yet.

Plus of course, we need documentation for @code{format}!

@subsection Implemented CL Format Control Directives

Documentation syntax: Uppercase characters represent the corresponding
control directive characters. Lowercase characters represent control
directive parameter descriptions.

@table @asis
@item @code{~A}
Any (print as @code{display} does).
@table @asis
@item @code{~@@A}
left pad.
@item @code{~@var{mincol},@var{colinc},@var{minpad},@var{padchar}A}
full padding.
@end table
@item @code{~S}
S-expression (print as @code{write} does).
@table @asis
@item @code{~@@S}
left pad.
@item @code{~@var{mincol},@var{colinc},@var{minpad},@var{padchar}S}
full padding.
@end table

@item @code{~C}
Character.
@table @asis
@item @code{~@@C}
prints a character as the reader can understand it (i.e. @code{#\} prefixing).
@item @code{~:C}
prints a character as emacs does (eg. @code{^C} for ASCII 03).
@end table
@end table

@subsection Formatting Integers

@table @asis
@item @code{~D}
Decimal.
@table @asis
@item @code{~@@D}
print number sign always.
@item @code{~:D}
print comma separated.
@item @code{~@var{mincol},@var{padchar},@var{commachar},@var{commawidth}D}
padding.
@end table
@item @code{~X}
Hexadecimal.
@table @asis
@item @code{~@@X}
print number sign always.
@item @code{~:X}
print comma separated.
@item @code{~@var{mincol},@var{padchar},@var{commachar},@var{commawidth}X}
padding.
@end table
@item @code{~O}
Octal.
@table @asis
@item @code{~@@O}
print number sign always.
@item @code{~:O}
print comma separated.
@item @code{~@var{mincol},@var{padchar},@var{commachar},@var{commawidth}O}
padding.
@end table
@item @code{~B}
Binary.
@table @asis
@item @code{~@@B}
print number sign always.
@item @code{~:B}
print comma separated.
@item @code{~@var{mincol},@var{padchar},@var{commachar},@var{commawidth}B}
padding.
@end table
@item @code{~@var{n}R}
Radix @var{n}.
@table @asis
@item @code{~@var{n},@var{mincol},@var{padchar},@var{commachar},@var{commawidth}R}
padding.
@end table
@item @code{~@@R}
print a number as a Roman numeral.
@item @code{~:@@R}
print a number as an ``old fashioned'' Roman numeral.
@item @code{~:R}
print a number as an ordinal English number.
@item @code{~R}
print a number as a cardinal English number.
@item @code{~P}
Plural.
@table @asis
@item @code{~@@P}
prints @code{y} and @code{ies}.
@item @code{~:P}
as @code{~P but jumps 1 argument backward.}
@item @code{~:@@P}
as @code{~@@P but jumps 1 argument backward.}
@end table
@end table

@var{commawidth} is the number of characters between two comma characters.


@subsection Formatting floating-point (real) numbers

@table @asis
@item @code{~F}
Fixed-format floating-point (prints a flonum like @var{mmm.nnn}).
@table @asis
@item @code{~@var{width},@var{digits},@var{scale},@var{overflowchar},@var{padchar}F}
@item @code{~@@F}
If the number is positive a plus sign is printed.
@end table
@end table

@table @asis
@item @code{~E}
Exponential floating-point (prints a flonum like @var{mmm.nnn}@code{E}@var{ee})
@table @asis
@item @code{~@var{width},@var{digits},@var{exponentdigits},@var{scale},@var{overflowchar},@var{padchar},@var{exponentchar}E}
@item @code{~@@E}
If the number is positive a plus sign is printed.
@end table
@end table

@table @asis
@item @code{~G}
General floating-point (prints a flonum either fixed or exponential).
@table @asis
@item @code{~@var{width},@var{digits},@var{exponentdigits},@var{scale},@var{overflowchar},@var{padchar},@var{exponentchar}G}
@item @code{~@@G}
If the number is positive a plus sign is printed.
@end table
A slight difference from Common Lisp:  If the number is printed
in fixed form and the fraction is zero,
then a zero digit is printed for the fraction, if allowed by the @var{width}
and @var{digits} is unspecified.
@end table

@table @asis
@item @code{~$}
Dollars floating-point (prints a flonum in fixed with signs separated).
@table @asis
@item @code{~@var{digits},@var{scale},@var{width},@var{padchar}$}
@item @code{~@@$}
If the number is positive a plus sign is printed.
@item @code{~:@@$}
A sign is always printed and appears before the padding.
@item @code{~:$}
The sign appears before the padding.
@end table
@end table

@subsection Miscellaneous formatting operators

@table @asis
@item @code{~%}
Newline.
@table @asis
@item @code{~@var{n}%}
print @var{n} newlines.
@end table
@item @code{~&}
print newline if not at the beginning of the output line.
@table @asis
@item @code{~@var{n}&}
prints @code{~&} and then @var{n-1} newlines.
@end table
@item @code{~|}
Page Separator.
@table @asis
@item @code{~@var{n}|}
print @var{n} page separators.
@end table
@item @code{~~}
Tilde.
@table @asis
@item @code{~@var{n}~}
print @var{n} tildes.
@end table
@item @code{~}<newline>
Continuation Line.
@table @asis
@item @code{~:}<newline>
newline is ignored, white space left.
@item @code{~@@}<newline>
newline is left, white space ignored.
@end table
@item @code{~T}
Tabulation.
@table @asis
@item @code{~@@T}
relative tabulation.
@item @code{~@var{colnum},@var{colinc}T}
full tabulation.
@end table
@item @code{~?}
Indirection (expects indirect arguments as a list).
@table @asis
@item @code{~@@?}
extracts indirect arguments from format arguments.
@end table
@item @code{~(@var{str}~)}
Case conversion (converts by @code{string-downcase}).
@table @asis
@item @code{~:(@var{str}~)}
converts by @code{string-capitalize}.
@item @code{~@@(@var{str}~)}
converts by @code{string-capitalize-first}.
@item @code{~:@@(@var{str}~)}
converts by @code{string-upcase}.
@end table
@item @code{~*}
Argument Jumping (jumps 1 argument forward).
@table @asis
@item @code{~@var{n}*}
jumps @var{n} arguments forward.
@item @code{~:*}
jumps 1 argument backward.
@item @code{~@var{n}:*}
jumps @var{n} arguments backward.
@item @code{~@@*}
jumps to the 0th argument.
@item @code{~@var{n}@@*}
jumps to the @var{n}th argument (beginning from 0)
@end table
@item @code{~[@var{str0}~;@var{str1}~;...~;@var{strn}~]}
Conditional Expression (numerical clause conditional).
@table @asis
@item @code{~@var{n}[}
take argument from @var{n}.
@item @code{~@@[}
true test conditional.
@item @code{~:[}
if-else-then conditional.
@item @code{~;}
clause separator.
@item @code{~:;}
default clause follows.
@end table
@item @code{~@{@var{str}~@}}
Iteration (args come from the next argument (a list)).
@table @asis
@item @code{~@var{n}@{}
at most @var{n} iterations.
@item @code{~:@{}
args from next arg (a list of lists).
@item @code{~@@@{}
args from the rest of arguments.
@item @code{~:@@@{}
args from the rest args (lists).
@end table
@item @code{~^}
Up and out.
@table @asis
@item @code{~@var{n}^}
aborts if @var{n} = 0
@item @code{~@var{n},@var{m}^}
aborts if @var{n} = @var{m}
@item @code{~@var{n},@var{m},@var{k}^}
aborts if @var{n} <= @var{m} <= @var{k}
@end table
@end table

@subsection Not Implemented CL Format Control Directives

@table @asis
@item @code{~:A}
print @code{#f} as an empty list (see below).
@item @code{~:S}
print @code{#f} as an empty list (see below).
@item @code{~<~>}
Justification.
@item @code{~:^}
@end table

@subsubsection Extended, Replaced and Additional Control Directives

These are not necesasrily implemented in Kawa!

@table @asis
@item @code{~I}
print a R4RS complex number as @code{~F~@@Fi} with passed parameters for
@code{~F}.
@item @code{~Y}
Pretty print formatting of an argument for scheme code lists.
@item @code{~K}
Same as @code{~?.}
@item @code{~!}
Flushes the output if format @var{destination} is a port.
@item @code{~_}
Print a @code{#\space} character
@table @asis
@item @code{~@var{n}_}
print @var{n} @code{#\space} characters.
@end table

@item @code{~@var{n}C}
Takes @var{n} as an integer representation for a character. No arguments
are consumed. @var{n} is converted to a character by
@code{integer->char}.  @var{n} must be a positive decimal number.@refill
@item @code{~:S}
Print out readproof.  Prints out internal objects represented as
@code{#<...>} as strings @code{"#<...>"} so that the format output can always
be processed by @code{read}.
@refill
@item @code{~:A}
Print out readproof.  Prints out internal objects represented as
@code{#<...>} as strings @code{"#<...>"} so that the format output can always
be processed by @code{read}.
@refill
@item @code{~F, ~E, ~G, ~$}
may also print number strings, i.e. passing a number as a string and
format it accordingly.
@end table

@node Types, Objects Classes and Modules, Input-Output, Top
@chapter Types

A @dfn{type} is a set of values, plus an associated set of operations
valid on those values.
Types are useful for catching errors ("type-checking"), documenting
the programmer's intent, and to help the compiler generate better code.
Types in some languages (such as C) appear in programs,
but do not exist at run-time.  In such languages, all type-checking
is done at compile-time.  Other languages (such as standard Scheme)
do not have types as such, but they have @dfn{predicates}, which
allow you to check if a value is a member of certain sets;  also,
the primitive functions will check at run-time if the arguments
are members of the allowed sets.  Other languages, including Java
and Common Lisp, provide a combination:  Types may be used as specifiers
to guide the compiler, but also exist as actual run-time values.
In Java, for each class, there is a corresponding @code{java.lang.Class}
run-time object, as well as an associated type (the set of values
of that class, plus its sub-classes, plus @code{null}).

Kawa, like Java, has first-class types, that is types exist as
objects you can pass around at run-time.  For each Java type,
there is a corresponding Kawa type (but not necessarily vice
versa).  It would be nice if we could represent run-time
type values using @code{java.lang.Class} objects, but unfortunately
that does not work very well.  One reason is that we need
to be able to refer to types and classes that do not exist yet,
because we are in the processing of compiling them.  Another
reason is that we want to be able to distinuish between different
types that are implemented using the same Java class.

Various Kawa constructs require or allow a type to be specified.
Those specifications consist of @dfn{type expressions}, which
is evaluated to yield a type value.  The current Kawa compiler
is rather simple-minded, and in many places only allows simple
types that the compiler can evaluate at compile-time.
More specifically, it only allows simple @dfn{type names}
that map to primitive Java types or java classes.

@menu
* Standard Types::
* Declaring Types of Variables::
@end menu

@node Standard Types, Declaring Types of Variables, Types, Types
@section Standard Types

These types are bound to identifiers having the form @code{<TYPENAME>}.
(This syntax and most of the names are as in RScheme.)

To find which Java classes these types map into, look in
@code{kawa/standard/Scheme.java}.

Note that the value of these variables are instances
of @code{gnu.bytecode.Type},
not (as you might at first expect) @code{java.lang.Class}.

@defvar <object>
An arbitrary Scheme value - and hence an arbitrary Java object.
@end defvar

@defvar <number>
The type of Scheme numbers.
@end defvar

@defvar <quantity>
The type of quantities optionally with units.
This is a sub-type of @code{<number>}.
@end defvar

@defvar <complex>
The type of complex numbers.
This is a sub-type of @code{<quantity>}.
@end defvar

@defvar <real>
The type of real numbers.
This is a sub-type of @code{<complex>}.
@end defvar

@defvar <rational>
The type of exact rationl numbers.
This is a sub-type of @code{<real>}.
@end defvar

@defvar <integer>
The type of exact Scheme integers.
This is a sub-type of @code{<rational>}.
@end defvar

@defvar <symbol>
The type of Scheme symbols.
@end defvar

@defvar <keyword>
The type of keyword values.  @xref{Keywords}.
@end defvar

@defvar <list>
The type of Scheme lists (pure and impure, including the empty list).
@end defvar

@defvar <pair>
The type of Scheme pairs.  This is a sub-type of @code{<list>}.
@end defvar

@defvar <string>
The type of (mutable) Scheme strings.
This is @emph{not} the same as (non-mutable) Java strings
(which happen to be the same as @code{<symbol>}).
@end defvar

@defvar <character>
The type of Scheme character values.  This is a sub-type of
@code{<object>}, in contrast to type @code{<char>}, which is the
primitive Java @code{char} type.
@end defvar

@defvar <vector>
The type of Scheme vectors.
@end defvar

@defvar <procedure>
The type of Scheme procedures.
@end defvar

@defvar <input-port>
The type of Scheme input ports.
@end defvar

@defvar <output-port>
The type of Scheme output ports.
@end defvar

@defvar <String>
This type name is a special case.  It specifies the class
@code{<java.lang.String>} (just as @code{<symbol>} does).
However, coercing a value to @code{<String>} is done by
invoking the @code{toString} method on the value to be coerced.
Thus it "works" for all objects.
It also works for @code{#!null}.

When Scheme code invokes a Java methods any parameter
whose type is @code{java.lang.String} is converted
as if it was decalred as a @code{<String>}.
@end defvar

More will be added later.

A type specifier can also be one of the primitive Java types.
The numeric types @code{<long>}, @code{<int>}, @code{<short>},
@code{<byte>}, @code{<float>}, and @code{<double>} are converted from the
corresponding Scheme number classes.  Similarly, @code{<char>}
can be converted to and from Scheme characters.  The type
@code{boolean} matches any object, and the result is @code{false}
if and only if the actual argument is @code{#f}.
(The value @code{#f} is identical to @code{Boolean.FALSE},
and @code{#t} is identical to @code{Boolean.TRUE}.)
The return type @code{<void>} indicates that no value is returned.

A type specifier can also be a fully-qualified Java class name
(for example @code{<java.lang.StringBuffer>}).  In that case,
the actual argument is cast at run time to the named class.
Also, @code{<java.lang.StringBuffer[]>} represents
an array of references to @code{java.lang.StringBuffer} objects.

@node Declaring Types of Variables,  , Standard Types, Types
@section Declaring Types of Variables

@deffn Syntax let ((name [:: type] init) ...) body
Declare new locals variables with the given @var{name}, initial value
@var{init}, and optional type specification @var{type}.
If @var{type} is specified, then the expression @var{init} is evaluated,
the result coerced to @var{type}, and then assigned to the variable.
If @var{type} is not specified, it defaults to @code{<object>}.
@end deffn

@deffn Syntax let* ((name [:: type] init) ...) body
@end deffn

@deffn Syntax letrec ((name [:: type] init) ...) body
@end deffn

@deffn Syntax define [:: type] value
@end deffn

See also @code{define-private}, and @code{define-constant}.

@node Objects Classes and Modules, Low-level functions, Types, Top
@chapter Object, Classes and Modules

Kawa provides various ways to define, create, and access Java objects.
Here are the currently supported features.

The Kawa module system is based on the features of the Java class system.

@menu
* Record types::          Defining Record Types
* Dynamic records::       Creating New Record Types On-the-fly
* Mangling::              Mapping Scheme names to Java names
* Allocating objects::
* Field operations::      Accessing fields of Java objects
* Method operations::     Calling Java methods from Scheme
* Defining new classes::
* Anonymous classes::
* Module classes::        Modules and how they are compiled to classes
@end menu

@deffn Syntax this
Returns the "this object" - the current instance of the current class.
The current implementation is incomplete, not robust, and not
well defined.  However, it will have to do for now.
Note:  "@code{this}" is a macro, not a variable, so you have to write
it using parentheses: @samp{(this)}.  A planned extension will
allow an optional class specifier (needed for nested clases).
@end deffn

@node Record types, Dynamic records, Objects Classes and Modules, Objects Classes and Modules

The @code{define-record-type} form can be used for creating new data
types, called record types. A predicate, constructor, and field
accessors and modifiers are defined for each record type.
The @code{define-record-type} feature is specified
by @uref{http://srfi.schemers.org/srfi-9/srfi-9.html,SRFI-9},
which is implemented by many modern Scheme implementations.

@deffn Syntax define-record-type @var{type-name} (@var{constructor-name} @var{field-tag} ...) @var{predicate-name} (@var{field-tag} @var{accessor-name} [@var{modifier-name}]) ...

The form @code{define-record-type} is generative: each use creates a new
record type that is distinct from all existing types, including other
record types and Scheme's predefined types. Record-type definitions may
only occur at top-level (there are two possible semantics for `internal'
record-type definitions, generative and nongenerative, and no consensus
as to which is better).

An instance of @code{define-record-type} is equivalent to the following definitions:
@itemize @bullet
@item
The @var{type-name} is bound to a representation of the record type
itself.
@item
The @var{constructor-name} is bound to a procedure that takes
as many arguments as there are @var{field-tag}s in the
@code{(@var{constructor-name} ...)} subform and returns
a new @var{type-name} record. Fields whose tags are listed with
@var{constructor-name} have the corresponding argument as their initial
value. The initial values of all other fields are unspecified.
@item
The @var{predicate-name} is a predicate that returns @code{#t}
when given a value returned by @var{constructor-name}
and @code{#f} for everything else.
@item
Each @var{accessor-name} is a procedure that takes a record of
type @var{type-name} and returns the current value of the corresponding field.
It is an error to pass an accessor a value which is not a record of the
appropriate type.
@item
Each @var{modifier-name} is a procedure that takes a record of
type @var{type-name} and a value which becomes the new value of
the corresponding field.
The result (in Kawa) is the empty value @code{#!void}.
It is an error to pass a
modifier a first argument which is not a record of the appropriate type.
@end itemize

Set!ing the value of any of these identifiers has no effect on the
behavior of any of their original values.
@end deffn

Here is an example of how you can define a record type named @code{pare}
with two fields @code{x} and @code{y}:
@example
(define-record-type pare
  (kons x y)
  pare?
  (x kar set-kar!)
  (y kdr))
@end example

The above defines @code{kons} to be a constructor,
@code{kar} and @code{kdr} to be accessors,
@code{set-kar!} to be a modifier,
and @code{pare?} to be a predicate for @code{pare}s.
@example
(pare? (kons 1 2))        --> #t
(pare? (cons 1 2))        --> #f
(kar (kons 1 2))          --> 1
(kdr (kons 1 2))          --> 2
(let ((k (kons 1 2)))
  (set-kar! k 3)
  (kar k))                --> 3
@end example

The Kawa compiler creates a new Java class with a name derived from
the @var{type-name}.  If the @var{type-name} is valid Java class name,
that becomes the name of the Java class.  If the @var{type-name} has
the form @code{<@var{name}>} (for example @code{<pare>}), then @var{name}
is used, if possible, for the Java class name.  Otherwise, the name
of the Java class is derived by "mangling" the @var{type-name}.
In any case, the package is the same as that of the surrounding module.

Kawa generates efficient code for the @var{predicate-name},
@var{accessor-name}, and @var{modifier-name} functions.
The @var{constructor-name} currently compiles into code using run-time
reflection, but hopefully that will get fixed.

@node Dynamic records, Mangling, Record types, Objects Classes and Modules
@section Creating New Record Types On-the-fly

Calling the @code{make-record-type} procedure creates a new record data
type at run-time, without any compile-time support.
It is primarily provided for compatibility; in most cases it is better
to use the @code{define-record-type} form (@pxref{Record types}).

@defun make-record-type type-name field-names
Returns a @dfn{record-type descriptor}, a value representing a new data
type disjoint from all others.  The @var{type-name} argument must be a
string, but is only used for debugging purposes (such as the printed
representation of a record of the new type).  The @var{field-names}
argument is a list of symbols naming the @dfn{fields} of a record of the
new type.  It is an error if the list contains any duplicates.
@end defun

@c @defun make-record-sub-type type-name field-names rtd
@c Returns a @dfn{record-type descriptor}, a value representing a new data
@c type, disjoint from all others.  The @var{type-name} argument must be a
@c string.  The @var{field-names} argument is a list of symbols naming the
@c additional @dfn{fields} to be appended to @var{field-names} of
@c @var{rtd}.  It is an error if the combinded list contains any
@c duplicates.@refill
@c
@c Record-modifiers and record-accessors for @var{rtd} work for the new
@c record-sub-type as well.  But record-modifiers and record-accessors for
@c the new record-sub-type will not neccessarily work for @var{rtd}.@refill
@c @end defun

@defun record-constructor rtd [field-names]
Returns a procedure for constructing new members of the type represented
by @var{rtd}.  The returned procedure accepts exactly as many arguments
as there are symbols in the given list, @var{field-names}; these are
used, in order, as the initial values of those fields in a new record,
which is returned by the constructor procedure.  The values of any
fields not named in that list are unspecified.  The @var{field-names}
argument defaults to the list of field names in the call to
@code{make-record-type} that created the type represented by @var{rtd};
if the @var{field-names} argument is provided, it is an error if it
contains any duplicates or any symbols not in the default list.

@c In Kawa, @var{rtd} may be any @code{Class} that has a public default
@c constructor, as long as the @var{field-names} are public instance
@c fields.  (The fields should have type @code{Object} -- unless you
@c know what you are doing!)
@end defun

@defun record-predicate rtd
Returns a procedure for testing membership in the type represented by
@var{rtd}.  The returned procedure accepts exactly one argument and
returns a true value if the argument is a member of the indicated record
type; it returns a false value otherwise.

@c In Kawa, the returned procedure checks if the argument is an instance
@c of @var{rtd} or one of its sub-classes.
@end defun

@c @defun record-sub-predicate rtd
@c Returns a procedure for testing membership in the type represented by
@c @var{rtd} or its parents.  The returned procedure accepts exactly one
@c argument and returns a true value if the argument is a member of the
@c indicated record type or its parents; it returns a false value
@c otherwise.@refill
@c @end defun

@defun record-accessor rtd field-name
Returns a procedure for reading the value of a particular field of a
member of the type represented by @var{rtd}.  The returned procedure
accepts exactly one argument which must be a record of the appropriate
type; it returns the current value of the field named by the symbol
@var{field-name} in that record.  The symbol @var{field-name} must be a
member of the list of field-names in the call to @code{make-record-type}
that created the type represented by @var{rtd}.
@end defun

@defun record-modifier rtd field-name
Returns a procedure for writing the value of a particular field of a
member of the type represented by @var{rtd}.  The returned procedure
accepts exactly two arguments: first, a record of the appropriate type,
and second, an arbitrary Scheme value; it modifies the field named by
the symbol @var{field-name} in that record to contain the given value.
The returned value of the modifier procedure is unspecified.  The symbol
@var{field-name} must be a member of the list of field-names in the call
to @code{make-record-type} that created the type represented by @var{rtd}.
@end defun

@defun record? obj
Returns a true value if @var{obj} is a record of any type and a false
value otherwise.
@end defun

@defun record-type-descriptor record
Returns a record-type descriptor representing the type of the given
record.  That is, for example, if the returned descriptor were passed to
@code{record-predicate}, the resulting predicate would return a true
value when passed the given record.
@end defun

@defun record-type-name rtd
Returns the type-name associated with the type represented by rtd.  The
returned value is @code{eqv?} to the @var{type-name} argument given in
the call to @code{make-record-type} that created the type represented by
@var{rtd}.@refill
@end defun

@defun record-type-field-names rtd
Returns a list of the symbols naming the fields in members of the type
represented by @var{rtd}.  The returned value is @code{equal?} to the
field-names argument given in the call to @code{make-record-type} that
created the type represented by @var{rtd}.@refill
@end defun

Records are extensions of the class @code{Record}.
These procedures use the Java 1.1 reflection facility.

@node Mangling, Allocating objects, Dynamic records, Objects Classes and Modules
@section Mapping Scheme names to Java names

Programs use "names" to refer to various values and procedures.
The definition of what is a "name" is different in different
programming languages.  A name in Scheme (and other Lisp-like
languages) can in principle contain any character (if using a
suitable quoting convention), but typically names consist of
"words" (one or more letters) separated by hyphens, such
as @samp{make-temporary-file}.  Digits
and some special symbols are also used.  Standard Scheme
is case-insensitive;  this means that the names @samp{loop},
@samp{Loop}, and @samp{LOOP} are all the same name.  Kawa
is by default case-sensitive, but we recommend that you
avoid using upper-case letters as a general rule.

The Java language and the Java virtual machine uses names for
classes, variables, fields and methods.  These names can
contain upper- and lower-case letters, digits, and the special
symbols @samp{_} and @samp{$}.

Given a name in a Scheme program,
Kawa needs to map that name into a valid Java name.  A typical
Scheme name such as @samp{make-temporary-file} is not a valid
Java name.  The convention for Java names is to use
"mixed-case" words, such as @samp{makeTemporaryFile}.
So Kawa will translate a Scheme-style name into a Java-style
name.  The basic rule is simple:  Hyphens are dropped, and
a letter that follows a hyphen is translated to its
upper-case (actually "title-case") equivalent.  Otherwise,
letters are translated as is.

Some special characters are handled specially.  A final @samp{?}
is replaced by an @emph{initial} @samp{is}, with the following
letter converted to titlecase.  Thus @samp{number?} is
converted to @samp{isNumber} (which fits with Java conventions),
and @samp{file-exists?} is converted to @samp{isFileExists}
(which doesn't really).
The pair @samp{->} is translated to @samp{$To$}.
For example @samp{list->string} is translated to @samp{list$To$string}.

Some symbols are mapped to a mnemonic sequence, starting with a dollar-sign,
followed by a two-character abbreviation.  For example, the less-than
symbol @samp{<} is mangled as @samp{$Ls}.
See the source code to the @code{mangleName} method in the
@code{gnu.expr.Compilation} class for the full list.
Characters that do not have a mnemonic abbreviation are
mangled as @samp{$} followed by a four-hex-digit unicode value.
For example @samp{Tamil vowel sign ai} is mangled as @samp{$0bc8}.

Note that this mapping may map different Scheme names to the
same Java name.  For example @samp{string?}, @samp{String?},
@samp{is-string}, @samp{is-String},
and @samp{isString} are all mapped to the same Java identifier
@samp{isString}.  Code that uses such "Java-clashing" names
is @emph{not} supported.  There is very partial support for
renaming names in the case of a clash, and there may be better
support in the future.  However, some of the nice features of
Kawa depend on being able to map Scheme name to Java names
naturally, so we urge you to @emph{not} write code that
"mixes" naming conventions by using (say) the names @samp{open-file}
and @samp{openFile} to name two different objects.

The above mangling is used to generate Java method names.
Each top-level definition is also mapped to a Java field.
The name of this field is also mangled, but using a mostly
reversible mapping:  The Scheme function @samp{file-exists?}
is mapped to the method name @samp{file$Mnexists$Qu}.
Because @samp{$} is used to encode special characters, you
should avoid using it in names in your source file.

@node Allocating objects, Method operations, Mangling, Objects Classes and Modules
@section  Allocating objects

@defun make type args ...
Constructs a new object instance of the specified @var{type},
which must be either a @code{java.lang.Class} or a
@code{<gnu.bytecode.ClassType>}.

The @var{args ...} are passed to the constructor of the class type.
If there is no applicable constructor, and the @var{args ...}
consist of a set of (@var{keyword},@var{value})-pairs,
then the default constructor is called, and each
(@var{keyword},@var{value})-pair is used to set the correspdong slot
of the result, as if by:
@code{(slot-set! @var{result} @var{keyword} @var{value})}.

For example, the following are all equivalent:
@example
(set! p (make <java.awt.Point> 3 4))

(set! p (make <java.awt.Point> y: 4 x: 3))

(set! p (make <java.awt.Point>))
(slot-set! p 'x 3)
(set! (slot-ref p 'y) 4)
@end example

@end defun

@node Method operations, Field operations, Allocating objects, Objects Classes and Modules
@section Calling Java methods from Scheme

You can call a Java method as if it were a Scheme procedure
using various mechanisms.
The most convenient way to do it is to
use @code{define-namespace} to define an alias for a Java class:
@example
(define-namespace Int32 "class:java.lang.Integer")
@end example
In this example the name @code{Int32} is a @dfn{namespace alias}
for the namespace whose full name is @code{"class:java.lang.Integer"}.
The full name should be the 6 characters @code{"class:"} followed
by the fully-qualified name of a Java class.
You can name a method using a @dfn{qualified name} containing a colon.
The part of the name before the colon is a namespace alias (in
this case @code{Int32}), and the part of the name after the colon is the
method name.  For example:
@example
(Int32:toHexString 255) => ff
@end example
This invokes the static method @code{toHexString} in the
Java class @code{java.lang.Integer}, passing it the argument @code{255},
and returning the Java String @code{"ff"}.  (Note this is not the
same as a Scheme string!)

You can use the method name @code{new} to construct new objects:
@example
(Int32:new '|255|)
@end example
This is equivalent to the Java expression @code{new Integer("255")}.
You can also write:
@example
(Int32:new "255")
@end example
Kawa is smart enough to convert the Kawa string to a Java String.

You can invoke non-static methods the same way.  In that case the first
argument is the receiver or @code{this} argument.
@example
(Int32:toString (Int32:new "00255"))
@end example
This evaluates to the Java String @code{"255"}.

As a shorthand, you can use the name of a Java class instead of a
namespace alias:
@example
(java.lang.Integer:toHexString 255)
(java.lang.Object:toString some-value)
@end example
If Kawa sees a qualified name with a prefix that is not defined @emph{and}
that matches the name of an existing class, then Kawa will automaticaly
treat the prefix
as a nickname for namespace uri like @code{class:java.lang.Integer}.
Both conditions should be true at both compile-time and run-time.
However, using an explicit @code{define-namespace} is recommended.

If you prefer, you can instead use the following functions.
(There is also an older deprecated lower-level interface
(@pxref{Low-level Method invocation}.)

@defun invoke-static class name args ...
The @var{class} can be a @code{<java.lang.Class>}, a
@code{<gnu.bytecode.ClassType>}, or a @code{<symbol>} or @code{<string>}
that names a Java class.  The @var{name} can be @code{<symbol>} or
@code{<string>} that names one or more methods in the Java class.
The name is "mangled" (@pxref{Mangling}) into a valid Java name.

Any public methods (static or instance) in the specified @var{class} (or its
super-classes) that match "@var{name}" or "@var{name}$V" collectively form a
generic procedure.  When the procedure is applied to the argument list,
the most specific applicable method is chosen depending on the
argument list;  that method is then
called with the given arguments.  Iff the method is an instance method,
the first actual argument is used as the @code{this} argument.  If there are
no applicable methods (or no methods at all!), or there is no "best"
method, @code{WrongType} is thrown.

("@var{name}$V" is used for procedures with @code{#!rest} or keyword args;
the last argument must be an array type;  all the "extra" arguments
must be compatible with the type of the array elements.)

An example (derived from the Skij FAQ):
@example
(invoke-static <java.lang.Thread> 'sleep 100)
@end example

The behavior of interpreted code and compiled code is not
identical, though you should get the same result either way
unless you have designed the classes rather strangely.  The
details will be nailed down later, but the basic idea is that
the compiler will "inline" the @code{invoke-static} call
if it can pick a single "best" matching method.
@end defun

@defun invoke object name args ...
The @var{name} can be @code{<symbol>} or
@code{<string>} that names one or more methods in the Java class.
The name is "mangled" (@pxref{Mangling}) into a valid Java name.

Any public methods (static or instance) in the specified @var{class} (or its
super-classes) that match "@var{name}" or "@var{name}$V" collectively form a
generic procedure.  When the procedure is applied to the argument list,
the most specific applicable method is chosen depending on the
argument list;  that method is then
called with the given arguments.  Iff the method is an instance method,
the @var{object} is used as the @code{this} argument;
otherwise @var{object} is prepended to the @var{args} list.  If there are
no applicable methods (or no methods at all!), or there is no "best"
method, @code{WrongType} is thrown.

("@var{name}$V" is used for procedures with @code{#!rest} or keyword args;
the last argument must be an array type;  all the "extra" arguments
must be compatible with the type of the array elements.)

The behavior of interpreted code and compiled code is not
indentical, though you should get the same result either way
unless you have designed the classes rather strangely.  The
details will be nailed down later, but the basic idea is that
the compiler will "inline" the @code{invoke-static} call
if it can pick a single "best" matching method.

If the compiler cannot determine the method to call (assuming
the method name is constant), the compiler has to generate code
at run-time to find the correct method.  This is much slower,
so the compiler will print a warning.  To avoid a waning, you can
use a type declaration, or insert a cast:
@example
(invoke (as <java.util.Date> my-date) 'setDate cur-date)
@end example
or
@example
(let ((my-date :: <java.util.Date> (calculate-date))
      (cur-date :: <int> (get-cur-date)))
  (invoke my-date 'setDate cur-date))
@end example
@end defun

@defun invoke-special class receiver-object name arg ...
The @var{class} can be a @code{<java.lang.Class>}, a
@code{<gnu.bytecode.ClassType>}, or a @code{<symbol>} or @code{<string>}
that names a Java class.  
The @var{name} can be @code{<symbol>} or
@code{<string>} that names one or more methods in the Java class.
The name is "mangled" (@pxref{Mangling}) into a valid Java name.

This procedure is very similar to @code{invoke} and @code{invoke-static}
and invokes the specified method, ignoring any methods in subclasses
that might overide it.  One interesting use is to invoke a method in
your super-class like the Java language @code{super} keyword.

Any methods in the specified @var{class} that match "@var{name}" or
"@var{name}$V" collectively form a generic procedure.  That generic
procedure is then applied as in @code{invoke} using the
@code{receiver-object} and the arguments (if any).

The compiler must be able to inline this procedure (because you cannot
force a specific method to be called using reflection).  Therefore the
@var{class} and @var{name} must resolve at compile-time to a specific
method.

@example
(define-simple-class <MyClass> (<java.util.Date>)
  ((get-year) :: <int>
   (+ (invoke-special <java.util.Date> (this) 'get-year)) 1900)
  ((set-year (year :: <int>)) :: <void>
   (invoke-special <java.util.Date> (this) 'set-year (- year 1900))))
@end example
@end defun

@defun class-methods class name
Return a generic function containing those methods of @var{class}
that match the name @var{name}, in the sense of @code{invoke-static}.
Same as:
@example
(lambda args (apply invoke-static (cons class (cons name args))))
@end example
@end defun

Some examples using these functions are @samp{vectors.scm}
and @samp{characters.scm} the directory @samp{kawa/lib} in
the Kawa sources.

@node Field operations, Defining new classes, Method operations, Objects Classes and Modules
@section Accessing fields of Java objects

Kawa has both a high-level interface and a low-level interface for accessing
the fields of Java objects and static fields.
The lower-level interfaces are macros that return functions.
These functions can be inlined, producing efficient code.
The higher-level functions are less verbose and more convenient.
However, they can only access public fields.

@defun field object fieldname
Get the instance field with the given @var{fieldname} from the given
@var{Object}.  Returns the value of the field, which must be public.
This procedure has a @code{setter}, and so can be used as the first
operand to @code{set!}.

The field name is "mangled" (@pxref{Mangling}) into a valid Java name.
If there is no accessible field whose name is @code{"@var{fieldname}"},
we look for a no-argument method whose name is @code{"get@var{Fieldname}"}.

If @var{object} is a primitive Java array, then @var{fieldname} can only
be @code{'length}, and the result is the number of elements of the array.
@end defun

@defun static-field class fieldname
Get the static field with the given @var{fieldname} from the given
@var{class}.  Returns the value of the field, which must be public.
This procedure has a @code{setter}, and so can be used as the first
operand to @code{set!}.
@end defun

Examples:
@example
(static-field <java.lang.System> 'err)
;; Copy the car field of b into a.
(set! (field a 'car) (field b 'car))
@end example

@defun slot-ref object fieldname
A synonym for @code{(field @var{object} @var{fieldname})}.
@end defun

@defun slot-set! object fieldname value
A synonym for @code{(set! (field @var{object} @var{fieldname}) @var{value})}.
@end defun

@node Defining new classes, Anonymous classes, Field operations, Objects Classes and Modules
@section Defining new classes

Kawa provides various mechanisms for defining new classes.
The @code{define-class} and @code{define-simple-class} forms
will usually be the preferred mechanisms.  They have basically
the same syntax, but have a couple of differences.
@code{define-class} allows multiple inheritance as well as true nested
(first-class) class objects.  However, the implementation
is more complex: code using it is slightly slower, and the mapping to
Java classes is a little less obvious.   (Each Scheme class is implemented
as a pair of an interface and an implementation class.)
A class defined by @code{define-simple-class} is slightly more
efficient, and it is easier to access it from Java code.

The syntax of @code{define-class} are mostly compatible with that
in the Guile and Stk dialects of Scheme.

@deffn Syntax define-class name (supers ...) field-or-method-decl ...
@deffnx Syntax define-simple-class name (supers ...) field-or-method-decl ...
@display
@var{field-or-method} ::= @var{field-decl} | @var{method-decl}
@var{field-decl} ::= (@var{fname} [:: @var{ftype}] [@var{option-keyword} @var{option-value}]*)
@var{method-decl} ::= ((@var{method-name} @var{formal-arguments}) [:: @var{rtype}] @var{body})
@end display
Defines a new class named @var{name}.  If @code{define-simple-class} is
used, creates a normal Java class named @var{name} in the current package.
(If @var{name} has the form @code{<xyx>} the Java implementation
type is named @code{xyz}.)  If @code{define-class} the implementation is
unspecified.  In most cases, the compiler creates a class pair,
consisting of a Java interface and a Java implementation class.

The class inherits from the classes and interfaces listed in @var{supers}.
This is a list of names of classes that are in scope (perhaps imported
using @code{require}), or names for existing classes or interfaces
surrounded by @code{<>}, such as @code{<gnu.lists.Sequence>}.
If @code{define-simple-class} is used, at most one of these may be
the name of a normal Java class or classes defined using
@code{define-simple-class}; the rest must be interfaces or classes
defined using @code{define-class}.
If @code{define-class} is used, @emph{all} of the classes listed
in @var{supers} should be interfaces or classes defined using
@code{define-class}.

Each @var{field-decl} declares a public instance "slot" (field)
with the given @var{fname}.  If @var{ftype} is specified it is the
type of the slot.  The following @var{option-keyword}s are implemented:
@table @asis
@item @code{type:} @var{ftype}
Specifies that @var{ftype} is the type of (the values of) the field.
Equivalent to @samp{:: @var{ftype}}.
@item @code{allocation:} @code{class:}
Specifies that there should be a single slot shared between all
instances of the class (and its sub-classes).
Not yet implemented for @code{define-class},
only for @code{define-simple-class}.
In Java terms this is a @code{static} field.
@item @code{allocation:} @code{instance:}
Specifies that each instance has a separate value "slot", and they
are not shared. In Java terms, this is a non-@code{static} field.
This is the default.
@item @code{init-form:} @var{expr}
An expression used to initialize the slot.
The lexical environment of the @var{expr} is that of the @code{define-class}
or @code{define-simple-class}.  (This is not quite true in the current
implementation, as the names of fields and methods of this class are visible.)
@item @code{init-value:} @var{value}
A value expression used to initialize the slot.
For now this is synonymous with @var{init-form:}, but that may change
(depending on what other implementation do), so to be safe only use
@code{init-value:} with a literal.
@item @code{init-keyword:} @code{@var{name}:}
A keyword that that can be used to initialize instance in @code{make} calls.
For now, this is ignored, and @var{name} should be the same as the
field's @var{fname}.
@code{static} field.
@end table

Each @var{method-decl} declares a public non-static method,
whose name is @var{method-name}.  (If @var{method-name} is not a valid
Java method name, it is mapped to something reasonable.
For example @code{foo-bar?} is mapped to @code{isFooBar}.)
The types of the method arguments can be specified in the
@var{formal-arguments}.  The return type can be specified by @var{rtype},
or is otherwise the type of the @var{body}.
Currently, the @var{formal-arguments} cannot contain optional, rest,
or keyword parameters.  (The plan is to allow optional parameters,
implemented using multiple overloaded methods.)

The scope of the @var{body} of a method includes the @var{field-decl}s
of the object.  It does include the surrounding lexical scope.
It sort-of also includes the declared methods, but this is not working yet.
@end deffn

A simple example:
@example
(define-simple-class <2d-vector> ()
  (x type: <double> init-value: 0.0 init-keyword: x:)
  (y type: <double> init-value: 0.0 init-keyword: y:)
  ((add (other :: <2d-vector>)) :: <2d-vector>
   ;; Kawa compiles this using primitive Java types!
   (make <2d-vector>
     x: (+ x (slot-ref other 'x))
     y: (+ y (slot-ref other 'y))))
  ((scale (factor :: <double>)) :: <2d-vector>
   ;; Unfortunately, multiply is not yet optimized as addition is.
   (make <2d-vector> x: (* factor x) y: (* factor y))))

(define-simple-class <3d-vector> (<2d-vector>)
  (z type: <double> init-value: 0.0 init-keyword: z:)
  ((scale (factor :: <double>)) :: <2d-vector>
   ;; Note we cannot override the return type to <3d-vector>
   ;; because Java does not allow that.  Should hide that. .
   (make <3d-vector>
     ;; Unfortunately, slot names of inherited classes are not visible.
     ;; Until this is fixed, use slot-ref.
     x: (* factor (slot-ref (this) 'x))
     y: (* factor (slot-ref (this) 'y))
     z: (* factor z))))
@end example

@node Anonymous classes, Module classes, Defining new classes, Objects Classes and Modules
@section Anonymous classes

@deffn Syntax object (supers ...) field-or-method-decl ...
Returns a new instance of an anonymous (inner) class.
The syntax is similar to @code{define-class}.
@display
@var{field-or-method} ::= @var{field-decl} | @var{method-decl}
@var{field-decl} ::= (@var{fname} [[[::] @var{ftype}] @var{finit}])
    | (@var{fname} [:: @var{ftype}] [@var{option-keyword} @var{option-value}]*)
@var{method-decl} ::= ((@var{method-name} @var{formal-arguments}) [[::] @var{rtype}] @var{body})
@end display

Returns a new instance of a unique (anonymous) class.
The class inherits from the list of @var{supers}, where at most one of the
elements should be the base class being extended from, and the rest
are interfaces.

This is roughly equivalent to:
@example
(begin
  (define-simple-class @var{hname} (@var{supers} ...) @var{field-or-method-decl} ...)
  (make @var{hname}))
@end example

A @var{field-decl} is as for @code{define-class}, except
that we also allow an abbreviated syntax.
Each @var{field-decl} declares a public instance field.
If @var{ftype} is given, it specifies the type of the field.
If @var{finit} is given, it is an expression whose value
becomes the initial value of the field.
The @var{finit} is evaluated at the same time as the @code{object}
expression is evaluated,
in a scope where all the @var{fname}s are visible.

A @var{method-decl} is as for @code{define-class}.
@end deffn

@node Module classes, , Anonymous classes, Objects Classes and Modules
@section Modules and how they are compiled to classes

A @dfn{module} is a set of definitions that the module @dfn{exports},
as well as some @dfn{actions} (expressions evaluated for their side effect).
The top-level forms in a Scheme source file compile a module;
the source file is the @dfn{module source}.
When Kawa compiles the module source, the result is the
@dfn{module class}.  Each exported definition is translated to
a public field in the module class.

There are two kinds of module class:
A @dfn{static module} is a class (or gets compiled to a class)
all of whose public fields a static, and that does not have a
public constructor.  A JVM can only have a single global instance of
a static module.
An @dfn{instance module} has a public default constructor,
and usually has at least one non-static public field.
There can be multiple instances
of an instance module; each instance is called a @dfn{module instance}.
However, only a single instance of a module can be @dfn{registered}
in an environment, so in most cases there is only a single
instance of instance modules.  Registering an instance in an environment
means creating a binding mapping a magic name (derived from the class name)
to the instance.

In fact, any Java class class that has the properties of either
an instance module or a static module, is a module, and can be
loaded or imported as such;  the class need not have written
using Scheme.

@subsection Name visibility

The definitions that a module exports are accessible to other modules.
These are the "public" definitions, to use Java terminology.
By default, all the identifiers declared at the top-level of a module
are exported, except those defined using @code{define-private}.
However, a major purpose of using modules is to control the set of
names exported.  One reason is to reduce the chance of accidental
name conflicts between separately developed modules.  An even more
important reason is to enforce an interface:  Client modules should
only use the names that are part of a documented interface, and should
not use internal implementation procedures (since those may change).

If there is a @code{module-export} declaration in the module, then
only those names listed in a @code{module-export} are exported.
There can be more than one @code{module-export}, and they can be
anywhere in the Scheme file.  As a matter of good style, I recommend
a single @code{module-export} near the beginning of the file.

@deffn Syntax module-export name ...
Make the definition for each @var{name} be exported.
Note that it is an error if there is no definition for @var{name}
in the current module, or if it is defined using @code{define-private}.
@end deffn

In this module, @code{fact} is public and @code{worker} is private:
@example
(module-export fact)
(define (worker x) ...)
(define (fact x) ...)
@end example

Alternatively, you can write:
@example
(define-private (worker x) ...)
(define (fact x) ...)
@end example

@subsection Definitions

In addition to @code{define} (which can take an optional type specifier),
Kawa has some extra definition forms.

@deffn Syntax define-private name [:: type] value
@deffnx Syntax define-private (name formals) body
Same as @code{define}, except that @code{name} is not exported.
@end deffn

@deffn Syntax define-constant name [:: type] value
Definites @var{name} to have the given @var{value}.
The value is readonly, and you cannot assign to it.
(This is not fully enforced.)
If the definition is at module level, then the compiler
will create a @code{final} field with the given name and type.
The @var{value} is evaluated as normal; however, if it is a
compile-time constant, it defaults to being static.
@end deffn

@deffn Syntax define-variable name [init]
If @var{init} is specified and @var{name} does not have a global variable
binding, then @var{init} is evaluated, and @var{name} bound to the result.
Otherwise, the value bound to @var{name} does not change.
(Note that @var{init} is not evaluated
if @var{name} does have a global variable binding.)

Also, declares to the compiler that @var{name} will be looked up
in the dynamic environment. This can be useful for shutting up
warnings from @code{--warn-undefined-variable}.

This is similar to the Common Lisp @code{defvar} form.
However, the Kawa version is (currently) only allowed at module level.
@end deffn

@deffn Syntax define-namespace name namespace-uri
Defines @var{name} as @dfn{namespace alias} - a lexically scoped
"nickname" for the namespace (or package)
whose full name is @var{namespace-uri}, which should be a string literal.
Any symbols in the scope of this definitions that contain a colon, and
where the part before the colon matches the @var{name} will be
treated as being in the package/namespace whose global unique name
is the @var{namespace-uri}.

The features is currently used for XML (to be documented).
In XML terminology, a name containing a colon is a @dfn{qualified name}.
The part of the name before the colon is a @dfn{namespace prefix},
which is an aliases for a locally-visible @dfn{namespace uri}.
The latter is an arbitrary string, but for uniqueness it is
recommended that it be a uri belonging to the organization
that defines the namespace.  (It need to correspond to an
actual browsable location, even though it looks like one.)
The part of a name following the colon is the @var{local part} of the name.

If the namespace starts with the strings @code{"class:"}, then the
@var{name} can be used for invoking Java methods
- @pxref{Method operations}.

@end deffn

@subsection How a module becomes a class

If you want to just use a Scheme module as a module (i.e. @code{load}
or @code{require} it), you don't care how it gets translated
into a module class.  However, Kawa gives you some control over how this
is done, and you can use a Scheme module to define a class which
you can use with other Java classes.  This style of class definition
is an alternative to @code{define-class} [not yet implemented]
which lets you define classes and instances fairly conveniently.

The default name of the module class is the main part of the
filename of the Scheme source file (with directories and extensions
sripped off).  That can be overridden by the @code{-T} Kawa
command-line flag.  The package-prefix specified by the @code{-P}
flag is prepended to give the fully-qualified class name.

@deffn Syntax module-name <name>
Sets the name of the generated class, overriding the default.
If there is no @samp{.} in the @var{name}, the package-prefix
(specified by the @code{-P} Kawa command-line flag) is prepended.
@end deffn

By default, the base class of the generated module class is unspecified;
you cannot count on it being more specific than @code{Object}.
However, you can override it with @code{module-extends}.

@deffn Syntax module-extends <class>
Specifies that the class generated from the immediately surrounding
module should extend (be a sub-class of) the class @code{<@var{class}>}.
@end deffn

@deffn Syntax module-implements <interface> ...
Specifies that the class generated from the immediately surrounding
module should implement the interfaces listed.
@end deffn

Note that the compiler does @emph{not} currently check that all the
abstract methods requires by the base class or implemented interfaces
are actually provided, and have the correct signatures.  This will
hopefully be fixed, but for now, if you are forgot a method, you will
probably get a verifier error

For each top-level exported definition the compiler creates a
corresponding public field with a similar (mangled) name.
By default, there is some indirection:  The value of the Scheme variable
is not that of the field itself.  Instead, the field is a
@code{gnu.mapping.Symbol} object, and the value Scheme variable is
defined to be the value stored in the @code{Symbol}.
Howewer, if you specify an explicit type, then the field will
have the specified type, instead of being a @code{Symbol}.
The indirection using @code{Symbol} is also avoided if you use
@code{define-constant}.

If the Scheme definition defines a procedure (which is not re-assigned
in the module), then the compiler assumes the variable as bound as a
constant procedure.  The compiler generates one or more methods
corresponding to the body of the Scheme procedure. It also generates
a public field with the same name; the value of the field is an
instance of a subclass of @code{<gnu.mapping.Procedure>} which when
applied will execute the correct method (depending on the actual arguments).
The field is used when the procedure used as a value (such as being passed
as an argument to @code{map}), but when the compiler is able to do so,
it will generate code to call the correct method directly.

You can control the signature of the generated method by declaring
the parameter types and the return type of the method.  See the
applet (@pxref{Applet compilation}) example for how this can be done.
If the procedures has optional parameters, then the compiler will
generate multiple methods, one for each argument list length.
(In rare cases the default expression may be such that this is
not possible, in which case an "variable argument list" method
is generated instead.  This only happens when there is a nested
scope @emph{inside} the default expression, which is very contrived.)
If there are @code{#!keyword} or @code{#!rest} arguments, the compiler
generate a "variable argument list" method.  This is a method whose
last parameter is either an array or a @code{<list>}, and whose
name has @code{$V} appended to indicate the last parameter is a list.

Top-leval macros (defined using either @code{define-syntax}
or @code{defmacro}) create a field whose type is currently a sub-class of
@code{kawa.lang.Syntax};  this allows importing modules to detect
that the field is a macro and apply the macro at compile time.

@deffn Syntax module-static name ...
@deffnx Syntax module-static @code{#t}
@deffnx Syntax module-static @code{#f}
Control whether the generated fields and methods are static.
If @code{#t} is specified, then the module will be a static module,
@emph{all} definitions will be static, and the module body is evaluated
in the class's static initializer.
Otherwise, the module is an instance module.  However, the @var{name}s
that are explicitly listed will be compiled to static fields and methods.
If @code{#f} is specified, then all exported names will be compiled
to non-static (instance) fields and methods.

By default, if no @code{module-static} is specified, the following rules apply:
@enumerate
@item
If there is a @code{module-extends} or @code{module-implements}
declaration, then @code{(module-static #f)} is implied.
@item
If the @code{--module-static} command-line parameter is specified,
then @code{(module-static #t)} is implied.
@item
(Not yet implemented: If there are no top-level actions and all
definitions are procedure definitions, macro definitions, or
constant definitions, then @code{(module-static #t)} is implied.)
@item
Otherwise, a method will be static iff it doesn't need to reference non-static
fields or methods of the module instance.  In that case, the corresponding
field will also be static.
@end enumerate

Note @code{(module-static #t)} usually produces more efficient
code, and is recommended if a module contains only procedure or macro
definitions.  (This may become the default.)
However, a static module means that all environments in a JVM
share the same bindings, which you may not want if you use
multiple top-level environments.
@end deffn

Unfortuntely, the Java class verifier does not allow fields to have
arbitrary names.  Therefore, the name of a field that represents a
Scheme variable is "mangled" (@pxref{Mangling}) into an acceptable Java name.
The implementation can recover the original name of a field @code{X}
as @code{((gnu.mapping.Named) X).getName()} because all the standard
compiler-generate field types implemented the @code{Named} interface.

The top-level actions of a module will get compiled to a @code{run}
method.  If there is an explicit @code{method-extends}, then the
module class will also automatically implement @code{java.lang.Runnable}.
(Otherwise, the class does not implement @code{Runnable}, since in that
case the @code{run} method return an @code{Object} rather than @code{void}.
This will likely change.)

@subsection Requiring (importing) a module

You can import a module into the current namespace with @code{require}.

@deffn Syntax require modulespec
The @var{modulespec} can be either a @code{<@var{classname}>}
or a @code{'@var{featurename}}.  In either case the names
exported by the specified module (class) are added to the current
set of visible names.

If @var{modulespec} is @code{<@var{classname}>} where @var{classname}
is an instance module (it has a public default constructor),
and if no module instance for that class
has been registered in the current environment, then a new instance
is created and registered (using a "magic" identifier).
If the module class either inherits from @code{gnu.expr.ModuleBody}
or implements @code{java.lang.Runnable} then the corresponding @code{run}
method is executed.  (This is done @emph{after} the instance is
registered so that cycles can be handled.)  These actions (creating,
registering, and running the module instance) are done both at compile
time and at run time, if necessary.

All the public fields of the module class are then incorporated
in the current set of local visible names in the current module.
This is done at compile time - no new bindings are created at run-time
(except for the magic binding used to register the module instance),
and the imported bindings are private to the current module.
References to the imported bindings will be compiled as field
references, using the module instance (except for static fields).

If the @var{modulespec} is @code{'@var{featurename}} then the
@var{featurename} is looked up (at compile time) in the "feature table"
which yields the implementing @code{<@var{classname}>}.
@end deffn

For some examples, you may want to look in the @code{gnu/kawa/slib}
directory.

@node Low-level functions, XML tools, Objects Classes and Modules, Top
@chapter The Scheme-Java interface

Kawa has extensive features so you can work with Java objects
and call Java methods.

@menu
* Scheme types in Java::
* Array operations::      Low-level operations on Java arrays
* Low-level Method invocation::
* Low-level Field operations::
* Loading Java functions into Scheme::
* Evaluating Scheme expressions from Java::
@end menu

@node Scheme types in Java, Array operations, Low-level functions, Low-level functions
@section Scheme types in Java

All Scheme values are implemented by sub-classes of @samp{java.lang.Object}.

Scheme symbols are implemented using @code{java.lang.String}.
(Don't be confused by the fact the Scheme sybols are represented
using Java Strings, while Scheme strings are represented by
@code{gnu.lists.FString}.  It is just that the semantics of Java strings
match Scheme symbols, but do not match mutable Scheme strings.)
Interned symbols are presented as interned Strings.
(Note that with JDK 1.1 string literals are automatically interned.)

Scheme integers are implemented by @code{gnu.math.IntNum}.
Use the make static function to create a new IntNum from an int or a long.
Use the intValue or longValue methods to get the int or long value of
an IntNum.

A Scheme "flonum" is implemented by @code{gnu.math.DFloNum}.

A Scheme pair is implemented by @code{gnu.lists.Pair}.

A Scheme vector is implemented by @code{gnu.lists.FVectror}.

Scheme characters are implemented using @code{gnu.text.Char}.

Scheme strings are implemented using @code{gnu.lists.FString}.

Scheme procedures are all sub-classes of @code{gnu.mapping.Procedure}.
The "action" of a @samp{Procedure} is invoked by using one of
the @samp{apply*} methods:  @samp{apply0}, @samp{apply1},
@samp{apply2}, @samp{apply3}, @samp{apply4}, or @samp{applyN}.
Various sub-class of @samp{Procedure} provide defaults
for the various @samp{apply*} methods.  For example,
a @samp{Procedure2} is used by 2-argument procedures.
The @samp{Procedure2} class provides implementations of all
the @samp{apply*} methods @emph{except} @samp{apply2},
which must be provided by any class that extends @code{Procedure2}.

@node Array operations, Low-level Method invocation, Scheme types in Java, Low-level functions
@section Low-level Operations on Java Arrays

The following macros evaluate to procedures that can be used to
manipulate primitive Java array objects.
The compiler can inline each to a single bytecode instruction
(not counting type conversion).

@deffn Syntax primitive-array-new element-type
Evaluates to a one-argument procedure.  Applying the resulting procedure to
an integer count allocates a new Java array of the specified length,
and whose elements have type @var{element-type}.
@end deffn

@deffn Syntax primitive-array-set element-type
Evaluates to a three-argument procedure.  The first argument of
the resulting procedure must be an array whose elements have type
@var{element-type};  the second argument is an index;  and the third
argument is a value (coercible to @var{element-type}) which replaces
the value specified by the index in the given array.
@end deffn

@deffn Syntax primitive-array-get element-type
Evaluates to a two-argument procedure.  The first argument of
the resulting procedure must be an array whose elements have type
@var{element-type};  the second argument is an index.
Applying the procedure returns the element at the specified index.
@end deffn

@deffn Syntax primitive-array-length element-type
Evaluates to a one-argument procedure.  The argument of
the resulting procedure must be an array whose elements have type
@var{element-type}.
Applying the procedure returns the length of the array.
(Alternatively, you can use @code{(field @var{array} 'length)}.)
@end deffn

@node Low-level Method invocation, Low-level Field operations, Array operations, Low-level functions
@section Low-level Method invocation

The following lower-level primitives require you to specify
the parameter and return types explicitly.
You should probably use the functions @code{invoke} and @code{invoke-static}
(@pxref{Method operations}) instead.

@deffn Syntax primitive-constructor class (argtype ...)
Returns a new anonymous procedure, which when called will create
a new object of the specified class, and will then call the
constructor matching the specified argument types.
@end deffn

@deffn Syntax primitive-virtual-method class method rtype (argtype ...)
Returns a new anonymous procedure, which when called will
invoke the instance method whose name is the string @var{method}
in the class whose name is @var{class}.
@end deffn

@deffn Syntax primitive-static-method class method rtype (argtype ...)
Returns a new anonymous procedure, which when called will
invoke the static method whose name is the string @var{method}
in the class whose name is @var{class}.
@end deffn

@deffn Syntax primitive-interface-method interface method rtype (argtype ...)
Returns a new anonymous procedure, which when called will
invoke the matching method from the interface whose name is @var{interface}.
@end deffn

The macros return procedure values, just like @code{lambda}.
If the macros are used directly as the procedure of a procedure call,
then kawa can inline the correct bytecodes to call the specified methods.
(Note also that neither macro
checks that there really is a method that matches the specification.)
Otherwise, the Java reflection facility is used.

@node Low-level Field operations, Loading Java functions into Scheme, Low-level Method invocation, Low-level functions
@section Low-level Operations on Object Fields

The following macros evaluate to procedures that can be used to
access or change the fields of objects or static fields.
The compiler can inline each to a single bytecode instruction
(not counting type conversion).

These macros are deprecated.
The @code{fields} and @code{static-field} functions
(@pxref{Field operations}) are easier to use, more powerful, and
just as efficient.  (One exception is for @code{primitive-set-static};
while its functionality can be expressed using
@code{(set! (static-field ...) ...)}, that idiom is currently
less efficient.)  Also, the high-level functions currently do
not provide access to private fields.

@deffn Syntax primitive-get-field class fname ftype
Use this to access a field named @var{fname} having type @var{type} in
class @var{class}.  Evaluates to a new one-argument procedure,
whose argument is a reference to an object of the specified @var{class}.
Calling that procedure returns the value of the specified field.
@end deffn

@deffn Syntax primitive-set-field class fname ftype
Use this to change a field named @var{fname} having type @var{type} in
class @var{class}.  Evaluates to a new two-argument procedure,
whose first argument is a reference to an object of the
specified @var{class}, and the second argument is the new value.
Calling that procedure sets the field to the specified value.
(This macro's name does not end in a @samp{!}, because it does not actually
set the field.  Rather, it returns a function for setting the field.)
@end deffn

@deffn Syntax primitive-get-static class fname ftype
Like @code{primitive-get-field}, but used to access static fields.
Returns a zero-argument function, which when called returns
the value of the static field.
@end deffn

@deffn Syntax primitive-set-static class fname ftype
Like @code{primitive-set-field}, but used to modify static fields.
Returns a one-argument function, which when called sets the
value of the static field to the argument.
@end deffn

@node Loading Java functions into Scheme, Evaluating Scheme expressions from Java, Low-level Field operations, Low-level functions
@section Loading Java functions into Scheme

When @code{kawa -C} compiles (@pxref{Files compilation}) a Scheme module
it creates a class that implements the @code{java.lang.Runnable} interface.
(Usually it is a class that extends the @code{gnu.expr.ModuleBody}.)
It is actually fairly easy to write similar "modules" by hand in Java,
which is useful when you want to extend Kawa with  new "primitive functions"
written in Java.  For each function you need to create an object that
extends @code{gnu.mapping.Procedure}, and then bind it in the global
environment.  We will look at these two operations.

There are multiple ways you can create a @code{Procedure} object.  Below
is a simple example, using the @code{Procedure1} class, which is class
extending @code{Procedure} that can be useful for one-argument
procedure.  You can use other classes to write procedures.  For example
a @code{ProcedureN} takes a variable number of arguments, and you must
define @code{applyN(Object[] args)} method instead of @code{apply1}.
(You may notice that some builtin classes extend @code{CpsProcedure}.
Doing so allows has certain advantages, including support for
full tail-recursion, but it has some costs, and is a bit trickier.)

@example
import gnu.mapping.*;
import gnu.math.*;
public class MyFunc extends Procedure1
@{
  // An "argument" that is part of each procedure instance.
  private Object arg0;

  public MyFunc(String name, Object arg0)
  @{
    super(name);
    this.arg0 = arg0;
  @}

  public Object apply1 (Object arg1)
  @{
    // Here you can so whatever you want. In this example,
    // we return a pair of the argument and arg0.
    return gnu.lists.Pair.make(arg0, arg1);
  @}
@}
@end example

You can create a @code{MyFunc} instance and call it from Java:
@example
  Procedure myfunc1 = new MyFunc("my-func-1", Boolean.FALSE);
  Object aresult = myfunc1.apply1(some_object);
@end example
The name @code{my-func-1} is used when @code{myfunc1} is printed
or when @code{myfunc1.toString()} is called.  However,
the Scheme variable @code{my-func-1} is still not bound.
To define the function to Scheme, we can create
a "module", which is a class intended to be loaded
into the top-level environment.  The provides the definitions to be
loaded, as well as any actions to be performed on loading 

@example
public class MyModule
@{
  // Define a function instance.
  public static final MyFunc myfunc1
    = new MyFunc("my-func-1", IntNum.make(1));
@}
@end example

If you use Scheme you can use @code{require}:
@example
#|kawa:1|# (require <MyModule>)
#|kawa:2|# (my-func-1 0)
(1 0)
@end example

Note that @code{require} magically defines @code{my-func-1} without
you telling it to.  For each public final
field, the name and value of the field are entered in the
top-level environment when the class is loaded.  (If there are
non-static fields, or the class implements @code{Runnable}, then
an instance of the object is created, if one isn't available.)
If the field value is a @code{Procedure} (or implements @code{Named}),
then the name bound to the procedure is used instead of the field name.
That is why the variable that gets bound in the Scheme environment is
@code{my-func-1}, not @code{myfunc1}.

Instead of @code{(require <MyModule>)}, you can do @code{(load "MyModule")}
or @code{(load "MyModule.class")}.
If you're not using Scheme, you can use Kawa's @code{-f} option:
@example
$ kawa -f MyModule --xquery --
#|kawa:1|# my-func-1(3+4)
<list>1 7</list>
@end example

If you need to do some more complex calculations when a module is loaded,
you can put them in a @code{run} method, and have the module
implement @code{Runnable}:

@example
public class MyModule implements Runnable
@{
  public void run ()
  @{
    Interpreter interp = Interpreter.getInterpreter();
    Object arg = Boolean.TRUE;
    interp.defineFunction (new MyFunc ("my-func-t", arg));
    System.err.println("MyModule loaded");
  @}
@}
@end example

Loading @code{MyModule} causes @code{"MyModule loaded"} to be printed,
and @code{my-func-t} to be defined.  Using @code{Interpreter}'s
@code{defineFunction} method is recommended because it does the righ
things even for languages like Common Lisp that use separate
"namespaces" for variables and functions.

A final trick is that you can have a @code{Procedure} be its own module:

@example
import gnu.mapping.*;
import gnu.math.*;
public class MyFunc2 extends Procedure2
@{
  public MyFunc(String name)
  @{
    super(name);
  @}

  public Object apply2 (Object arg1, arg2)
  @{
    return gnu.lists.Pair.make(arg1, arg2);
  @}

  public static final MyFunc myfunc1 = new MyFunc("my-func-2);
@}
@end example

@node Evaluating Scheme expressions from Java,  , Loading Java functions into Scheme, Low-level functions
@section Evaluating Scheme expressions from Java

The following methods are recommended if you need to evaluate a
Scheme expression from a Java method.
(Some details (such as the @samp{throws} lists) may change.)

@deftypefn {Static method} void Scheme.registerEnvironment ()
Initializes the Scheme environment.  Maybe needed if you
try to load a module compiled from a Scheme source file.
@end deftypefn

@deftypefn {Static method} Object Scheme.eval (InPort @var{port}, Environment @var{env})
Read expressions from @var{port}, and evaluate them in the
@var{env} environment, until end-of-file is reached.
Return the value of the last expression,
or @code{Interpreter.voidObject} if there is no expression.
@end deftypefn

@deftypefn {Static method} Object Scheme.eval (String @var{string}, Environment @var{env})
Read expressions from @var{string}, and evaluate them in the
@var{env} environment, until the end of the string is reached.
Return the value of the last expression,
or @code{Interpreter.voidObject} if there is no expression.
@end deftypefn

@deftypefn {Static method} Object Scheme.eval (Object @var{sexpr}, Environment @var{env})
The @var{sexpr} is an S-expression (as may be returned by @code{read}).
Evaluate it in the @var{env} environment, and return the result.
@end deftypefn

For the @code{Environment} in most cases you could use
@samp{Environment.current()}.  Before you start, you
need to initialize the global environment,
which you can with
@example
Environment.setCurrent(new Scheme().getEnvironment());
@end example

Alternatively, rather than setting the global environment,
you can use this style:
@example
Scheme scm = new Scheme();
Object x = scm.eval("(+ 3 2)");
System.out.println(x);
@end example

@node XML tools, KRL, Low-level functions, Top
@chapter Tools for working with XML and HTML

Kawa has a number of experimental features for working with XML.
These are built on the concepts of the @code{gnu.lists} package.

@menu
* Server-side scripts::  Writing web-server-side Kawa scripts
* Servlets::             Installing Kawa programs as Servlets
* CGI scripts::          Installing Kawa programs as CGI scripts
* HTTP requests::        Functions for accessing HTTP requests
* HTTP response::        Functions for generating HTTP response
@end menu

@subsection Scheme functions

@defun make-element tag [attribute ...] child ...
Create a representation of a XML element, corresponding to
@example
<@var{tag} @var{attribute}...>@var{child}...</@var{tag}>
@end example
The result is a @code{TreeList}, though if the result context is a consumer
the result is instead "written" to the consumer.
Thus nested calls to @code{make-element} only result in a
single @code{TreeList}.
More generally, whether an @var{attribute} or @var{child} is includded
by copying or by reference is (for now) undefined.
The @var{tag} should currently be a symbol, though in the future it should
be a qualified name.
An @var{attribute} is typically a call to @code{make-attribute},
but it can be any attribute-valued expression.
@example
(make-element 'p
	      "The time is now: "
	      (make-element 'code (make <java.util.Date>)))
@end example
@end defun

@defun make-attribute name value...
Create an "attribute", which is a name-value pair.
For now, @var{name} should be a symbol
@end defun

@defun as-xml value
Return a value (or multiple values) that when printed will
print @var{value} in XML syntax.
@example
(require 'xml)
(as-xml (make-element 'p "Some " (make-element 'em "text") "."))
@end example
prints @code{<p>Some <em>text</em>.</p>}.
@end defun

@subsection xquery language

W3C is working an an @uref{http://www.w3c.org/XML/Query,XML Query language},
and a draft has been released.
If you start Kawa with the @code{--xquery} it selects the "XQuery"
source language; this also prints output using XML syntax.
See the @uref{http://www.gnu.org/software/qexo/,Qexo (Kawa-XQuery) home page}
for examples and more information.

@subsection XSL transformations

There is an experimental implementation of the XSLT (XML Stylesheet
Language Transformations) language.  Selecting @code{--xslt} at the
Kawa command line will parse a source file according to the syntax
on an XSLT stylesheet.
See the @uref{http://www.gnu.org/software/qexo/xslt.html,Kawa-XSLT page}
for more information.

@node Server-side scripts, Servlets, , XML tools
@section Writing web-server-side Kawa scripts

You can compile a Kawa program (written in any supported
Kawa language, including Scheme, BRL, KRL, or XQuery),
and run it as either servlet engine (using a web server
that supports servlets), or as a "CGI script" on most web servers.

In either case, the result of evaluating the top-level expressions
becomes the HTTP response that the servlet sends back to the browser.
The result is typically an HTML/XML element code object;
Kawa will automatically format the result as appropriate for the type.
The initial result values may be special "response header values",
as created by the @code{response-header} function.
Kawa will use the response header values to set various
required and optional fields of the HTTP response.
Note that @code{response-header} does not actually do anything
until it is "printed" to the standard output.
Note also that if a @code{"Content-Type"} response value is
printed that controls the formatting of the following
non-response-header values.

Here is a simple program @code{hello.scm}:
@example
(require 'http) ; Required for Scheme, though not BRL/KRL.
(response-content-type 'text/html) ; Optional
(make-element 'p
  "The request URL was: " (request-url))
(make-element 'p
  (let ((query (request-query-string)))
    (if query
      (values-append "The query string was: " query)
      "There was no query string.")))
#\newline ; emit a new-line at the end
@end example

The same program using KRL is shorter:
@example
<p>The request URL was: [(request-url)]</p>,
<p>[(let ((query (request-query-string)))
    (if query
      (begin ]The query string was: [query)
      ]There was no query string.[))]</p>
@end example

You can also use XQuery:
@example
<p>The request URL was: @{request-url()@}</p>
<p>@{let $query := request-query-string() return
    if ($query)
    then ("The query string was: ",$query)
    else "There was no query string."@}</p>
@end example

Either way, you compile your program to a servlet:
@example
kawa --servlet -C hello.scm
@end example
or:
@example
kawa --servlet --krl -C hello.krl
@end example
or:
@example
kawa --servlet --xquery -C hello.xql
@end example

The next two sections will explain how you can install this script
as either a servlet or a CGI script.

@node Servlets, CGI scripts, Server-side scripts, XML tools
@section Installing Kawa programs as Servlets

You can compile a Kawa program to a @code{Servlet}, and run it
in a servlet engine (a Servlet-aware web server).
I assume you have compiled your program to a servlet as
descrbibed in the previous section.

If you have Tomcat 4.x installed, and you want @code{hello} to be
part of the @code{myutils} "web application", copy @code{hello*.class}
into @code{$CATALINA_HOME/webapps/myutils/WEB-INF/classes/}.
You also need to copy Kawa somewhere where Tomcat can find it,
for example @code{$CATALINA_HOME/lib/kawa-@value{VERSION}.jar}.
You can then run the @code{hello} servlet using the URL
@url{http://localhost:8080/myutils/servlet/hello}.

@defun current-servlet
When called from a Kawa servlet's handler, returns the
actual @code{javax.servlet.http.HttpServlet} instance.
@end defun

@defun current-servlet-context
Returns the @code{ServletContext} of the currently executing servlet.
@end defun

@defun current-servlet-config
Returns the @code{ServletConfig} of the currently executing servlet.
@end defun

@defun servlet-context-realpath
Returns the file path of the current servlet's "Web application".
@end defun

@node CGI scripts, HTTP requests, Servlets, XML tools
@section Installing Kawa programs as CGI scripts

The recommended way to have a web-server run a Kawa program
as a CGI script is to compile the Kawa program to a servlet
(as explained in @ref{Server-side scripts}, and then use
Kawa's supplied CGI-to-servlet bridge.

First, compile your program to one or more class files
as explain in @ref{Server-side scripts}.  For example:
@example
kawa --servlet --xquery -C hello.xql
@end example

Then copy the resulting @code{.class} files to your server's
CGI directory.  On Red Hat GNU/Linux, you can do the following (as root):
@example
cp hello*.class /var/www/cgi-bin/
@end example

Next find the @code{cgi-servlet} program that Kawa builds and installs.
If you installed Kawa in the default place, it will be in
@code{/usr/local/bin/cgi-servlet}.
(You'll have this if you installed Kawa from source, but not
if you're just using Kawa @code{.jar} file.)
Copy this program into the same CGI directory:
@example
cp /usr/local/bin/cgi-servlet /var/www/cgi-bin/
@end example

You can link instead of copying:
@example
ln -s /usr/local/bin/cgi-servlet /var/www/cgi-bin/
@end example
However, because of security issues this may not work, so it is
safer to copy the file.  However, if you already have a copy
of @code{cgi-servlet} in the CGI-directory, it is safe to make
a hard link instead of making an extra copy.

Make sure the files have the correct permissions:
@example
chmod a+r /var/www/cgi-bin/hello*.class /var/www/cgi-bin/hello
chmod a+x /var/www/cgi-bin/hello
@end example

Now you should be able to run the Kawa program,
using the URL @url{http://localhost/cgi-bin/hello}.
It may take a few seconds to get the reply, mainly because of the
start-up time of the Java VM.  That is why servlets are
preferred.  Using the CGI interface can still be useful
for testing or when you can't run servlets.  We hope to
soon be able to run Kawa CGI scripts compiled using GCJ,
which should have much reduced start-up time, making
Kawa servlets more practical.

@node HTTP requests, HTTP response, CGI scripts, XML tools
@section Functions for accessing HTTP requests

The following functions are useful for accessing
properties of a HTTP request, in a Kawa program that is
run either as a servlet or a CGI script.  These functions
can be used from plain Scheme, from KRL (whether
in BRL-compatible mode or not), and from XQuery.

If using plain Scheme, you need to do the following
before using these functions.
@example
(require 'http)
@end example
This is not needed for KRL or XQuery.

@defun request-method
Returns the method of the HTTP request, usually @code{"GET"}
or @code{"POST"}.  Corresponds to the CGI variable @code{REQUEST_METHOD}.
@end defun

@defun request-path-info
Corresponds to the CGI variable @code{PATH_INFO}.
@end defun

@defun request-path-translated
Corresponds to the CGI variable @code{PATH_TRANSLATED}.
@end defun

@defun request-uri
Returns the URI of the request, not including the query string,
or server specification.
The is the combination of CGI variables @code{SCRIPT_NAME}
and @code{PATH_INFO}.
@end defun

@defun request-url
Returns the complete URL of the request, except the query string.
@end defun

@defun request-query-string
Returns the query string from an HTTP request.  The query string is
the part of the request URL after a quetion mark.
Returns false if there was no query string.
Corresponds to the CGI variable @code{QUERY_STRING}.
@end defun

@node HTTP response, , HTTP requests, XML tools
@section Functions for generating HTTP responses

@defun unescaped-data data
Creates a special value which causes @code{data} to be printed,
as is, without normal escaping.  For example, when the output format
is XML, then printing @code{"<?xml?>"} prints as @samp{&lt;?xml?&gt;},
but @code{(unescaped-data "<?xml?>")} prints as  @samp{<?xml?>}.
@end defun

If using plain Scheme, you need to do the following
before using these functions.
@example
(require 'http)
@end example
This is not needed for KRL or XQuery.

@defun response-header key value
Create the response header @samp{@var{key}: @var{value}} in the HTTP
response.  The result is a "response header value" (of some unspecified
type).  It does not directly set or print a response header, but only
does so when you actually "print" its value to the response output stream.
@end defun

@defun response-content-type type
Species the content-type of the result - for example @code{"text/plain"}.
Convenience function for @code{(response-header "Content-Type" @var{type})}.
@end defun

@defun error-response code [message]
Creates a response-header with an error code of @var{code} and a
response message of @var{message}.
(For now this is the same as @code{response-status}.)

Note this also returns a response-header value, which does not actually
do anything unless it is returned as the result of executing a servlet body.
@end defun

@defun response-status code [message]
Creates a response-header with an status code of @var{code} and a
response message of @var{message}.
(For now this is the same as @code{error-response}.)
@end defun

@node KRL, Mailing lists,  XML tools, Top
@chapter KRL - The Kawa Report Language for generating XML/HTML

KRL (the "Kawa Report Language") is powerful Kawa dialect for embedding
Scheme code in text files such as HTML or XML templates.  You select
the KRL language by specifying @code{--krl} on the Kawa command line.

KRL is based on on @uref{http://brl.sourceforge.net/,BRL},
Bruce Lewis's "Beautiful Report Language", and
uses some of BRL's code, but there are some experimental differences,
and the implementation core is different.  You can run KRL in
BRL-compatility-mode by specifying @code{--brl} instead of @code{--krl}.

@section Differences between KRL and BRL

This section summarizes the known differences between KRL and BRL.
Unless otherwise specified, KRL in BRL-compatibility mode will
act as BRL.

@itemize @bullet
@item
In BRL a normal Scheme string @code{"mystring"} is the same
as the inverted quote string @code{]mystring[}, and both are instances
of the type @code{<string>}.
In KRL @code{"mystring"} is a normal Scheme string of type @code{<string>},
but @code{]mystring[} is special type that suppresses output escaping.
(It is equivalent to @code{(unescaped-data "mystring")}.)
@item
When BRL writes out a string, it does not do any processing
to escape special characters like @code{<}.  However, KRL in its default
mode does normally escape characters and strings.  Thus @code{"<a>"}
is written as @code{&lt;a&gr;}.
You can stop it from doing this by overriding the output format, for example
by specifying @code{--output-format scheme} on the Kawa command line,
or by using the @code{unescaped-data} function.
@item
Various Scheme syntax forms, including @code{lambda},
take a @code{<body>}, which is a list of one or more declarations and
expressions.  In normal Scheme and in BRL the value of a @code{<body>}
is the value of the last expression.  In KRL the value of a @code{<body>}
is the concatenation of all the values of the expressions,
as if using @code{values-append}.
@item
In BRL a word starting with a colon is a keyword.
In KRL a word starting with a colon is an identifier, which by
default is bound to the @code{make-element} function specialized
to take the rest of the word as the tag name (first argument).
@item
BRL has an extensive utility library.  Most of this has not yet been ported
to KRL, even in BRL-compatibility mode.
@end itemize

@node Mailing lists, Support, KRL, Top
@chapter Where to report bugs, discuss changes, etc

@section Reporting bugs

To report a bug or feature request for Kawa (including Qexo or JEmacs), it is
best to use the @uref{http://savannah.gnu.org/bugs/?func=addbug&group=kawa,
bug-submission page}.
You can browse and comment on existing bug reports
using the @uref{http://savannah.gnu.org/bugs/?group=kawa, Kawa Bugzilla page}.

When a bug report is created or modified, mail is automatically sent to the
@email{bug-kawa@@gnu.org} list.  You can subscribe, unsubscribe, or browse
the archives through the
@uref{http://mail.gnu.org/mailman/listinfo/bug-kawa,
@code{bug-kawa} web interface}.

@section General Kawa email and discussion

The general Kawa email list is @email{kawa@@sources.redhat.com}.
This mailing list is used for announcements, questions, patches,
and general discussion relating to Kawa.  If you wish to subscribe,
send a blank message request to @email{kawa-subscribe@@sources.redhat.com}.
To unsubscribe, send a blank message to
@email{kawa-unsubscribe@@sources.redhat.com}.
(If your mail is forwarded and you're not sure which email address you're
subscribed as send mail to the address following @code{mailto:} in the
@code{List-Unsubscribe} line in the headers of the messages you get from
the list.)

You can browse the @uref{http://sources.redhat.com/ml/kawa/,
archive of past messages}.

There are separate mailing lists for
@uref{http://mail.gnu.org/mailman/listinfo/qexo-general, Qexo}
and @uref{http://lists.sourceforge.net/mailman/listinfo/jemacs-info,JEmacs}.


@node Support, Projects, Mailing lists, Top
@chapter Technical Support for Kawa

If you have a project that depends on Kawa or one of its component
packages, you might do well get get paid priority support from
Kawa's author.

The base price is $2400 for one year.  This entitles you to basic
support by email or phone.  Per @email{per@@bothner.com} will answer techical
questions about Kawa or its implementation, investigate bug reports, and
suggest work-arounds.  I may (at my discretion) provide fixes and
enhancements (patches) for simple problems.  Reponse for support
requests received using the day (California time) will normally be
within a few hours.

All support requests must come through a single designated contact
person.  If Kawa is important to your business, you probably
want at least two contact people, doubling the price.

If the support contract is cancelled (by either party), remaining
time will be prorated and refunded.

Per is also available for development projects.

@node Projects, License, Support, Top
@chapter Projects using Kawa

JEmacs is included in the Kawa distribution.  It is a project to
re-implement Emacs, allowing a mix of Java. Scheme, and Emacs Lisp.
It has its own @uref{http://www.jemacs.net/,home-page}.

BRL ("the Beautiful Report Language") is a database-oriented language
to embed in HTML and other markup.
@uref{http://brl.sourceforge.net/, BRL} allows you to embed Scheme in
a an HTML file on a web server.

The Health Media Research Laboratory, part of the Comprehensive Cancer
Center at the University of Michigan, is using Kawa as an integral part of
its core tailoring technologies. Java programs using Kawa libraries are used
to administer customized web-based surveys, generate tailored feedback,
validate data, and "characterize," or transform, data. Kawa code is embedded
directly in XML-formatted surveys and data dictionaries. Performance and
ease of implementation has far exceeded expectations. For more information
contact Paul R. Potts, Technical Director, Health Media Research Lab,
@code{<potts@@umich.edu>}.

Mike Dillon (@code{mdillon@@gjt.org})
did the preliminary work of creating a
Kawa plugin for jEdit. It is called SchemeShell and provides a REPL inside
of the jEdit console for executing expressions in Kawa (much as the BeanShell
plugin does with the BeanShell scripting language).
It is currently available only via CVS from:
@example
CVSROOT=:pserver:anonymous@@cvs.jedit.sourceforge.net:/cvsroot/jedit
MODULE=plugins/SchemeShell
@end example

STMicroelectronics (@code{marco.vezzoli@@st.com})
uses Kawa in a prototypal
intranet 3tier information retrival system as a communication protocol
between server and clients and to do server agents programming.

The Nice Programming Language is an open source research language that
has a Java-like syntax.
It features multiple dispatch methods, parametric types, higher-order
functions, tuples, ..., and the new concept of "abstract interfaces". 
The Nice compiler (@code{nicec}) uses Kawa's @code{gnu.expr}
and @code{gnu.bytecode}
packages to generate Java bytecode. 
You can find more about Nice at @uref{http://nice.sourceforge.net}.
For more information feel free to contact
Daniel Bonniot (@w{@code{d.bonniot@@mail.dotcom.fr}}).

@node License, Overall Index, Projects, Top
@chapter License

@section License for the Kawa software

The license for Kawa and the packages it depends on
is a "modified Gnu Public License".  You can find it in
the file @code{COPYING} in the Kawa sources, and
also quoted here:.

@example
The Java classes (with related files and documentation) in these packages
are copyright (C) 1996, 1997, 1998, 1999  Per Bothner.

These classes are distributed in the hope that they 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.

These classes are free software.  You can use and re-distribute a class
without restriction (in source or binary form) as long as you use a
version that has not been modified in any way from a version released
by Per Bothner, Red Hat inc, or the Free Software Foundation.
You may make and distribute a modified version, provided you follow
the terms of the GNU General Public License; either version 2,
or (at your option) any later version.
@end example

The file @code{COPYING} also contains a copy of the
GNU General Public License version 2.

People have asked what the Kawa license means in practice.
Informally, you get to pick between these choices:
@enumerate
@item
Use Kawa as distributed by Per Bothner, Red Hat Inc, or the
Free Software Foundation (or their approved agents),
with no modifications.  In that case, you can use Kawa for any
purpose you like, and distribute your application with any license
you like.  (This basically gives you the same rights as
a typical commercial royalty-free re-distribution license.)
@item
Obey the terms of the standard Gnu Public License.  (See
@uref{http://www.gnu.org/copyleft/gpl.html}).  Informally, this means
that if you distribute any application that is based on Kawa, you must
also make available to all your recipients (customers) the source code
for your entire application, giving them the modification and
re-distribution rights they have under the GPL.  In a Java context, I take
"entire application" to mean all classes (and native code) that run in
the same Java virtual machine, except for the Java runtime system itself
(the virtual machine, low-level run-time system, and any classes in
a @code{java} or @code{javax} package).
@item
If you need to make a change to Kawa, you can submit them to Per Bothner,
and convince him to include them in future Kawa releases.
@item
You can negotiate some other (commercial) license with Per Bothner.
@end enumerate

In general, if the license of Kawa or associated packages causes
difficulties, let me know.

Kawa uses some math routines from fdlib's libf77, which bear the
following copyright:

@quotation
Copyright 1990, 1991, 1992, 1993 by AT&T Bell Laboratories and Bellcore.
 
Permission to use, copy, modify, and distribute this software
and its documentation for any purpose and without fee is hereby
granted, provided that the above copyright notice appear in all
copies and that both that the copyright notice and this
permission notice and warranty disclaimer appear in supporting
documentation, and that the names of AT&T Bell Laboratories or
Bellcore or any of their entities not be used in advertising or
publicity pertaining to distribution of the software without
specific, written prior permission.
 
AT&T and Bellcore disclaim all warranties with regard to this
software, including all implied warranties of merchantability
and fitness.  In no event shall AT&T or Bellcore be liable for
any special, indirect or consequential damages or any damages
whatsoever resulting from loss of use, data or profits, whether
in an action of contract, negligence or other tortious action,
arising out of or in connection with the use or performance of
this software.
@end quotation

@section Copyright for this manual

Here is the license for this manual:

Copyright @copyright{} 1996, 1997, 1998, 1999 Per Bothner
@*Parts of this manual were derived from the SLIB manual,
copyright @copyright{} 1993-1998 Todd R. Eigenschink and Aubrey Jaffer.
@*Parts of this manual were derived from ISO/EIC 10179:1996(E)
(Document Style and Specifical Language) - unknown copyright.

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

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

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

This manual has quoted from SRFI-6 (Basic String Ports),
which is Copyright (C) William D Clinger (1999). All Rights Reserved.

This manual has quoted from SRFI-8 (receive: Binding to multiple values),
which is Copyright (C) John David Stone (1999). All Rights Reserved.

This manual has quoted from SRFI-9 (Defining Record Types)
which is Copyright (C) Richard Kelsey (1999).  All Rights Reserved.

This manual has quoted from SRFI-11 (Syntax for receiving multiple values),
which is Copyright (C) Lars T. Hansen (1999). All Rights Reserved.

This manual has quoted from SRFI-25 (Multi-dimensional Array Primitives),
which is Copyright (C) Jussi Piitulainen (2001). All Rights Reserved.

This manual has quoted from SRFI-26 (Notation for Specializing
Parameters without Currying),
which is Copyright (C) Sebastian Egner (2002). All Rights Reserved.

The following notice applies to SRFI-6, SRFI-8, SRFI-9, SRFI-11, SRFI-25,
and SRFI-26, which are quoted in this manual, but it does not apply to the
manual as a whole:

@quotation
This document and translations of it may be copied and furnished to
others, and derivative works that comment on or otherwise explain it or
assist in its implementation may be prepared, copied, published and
distributed, in whole or in part, without restriction of any kind,
provided that the above copyright notice and this paragraph are included
on all such copies and derivative works. However, this document itself
may not be modified in any way, such as by removing the copyright notice
or references to the Scheme Request For Implementation process or
editors, except as needed for the purpose of developing SRFIs in which
case the procedures for copyrights defined in the SRFI process must be
followed, or as required to translate it into languages other than
English.
@end quotation

@c I'd prefer to call this node plain "Index", but that causes a clash
@c with index.html when generating HTML on case-insenstive file systems.
@node Overall Index,  , License, Top
@unnumbered Index
@printindex cp

@bye
