This is kawa.info, produced by makeinfo version 4.5 from
/home/bothner/Kawa/kawa/doc/kawa.texi.

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


File: kawa.info,  Node: Field operations,  Next: Defining new classes,  Prev: Method operations,  Up: Objects Classes and Modules

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.

 - Function: field object fieldname
     Get the instance field with the given FIELDNAME from the given
     OBJECT.  Returns the value of the field, which must be public.
     This procedure has a `setter', and so can be used as the first
     operand to `set!'.

     The field name is "mangled" (*note Mangling::) into a valid Java
     name.  If there is no accessible field whose name is `"FIELDNAME"',
     we look for a no-argument method whose name is `"getFIELDNAME"'.

     If OBJECT is a primitive Java array, then FIELDNAME can only be
     `'length', and the result is the number of elements of the array.

 - Function: static-field class fieldname
     Get the static field with the given FIELDNAME from the given
     CLASS.  Returns the value of the field, which must be public.
     This procedure has a `setter', and so can be used as the first
     operand to `set!'.

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

 - Function: slot-ref object fieldname
     A synonym for `(field OBJECT FIELDNAME)'.

 - Function: slot-set! object fieldname value
     A synonym for `(set! (field OBJECT FIELDNAME) VALUE)'.


File: kawa.info,  Node: Defining new classes,  Next: Anonymous classes,  Prev: Field operations,  Up: Objects Classes and Modules

Defining new classes
====================

   Kawa provides various mechanisms for defining new classes.  The
`define-class' and `define-simple-class' forms will usually be the
preferred mechanisms.  They have basically the same syntax, but have a
couple of differences.  `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 `define-simple-class' is slightly more
efficient, and it is easier to access it from Java code.

   The syntax of `define-class' are mostly compatible with that in the
Guile and Stk dialects of Scheme.

 - Syntax: define-class name (supers ...) field-or-method-decl ...
 - Syntax: define-simple-class name (supers ...) field-or-method-decl
          ...
          FIELD-OR-METHOD ::= FIELD-DECL | METHOD-DECL
          FIELD-DECL ::= (FNAME [:: FTYPE] [OPTION-KEYWORD OPTION-VALUE]*)
          METHOD-DECL ::= ((METHOD-NAME FORMAL-ARGUMENTS) [:: RTYPE] BODY)
     Defines a new class named NAME.  If `define-simple-class' is used,
     creates a normal Java class named NAME in the current package.
     (If NAME has the form `<xyx>' the Java implementation type is
     named `xyz'.)  If `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
     SUPERS.  This is a list of names of classes that are in scope
     (perhaps imported using `require'), or names for existing classes
     or interfaces surrounded by `<>', such as `<gnu.lists.Sequence>'.
     If `define-simple-class' is used, at most one of these may be the
     name of a normal Java class or classes defined using
     `define-simple-class'; the rest must be interfaces or classes
     defined using `define-class'.  If `define-class' is used, _all_ of
     the classes listed in SUPERS should be interfaces or classes
     defined using `define-class'.

     Each FIELD-DECL declares a public instance "slot" (field) with the
     given FNAME.  If FTYPE is specified it is the type of the slot.
     The following OPTION-KEYWORDs are implemented:
    `type:' FTYPE
          Specifies that FTYPE is the type of (the values of) the field.
          Equivalent to `:: FTYPE'.

    `allocation:' `class:'
          Specifies that there should be a single slot shared between
          all instances of the class (and its sub-classes).  Not yet
          implemented for `define-class', only for
          `define-simple-class'.  In Java terms this is a `static'
          field.

    `allocation:' `instance:'
          Specifies that each instance has a separate value "slot", and
          they are not shared. In Java terms, this is a non-`static'
          field.  This is the default.

    `init-form:' EXPR
          An expression used to initialize the slot.  The lexical
          environment of the EXPR is that of the `define-class' or
          `define-simple-class'.  (This is not quite true in the current
          implementation, as the names of fields and methods of this
          class are visible.)

    `init-value:' VALUE
          A value expression used to initialize the slot.  For now this
          is synonymous with INIT-FORM:, but that may change (depending
          on what other implementation do), so to be safe only use
          `init-value:' with a literal.

    `init-keyword:' `NAME:'
          A keyword that that can be used to initialize instance in
          `make' calls.  For now, this is ignored, and NAME should be
          the same as the field's FNAME.  `static' field.

     Each METHOD-DECL declares a public non-static method, whose name
     is METHOD-NAME.  (If METHOD-NAME is not a valid Java method name,
     it is mapped to something reasonable.  For example `foo-bar?' is
     mapped to `isFooBar'.)  The types of the method arguments can be
     specified in the FORMAL-ARGUMENTS.  The return type can be
     specified by RTYPE, or is otherwise the type of the BODY.
     Currently, the 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 BODY of a method includes the FIELD-DECLs of the
     object.  It does include the surrounding lexical scope.  It
     sort-of also includes the declared methods, but this is not
     working yet.

   A simple 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))))


File: kawa.info,  Node: Anonymous classes,  Next: Module classes,  Prev: Defining new classes,  Up: Objects Classes and Modules

Anonymous classes
=================

 - Syntax: object (supers ...) field-or-method-decl ...
     Returns a new instance of an anonymous (inner) class.  The syntax
     is similar to `define-class'.
          FIELD-OR-METHOD ::= FIELD-DECL | METHOD-DECL
          FIELD-DECL ::= (FNAME [[[::] FTYPE] FINIT])
              | (FNAME [:: FTYPE] [OPTION-KEYWORD OPTION-VALUE]*)
          METHOD-DECL ::= ((METHOD-NAME FORMAL-ARGUMENTS) [[::] RTYPE] BODY)

     Returns a new instance of a unique (anonymous) class.  The class
     inherits from the list of 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:
          (begin
            (define-simple-class HNAME (SUPERS ...) FIELD-OR-METHOD-DECL ...)
            (make HNAME))

     A FIELD-DECL is as for `define-class', except that we also allow
     an abbreviated syntax.  Each FIELD-DECL declares a public instance
     field.  If FTYPE is given, it specifies the type of the field.  If
     FINIT is given, it is an expression whose value becomes the
     initial value of the field.  The FINIT is evaluated at the same
     time as the `object' expression is evaluated, in a scope where all
     the FNAMEs are visible.

     A METHOD-DECL is as for `define-class'.


File: kawa.info,  Node: Module classes,  Prev: Anonymous classes,  Up: Objects Classes and Modules

Modules and how they are compiled to classes
============================================

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

   There are two kinds of module class: A "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 "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 "module instance".  However, only a single
instance of a module can be "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.

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 `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 `module-export' declaration in the module, then only
those names listed in a `module-export' are exported.  There can be
more than one `module-export', and they can be anywhere in the Scheme
file.  As a matter of good style, I recommend a single `module-export'
near the beginning of the file.

 - Syntax: module-export name ...
     Make the definition for each NAME be exported.  Note that it is an
     error if there is no definition for NAME in the current module, or
     if it is defined using `define-private'.

   In this module, `fact' is public and `worker' is private:
     (module-export fact)
     (define (worker x) ...)
     (define (fact x) ...)

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

Definitions
-----------

   In addition to `define' (which can take an optional type specifier),
Kawa has some extra definition forms.

 - Syntax: define-private name [:: type] value
 - Syntax: define-private (name formals) body
     Same as `define', except that `name' is not exported.

 - Syntax: define-constant name [:: type] value
     Definites NAME to have the given 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
     `final' field with the given name and type.  The VALUE is
     evaluated as normal; however, if it is a compile-time constant, it
     defaults to being static.

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

     Also, declares to the compiler that NAME will be looked up in the
     dynamic environment. This can be useful for shutting up warnings
     from `--warn-undefined-variable'.

     This is similar to the Common Lisp `defvar' form.  However, the
     Kawa version is (currently) only allowed at module level.

 - Syntax: define-namespace name namespace-uri
     Defines NAME as "namespace alias" - a lexically scoped "nickname"
     for the namespace (or package) whose full name is 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 NAME will be treated as being in the
     package/namespace whose global unique name is the NAMESPACE-URI.

     The features is currently used for XML (to be documented).  In XML
     terminology, a name containing a colon is a "qualified name".  The
     part of the name before the colon is a "namespace prefix", which
     is an aliases for a locally-visible "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 LOCAL PART of the name.

     If the namespace starts with the strings `"class:"', then the NAME
     can be used for invoking Java methods - *note Method operations::.


How a module becomes a class
----------------------------

   If you want to just use a Scheme module as a module (i.e. `load' or
`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 `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 `-T' Kawa command-line
flag.  The package-prefix specified by the `-P' flag is prepended to
give the fully-qualified class name.

 - Syntax: module-name <name>
     Sets the name of the generated class, overriding the default.  If
     there is no `.' in the NAME, the package-prefix (specified by the
     `-P' Kawa command-line flag) is prepended.

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

 - Syntax: module-extends <class>
     Specifies that the class generated from the immediately surrounding
     module should extend (be a sub-class of) the class `<CLASS>'.

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

   Note that the compiler does _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 `gnu.mapping.Symbol'
object, and the value Scheme variable is defined to be the value stored
in the `Symbol'.  Howewer, if you specify an explicit type, then the
field will have the specified type, instead of being a `Symbol'.  The
indirection using `Symbol' is also avoided if you use `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 `<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 `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
(*note 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 _inside_ the default
expression, which is very contrived.)  If there are `#!keyword' or
`#!rest' arguments, the compiler generate a "variable argument list"
method.  This is a method whose last parameter is either an array or a
`<list>', and whose name has `$V' appended to indicate the last
parameter is a list.

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

 - Syntax: module-static name ...
 - Syntax: module-static `#t'
 - Syntax: module-static `#f'
     Control whether the generated fields and methods are static.  If
     `#t' is specified, then the module will be a static module, _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 NAMEs that are explicitly listed
     will be compiled to static fields and methods.  If `#f' is
     specified, then all exported names will be compiled to non-static
     (instance) fields and methods.

     By default, if no `module-static' is specified, the following
     rules apply:
       1. If there is a `module-extends' or `module-implements'
          declaration, then `(module-static #f)' is implied.

       2. If the `--module-static' command-line parameter is specified,
          then `(module-static #t)' is implied.

       3. (Not yet implemented: If there are no top-level actions and
          all definitions are procedure definitions, macro definitions,
          or constant definitions, then `(module-static #t)' is
          implied.)

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

     Note `(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.

   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" (*note Mangling::) into an acceptable Java
name.  The implementation can recover the original name of a field `X'
as `((gnu.mapping.Named) X).getName()' because all the standard
compiler-generate field types implemented the `Named' interface.

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

Requiring (importing) a module
------------------------------

   You can import a module into the current namespace with `require'.

 - Syntax: require modulespec
     The MODULESPEC can be either a `<CLASSNAME>' or a `'FEATURENAME'.
     In either case the names exported by the specified module (class)
     are added to the current set of visible names.

     If MODULESPEC is `<CLASSNAME>' where 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
     `gnu.expr.ModuleBody' or implements `java.lang.Runnable' then the
     corresponding `run' method is executed.  (This is done _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 MODULESPEC is `'FEATURENAME' then the FEATURENAME is looked
     up (at compile time) in the "feature table" which yields the
     implementing `<CLASSNAME>'.

   For some examples, you may want to look in the `gnu/kawa/slib'
directory.


File: kawa.info,  Node: Low-level functions,  Next: XML tools,  Prev: Objects Classes and Modules,  Up: Top

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


File: kawa.info,  Node: Scheme types in Java,  Next: Array operations,  Prev: Low-level functions,  Up: Low-level functions

Scheme types in Java
====================

   All Scheme values are implemented by sub-classes of
`java.lang.Object'.

   Scheme symbols are implemented using `java.lang.String'.  (Don't be
confused by the fact the Scheme sybols are represented using Java
Strings, while Scheme strings are represented by `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 `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 `gnu.math.DFloNum'.

   A Scheme pair is implemented by `gnu.lists.Pair'.

   A Scheme vector is implemented by `gnu.lists.FVectror'.

   Scheme characters are implemented using `gnu.text.Char'.

   Scheme strings are implemented using `gnu.lists.FString'.

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


File: kawa.info,  Node: Array operations,  Next: Low-level Method invocation,  Prev: Scheme types in Java,  Up: Low-level functions

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

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

 - 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
     ELEMENT-TYPE;  the second argument is an index;  and the third
     argument is a value (coercible to ELEMENT-TYPE) which replaces the
     value specified by the index in the given array.

 - 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
     ELEMENT-TYPE;  the second argument is an index.  Applying the
     procedure returns the element at the specified index.

 - 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
     ELEMENT-TYPE.  Applying the procedure returns the length of the
     array.  (Alternatively, you can use `(field ARRAY 'length)'.)


File: kawa.info,  Node: Low-level Method invocation,  Next: Low-level Field operations,  Prev: Array operations,  Up: Low-level functions

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 `invoke' and `invoke-static' (*note Method operations::)
instead.

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

 - 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 METHOD in the class
     whose name is CLASS.

 - 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 METHOD in the class
     whose name is CLASS.

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

   The macros return procedure values, just like `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.


File: kawa.info,  Node: Low-level Field operations,  Next: Loading Java functions into Scheme,  Prev: Low-level Method invocation,  Up: Low-level functions

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 `fields' and `static-field'
functions (*note Field operations::) are easier to use, more powerful,
and just as efficient.  (One exception is for `primitive-set-static';
while its functionality can be expressed using `(set! (static-field
...) ...)', that idiom is currently less efficient.)  Also, the
high-level functions currently do not provide access to private fields.

 - Syntax: primitive-get-field class fname ftype
     Use this to access a field named FNAME having type TYPE in class
     CLASS.  Evaluates to a new one-argument procedure, whose argument
     is a reference to an object of the specified CLASS.  Calling that
     procedure returns the value of the specified field.

 - Syntax: primitive-set-field class fname ftype
     Use this to change a field named FNAME having type TYPE in class
     CLASS.  Evaluates to a new two-argument procedure, whose first
     argument is a reference to an object of the specified 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 `!', because it does not actually set the field.  Rather, it
     returns a function for setting the field.)

 - Syntax: primitive-get-static class fname ftype
     Like `primitive-get-field', but used to access static fields.
     Returns a zero-argument function, which when called returns the
     value of the static field.

 - Syntax: primitive-set-static class fname ftype
     Like `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.


File: kawa.info,  Node: Loading Java functions into Scheme,  Next: Evaluating Scheme expressions from Java,  Prev: Low-level Field operations,  Up: Low-level functions

Loading Java functions into Scheme
==================================

   When `kawa -C' compiles (*note Files compilation::) a Scheme module
it creates a class that implements the `java.lang.Runnable' interface.
(Usually it is a class that extends the `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 `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 `Procedure' object.  Below
is a simple example, using the `Procedure1' class, which is class
extending `Procedure' that can be useful for one-argument procedure.
You can use other classes to write procedures.  For example a
`ProcedureN' takes a variable number of arguments, and you must define
`applyN(Object[] args)' method instead of `apply1'.  (You may notice
that some builtin classes extend `CpsProcedure'.  Doing so allows has
certain advantages, including support for full tail-recursion, but it
has some costs, and is a bit trickier.)

     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);
       }
     }

   You can create a `MyFunc' instance and call it from Java:
       Procedure myfunc1 = new MyFunc("my-func-1", Boolean.FALSE);
       Object aresult = myfunc1.apply1(some_object);
   The name `my-func-1' is used when `myfunc1' is printed or when
`myfunc1.toString()' is called.  However, the Scheme variable
`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

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

   If you use Scheme you can use `require':
     #|kawa:1|# (require <MyModule>)
     #|kawa:2|# (my-func-1 0)
     (1 0)

   Note that `require' magically defines `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
`Runnable', then an instance of the object is created, if one isn't
available.)  If the field value is a `Procedure' (or implements
`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 `my-func-1', not `myfunc1'.

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

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

     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");
       }
     }

   Loading `MyModule' causes `"MyModule loaded"' to be printed, and
`my-func-t' to be defined.  Using `Interpreter''s `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 `Procedure' be its own module:

     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);
     }


File: kawa.info,  Node: Evaluating Scheme expressions from Java,  Prev: Loading Java functions into Scheme,  Up: Low-level functions

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
`throws' lists) may change.)

 - Static method: void Scheme.registerEnvironment ()
     Initializes the Scheme environment.  Maybe needed if you try to
     load a module compiled from a Scheme source file.

 - Static method: Object Scheme.eval (InPort PORT, Environment ENV)
     Read expressions from PORT, and evaluate them in the ENV
     environment, until end-of-file is reached.  Return the value of
     the last expression, or `Interpreter.voidObject' if there is no
     expression.

 - Static method: Object Scheme.eval (String STRING, Environment ENV)
     Read expressions from STRING, and evaluate them in the ENV
     environment, until the end of the string is reached.  Return the
     value of the last expression, or `Interpreter.voidObject' if there
     is no expression.

 - Static method: Object Scheme.eval (Object SEXPR, Environment ENV)
     The SEXPR is an S-expression (as may be returned by `read').
     Evaluate it in the ENV environment, and return the result.

   For the `Environment' in most cases you could use
`Environment.current()'.  Before you start, you need to initialize the
global environment, which you can with
     Environment.setCurrent(new Scheme().getEnvironment());

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


File: kawa.info,  Node: XML tools,  Next: KRL,  Prev: Low-level functions,  Up: Top

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

Scheme functions
----------------

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

 - Function: make-attribute name value...
     Create an "attribute", which is a name-value pair.  For now, NAME
     should be a symbol

 - Function: as-xml value
     Return a value (or multiple values) that when printed will print
     VALUE in XML syntax.
          (require 'xml)
          (as-xml (make-element 'p "Some " (make-element 'em "text") "."))
     prints `<p>Some <em>text</em>.</p>'.

xquery language
---------------

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

XSL transformations
-------------------

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


File: kawa.info,  Node: Server-side scripts,  Next: Servlets,  Up: XML tools

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 `response-header' function.  Kawa will use the response
header values to set various required and optional fields of the HTTP
response.  Note that `response-header' does not actually do anything
until it is "printed" to the standard output.  Note also that if a
`"Content-Type"' response value is printed that controls the formatting
of the following non-response-header values.

   Here is a simple program `hello.scm':
     (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

   The same program using KRL is shorter:
     <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>

   You can also use XQuery:
     <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>

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

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


File: kawa.info,  Node: Servlets,  Next: CGI scripts,  Prev: Server-side scripts,  Up: XML tools

Installing Kawa programs as Servlets
====================================

   You can compile a Kawa program to a `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 `hello' to be part of
the `myutils' "web application", copy `hello*.class' into
`$CATALINA_HOME/webapps/myutils/WEB-INF/classes/'.  You also need to
copy Kawa somewhere where Tomcat can find it, for example
`$CATALINA_HOME/lib/kawa-1.7.90.jar'.  You can then run the `hello'
servlet using the URL <http://localhost:8080/myutils/servlet/hello>.

 - Function: current-servlet
     When called from a Kawa servlet's handler, returns the actual
     `javax.servlet.http.HttpServlet' instance.

 - Function: current-servlet-context
     Returns the `ServletContext' of the currently executing servlet.

 - Function: current-servlet-config
     Returns the `ServletConfig' of the currently executing servlet.

 - Function: servlet-context-realpath
     Returns the file path of the current servlet's "Web application".


File: kawa.info,  Node: CGI scripts,  Next: HTTP requests,  Prev: Servlets,  Up: XML tools

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
*Note 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
*Note Server-side scripts::.  For example:
     kawa --servlet --xquery -C hello.xql

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

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

   You can link instead of copying:
     ln -s /usr/local/bin/cgi-servlet /var/www/cgi-bin/
   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
`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:
     chmod a+r /var/www/cgi-bin/hello*.class /var/www/cgi-bin/hello
     chmod a+x /var/www/cgi-bin/hello

   Now you should be able to run the Kawa program, using the 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.


File: kawa.info,  Node: HTTP requests,  Next: HTTP response,  Prev: CGI scripts,  Up: XML tools

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.
     (require 'http)
   This is not needed for KRL or XQuery.

 - Function: request-method
     Returns the method of the HTTP request, usually `"GET"' or
     `"POST"'.  Corresponds to the CGI variable `REQUEST_METHOD'.

 - Function: request-path-info
     Corresponds to the CGI variable `PATH_INFO'.

 - Function: request-path-translated
     Corresponds to the CGI variable `PATH_TRANSLATED'.

 - Function: request-uri
     Returns the URI of the request, not including the query string, or
     server specification.  The is the combination of CGI variables
     `SCRIPT_NAME' and `PATH_INFO'.

 - Function: request-url
     Returns the complete URL of the request, except the query string.

 - Function: 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
     `QUERY_STRING'.


File: kawa.info,  Node: HTTP response,  Prev: HTTP requests,  Up: XML tools

Functions for generating HTTP responses
=======================================

 - Function: unescaped-data data
     Creates a special value which causes `data' to be printed, as is,
     without normal escaping.  For example, when the output format is
     XML, then printing `"<?xml?>"' prints as `&lt;?xml?&gt;', but
     `(unescaped-data "<?xml?>")' prints as  `<?xml?>'.

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

 - Function: response-header key value
     Create the response header `KEY: 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.

 - Function: response-content-type type
     Species the content-type of the result - for example
     `"text/plain"'.  Convenience function for `(response-header
     "Content-Type" TYPE)'.

 - Function: error-response code [message]
     Creates a response-header with an error code of CODE and a
     response message of MESSAGE.  (For now this is the same as
     `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.

 - Function: response-status code [message]
     Creates a response-header with an status code of CODE and a
     response message of MESSAGE.  (For now this is the same as
     `error-response'.)

