% -*- mode: latex; -*-
% http://en.wikibooks.org/wiki/LaTeX/
\documentclass[10pt]{book}
\usepackage{abcl}

\begin{document}
\title{A Manual for Armed Bear Common Lisp}
\date{January 5, 2012}
\author{Mark~Evenson, Erik~H\"{u}lsmann, Alessio~Stalla, Ville~Voutilainen}

\maketitle

\tableofcontents

\chapter{Introduction}

Armed Bear is a conforming implementation of the ANSI Common Lisp
standard (see \ref{chapter:conformance} on page
\pageref{chapter:conformance} which states the details of the
conformance level.  This manual documents the Armed Bear Common Lisp
implementation for users of the system.

\subsection{Version}
This manual corresponds to abcl-1.0.1.

\subsection{License}

The implementation is licensed under the terms of the GPL v2 of June
1991 with the ``classpath-exception'' that makes its deployment in
commercial settings quite reasonable.  The license is viral in the
sense that if you change the implementation, and redistribute those
changes, you are required to provide the source to those changes back
to be merged with the public trunk.

\subsection{Contributors}

% TODO format this better, optionally link to URI

% Thanks for the markup
Philipp Marek

% Thanks for the whacky IKVM stuff and keeping the flame alive
Douglas Miles

% Thanks for JSS
Alan Ruttenberg

and of course

Peter Graves

\chapter{Running}

\textsc{ABCL} is packaged as a single jar file usually named either
``abcl.jar'' or possibly``abcl-1.0.0.jar'' if one is using a versioned
package from your system vendor.  This byte archive can be executed
under the control of a suitable JVM \footnote {Java Virtual Machine}
by using the ``-jar'' option to parse the manifest, and select the
class named therein ``\code{org.armedbear.lisp.Main}'' for execution,
viz:

\begin{listing-shell}
  cmd$ java -jar abcl.jar
\end{listing-shell}

\emph{N.b.} for the proceeding command to work, the ``java'' executable needs
to be in your path.

To make it easier to facilitate the use of ABCL in tool chains (such
as SLIME \footnote{SLIME is the Superior Lisp Mode for Interaction
  under Emacs}) the invocation is wrapped in a Bourne shell script
under \textsc{UNIX} or a \textsc{DOS} command script under Windows so that ABCL may be
executed simply as:

\begin{listing-shell}
  cmd$ abcl
\end{listing-shell}

\section{Options}

ABCL supports the following command line options:

\begin{verbatim}
--help
    Displays this message.
--noinform
    Suppresses the printing of startup information and banner.
--noinit
    Suppresses the loading of the '~/.abclrc' startup file.
--nosystem
    Suppresses loading the 'system.lisp' customization file. 
--eval <FORM>
    Evaluates the <FORM> before initializing REPL.
--load <FILE>
    Loads the file <FILE> before initializing REPL.
--load-system-file <FILE>
    Loads the system file <FILE> before initializing REPL.
--batch
    The process evaluates forms specified by arguments and possibly by those
    by those in the intialization file '~/.abcl', and then exits.

The occurance of '--' copies the remaining arguments, unprocessed, into
the variable EXTENSIONS:*COMMAND-LINE-ARGUMENT-LIST*.
\end{verbatim}

All of the command line arguments which follow the occurrence of ``----''
are passed into a list bound to the EXT:*COMMAND-LINE-ARGUMENT-LIST*
variable.

\section{Initialization}

If the \textsc{ABCL} process is started without the ``--noinit'' flag, it
attempts to load a file named ``.abclrc'' located in the user's home
directory and then interpret its contents.  

The user's home directory is determined by the value of the JVM system
property ``user.home''.  This value may--or may not--correspond to the
value of the HOME system environment variable at the discretion of the
JVM implementation that \textsc{ABCL} finds itself hosted upon.

\chapter{Conformance}
\label{chapter:conformance}

\section{ANSI Common Lisp}
\textsc{ABCL} is currently a (non)-conforming ANSI Common Lisp
implementation due to the following known issues:

\begin{itemize}
  \item The generic function signatures of the DOCUMENTATION symbol do
    not match the CLHS.
  \item The TIME form does not return a proper VALUES environment to
    its caller.
\end{itemize}

Somewhat confusingly, this statement of non-conformance in the
accompanying user documentation fulfills the requirements that
\textsc{ABCL} is a conforming ANSI Common Lisp implementation
according to the CLHS \footnote{Common Lisp Hyperspec language
  reference document.}.  Clarifications to this point are solicited.

ABCL aims to be be a fully conforming ANSI Common Lisp implementation.
Any other behavior should be reported as a bug.

\section{Contemporary Common Lisp}
In addition to ANSI conformance, \textsc{ABCL} strives to implement features
expected of a contemporary Common Lisp \footnote{i.e. a Lisp of the
  post 2005 Renaissance}

\subsection{Deficiencies}
The following known problems detract from \textsc{ABCL} being a proper
contemporary Common Lisp.
\begin{itemize}

  \item An incomplete implementation of interactive debugging
    mechanisms namely a no-op version of
    \code{STEP} \footnote{Somewhat surprisingly allowed by
      \textsc{ANSI}}, the inability to inspect local variables in a
    given call frame, and the inability to resume a halted computation
    at an arbitrarily selected call frame.

  \item An incomplete implementation of a properly named metaobject
    protocol (viz. (A)MOP \footnote{The Art of the  Metaobject Protocol} )

    % N.b. 
    % TODO go through AMOP with symbols, starting by looking for
    % matching function signature.
    % XXX is this really blocking ANSI conformance?  Answer: we have
    % to start with such a ``census'' to determine what we have.

  \item Incomplete streams abstraction, in that \textsc{ABCL} needs suitable
    abstraction between ANSI and Gray streams.  The streams could be
    optimized to the JVM NIO abstractions at great profit for binary
    byte-level manipulations.
    
  \item Incomplete documentation (missing docstrings from exported
    symbols and the draft status of the User Manual).

\end{itemize}

\chapter{Interaction with Hosting JVM}

%  Plan of Attack
%
% describe calling Java from Lisp, and calling Lisp from Java,
% probably in two separate sections.  Presumably, we can partition our
% audience into those who are more comfortable with Java, and those
% that are more comforable with Lisp

The Armed Bear Common Lisp implementation is hosted on a Java Virtual
Machine.  This chapter describes the mechanisms by which the
implementation interacts with that hosting mechanism.

\section{Lisp to Java}

\textsc{ABCL} offers a number of mechanisms to interact with Java from its
Lisp environment. It allows calling both instance and static methods
of Java objects, manipulation of instance and static fields on Java
objects, and construction of new Java objects.

When calling Java routines, some values will automatically be
converted by the FFI \footnote{FFI stands for Foreign Function
  Interface which is the term of art which describes how a Lisp
  implementation encapsulates invocation in other languages.}  from
Lisp values to Java values. These conversions typically apply to
strings, integers and floats. Other values need to be converted to
their Java equivalents by the programmer before calling the Java
object method. Java values returned to Lisp are also generally
converted back to their Lisp counterparts. Some operators make an
exception to this rule and do not perform any conversion; those are
the ``raw'' counterparts of certain FFI functions and are recognizable
by their name ending with \code{-RAW}.

\subsection{Low-level Java API}

We define a higher level Java API in the topic:Higher level Java JSS
package developed by Alan Ruttenberg which is available in the
\code{contrib/} directory, see the  . This package is
described later in this document, see \ref{section:jss} on page
\pageref{section:jss}.  This section covers the lower level API
directly available after evaluating \code{(require 'JAVA)}.

\subsubsection{Calling Java Object Methods}

There are two ways to call a Java object method in the low-level (basic) API:

\begin{itemize}
\item Call a specific method reference (which was previously acquired)
\item Dynamic dispatch using the method name and
  the call-specific arguments provided by finding the
  \ref{section:Parameter matching for FFI dynamic dispatch}{best match}.
\end{itemize}

The dynamic dispatch variant is discussed in the next section.

\code{JAVA:JMETHOD} is used to acquire a specific method reference.
The function takes at two or more arguments. The first is Java class designator
(a \code{JAVA:JAVA-CLASS} object returned by \code{JAVA:JCLASS} or a string naming
a Java class). The second is a string naming the method.

Any arguments beyond the first two should be strings naming Java classes with
one exception as listed in the next paragraph. These
classes specify the types of the arguments for the method to be returned.

There's additional calling convention to the \code{JAVA:JMETHOD} function:
When the method is called with three parameters and the last parameter is an
integer, the first method by that name and matching number of parameters is
returned.

Once one has a reference to the method, one may invoke it using
\code{JAVA:JCALL}, which takes the method as the first argument. The
second argument is the object instance to call the method on, or
\code{NIL} in case of a static method.  Any remaining parameters are
used as the remaining arguments for the call.

\subsubsection{Calling Java object methods: dynamic dispatch}

The second way of calling Java object methods is by using dynamic dispatch.
In this case \code{JAVA:JCALL} is used directly without acquiring a method
reference first. In this case, the first argument provided to \code{JAVA:JCALL}
is a string naming the method to be called. The second argument is the instance
on which the method should be called and any further arguments are used to
select the best matching method and dispatch the call.

\subsubsection{Dynamic dispatch: Caveats}

Dynamic dispatch is performed by using the Java reflection
API \footnote{The Java reflection API is found in the
  \code{java.lang.reflect} package}. Generally the dispatch works
fine, but there are corner cases where the API does not correctly
reflect all the details involved in calling a Java method. An example
is the following Java code:

\begin{listing-java}
ZipFile jar = new ZipFile("/path/to/some.jar");
Object els = jar.entries();
Method method = els.getClass().getMethod("hasMoreElements");
method.invoke(els);
\end{listing-java}

even though the method \code{hasMoreElements()} is public in \code{Enumeration},
the above code fails with

\begin{listing-java}
java.lang.IllegalAccessException: Class ... can
not access a member of class java.util.zip.ZipFile\$2 with modifiers
"public"
       at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:65)
       at java.lang.reflect.Method.invoke(Method.java:583)
       at ...
\end{listing-java}

because the method has been overridden by a non-public class and the
reflection API, unlike javac, is not able to handle such a case.

While code like that is uncommon in Java, it is typical of ABCL's FFI
calls. The code above corresponds to the following Lisp code:

\begin{listing-lisp}
(let ((jar (jnew "java.util.zip.ZipFile" "/path/to/some.jar")))
  (let ((els (jcall "entries" jar)))
    (jcall "hasMoreElements" els)))
\end{listing-lisp}

except that the dynamic dispatch part is not shown.

To avoid such pitfalls, all Java objects in \textsc{ABCL} carry an extra
field representing the ``intended class'' of the object. That is the class
that is used first by \code{JAVA:JCALL} and similar to resolve methods;
the actual class of the object is only tried if the method is not found
in the intended class. Of course, the intended class is always a super-class
of the actual class - in the worst case, they coincide. The intended class
is deduced by the return type of the method that originally returned
the Java object; in the case above, the intended class of \code{ELS}
is \code{java.util.Enumeration} because that's the return type of
the \code{entries} method.

While this strategy is generally effective, there are cases where the
intended class becomes too broad to be useful. The typical example
is the extraction of an element from a collection, since methods in
the collection API erase all types to \code{Object}. The user can
always force a more specific intended class by using the \code{JAVA:JCOERCE}
operator.

% \begin{itemize}
% \item Java values are accessible as objects of type JAVA:JAVA-OBJECT.
% \item The Java FFI presents a Lisp package (JAVA) with many useful
%   symbols for manipulating the artifacts of expectation on the JVM,
%   including creation of new objects \ref{JAVA:JNEW}, \ref{JAVA:JMETHOD}), the
%   introspection of values \ref{JAVA:JFIELD}, the execution of methods
%   (\ref{JAVA:JCALL}, \ref{JAVA:JCALL-RAW}, \ref{JAVA:JSTATIC})
% \item The JSS package (\ref{JSS}) in contrib introduces a convenient macro
%   syntax \ref{JSS:SHARPSIGN_DOUBLEQUOTE_MACRO} for accessing Java
%   methods, and additional convenience functions.
% \item Java classes and libraries may be dynamically added to the
%   classpath at runtime (JAVA:ADD-TO-CLASSPATH).
% \end{itemize}

\subsubsection{Calling Java class static methods}

Like with non-static methods, references to static methods can be acquired
by using the \code{JAVA:JMETHOD} primitive. In order to call this method,
it's not possible to use the \code{JAVA:JCALL} primitive however: there's a 
separate API to retrieve a reference to static methods. This
primitive is called \code{JAVA:JSTATIC}. 

Like \code{JAVA:JCALL}, \code{JAVA:JSTATIC} supports dynamic dispatch by
passing the name of the method as a string instead of passing a method reference.
The parameter values should be values to pass in the function call instead of
a specification of classes for each parameter.

\subsubsection{Parameter matching for FFI dynamic dispatch}

The algorithm used to resolve the best matching method given the name
and the arguments' types is the same as described in the Java Language
Specification. Any deviation should be reported as a bug.

% ###TODO reference to correct JLS section

\subsubsection{Instantiating Java objects}

Java objects can be instantiated (created) from Lisp by calling
a constructor from the class of the object to be created. The same way
\code{JAVA:JMETHOD} is used to acquire a method reference, the
\code{JAVA:JCONSTRUCTOR} primitive can be used to acquire a constructor
reference. It's arguments specify the types of arguments of the constructor
method the same way as with \code{JAVA:JMETHOD}.

The constructor can't be passed to \code{JAVA:JCALL}, but instead should
be passed as an argument to \code{JAVA:JNEW}.

\subsubsection{Accessing Java object fields}

Fields in Java objects can be accessed using the getter and setter functions
\code{JAVA:GETFIELD} and \code{JAVA:PUTFIELD}. This applies to values stored in object
instances. If you want to access static fields: see the next section.

Like \code{JAVA:JCALL} and friends, values returned from these accessors carry
an intended class around and values which can be converted to Lisp values will
be converted.

\subsubsection{Accessing Java static fields}

Static fields in Java objects (class fields) can be accessed using the getter
and setter functions \code{JAVA:GETSTATIC} and \code{JAVA:PUTSTATIC}. Values
stored in object instance fields can be accessed as described in the previous
section.

Like \code{JAVA:JCALL} and friends, values returned from these accessors carry
an intended class around and values which can be converted to Lisp values will
be converted.

\section{Lisp from Java}

In order to access the Lisp world from Java, one needs to be aware
of a few things. The most important ones are listed below.

\begin{itemize}
\item All Lisp values are descendants of LispObject.java
\item In order to 
\item Lisp symbols are accessible via either directly referencing the
  Symbol.java instance or by dynamically introspecting the
  corresponding Package.java instance.
\item The Lisp dynamic environment may be saved via
  \code{LispThread.bindSpecial(Binding)} and restored via
  \code{LispThread.resetSpecialBindings(Mark)}.
\item Functions may be executed by invocation of the
  Function.execute(args [...]) 
\end{itemize}

\subsection{Lisp FFI}

FFI stands for "Foreign Function Interface" which is the phase which
the contemporary Lisp world refers to methods of "calling out" from
Lisp into "foreign" languages and environments.  This document
describes the various ways that one interacts with Lisp world of ABCL
from Java, considering the hosted Lisp as the "Foreign Function" that
needs to be "Interfaced".

\subsection{Calling Lisp from Java}

Note: As the entire ABCL Lisp system resides in the org.armedbear.lisp
package the following code snippets do not show the relevant import
statements in the interest of brevity.  An example of the import
statement would be

\begin{listing-java}
  import org.armedbear.lisp.*;
\end{listing-java}

to potentially import all the JVM symbol from the `org.armedbear.lisp'
namespace.

Per JVM, there can only ever be a single Lisp interpreter.  This is
started by calling the static method `Interpreter.createInstance()`.

\begin{listing-java}
  Interpreter interpreter = Interpreter.createInstance();
\end{listing-java}

If this method has already been invoked in the lifetime of the current
Java process it will return null, so if you are writing Java whose
life-cycle is a bit out of your control (like in a Java servlet), a
safer invocation pattern might be:

\begin{listing-java}
  Interpreter interpreter = Interpreter.getInstance();
  if (interpreter == null) {
    interpreter = Interpreter.createInstance();
  }
\end{listing-java}


The Lisp \code{eval} primitive may be simply passed strings for evaluation,
as follows

\begin{listing-java}
  String line = "(load \"file.lisp\")";
  LispObject result = interpreter.eval(line);
\end{listing-java}

Notice that all possible return values from an arbitrary Lisp
computation are collapsed into a single return value.  Doing useful
further computation on the ``LispObject'' depends on knowing what the
result of the computation might be, usually involves some amount
of \code{instanceof} introspection, and forms a whole topic to itself
(c.f. [Introspecting a LispObject])

Using \code{eval} involves the Lisp interpreter.  Lisp functions may
be directly invoked by Java method calls as follows.  One simply
locates the package containing the symbol, then obtains a reference to
the symbol, and then invokes the \code{execute()} method with the
desired parameters.

\begin{listing-java}
    interpreter.eval("(defun foo (msg) (format nil \"You told me '~A'~%\" msg))");
    Package pkg = Packages.findPackage("CL-USER");
    Symbol foo = pkg.findAccessibleSymbol("FOO"); 
    Function fooFunction = (Function)foo.getSymbolFunction();
    JavaObject parameter = new JavaObject("Lisp is fun!");
    LispObject result = fooFunction.execute(parameter);
    // How to get the "naked string value"?
    System.out.println("The result was " + result.writeToString()); 
\end{listing-java}

If one is calling an primitive function in the CL package the syntax
becomes considerably simpler.  If we can locate the instance of
definition in the ABCL Java source, we can invoke the symbol directly.
For instance, to tell if a `LispObject` contains a reference to a symbol.

\begin{listing-java}
    boolean nullp(LispObject object) {
      LispObject result = Primitives.NULL.execute(object);
      if (result == NIL) { // the symbol 'NIL' is explicitly named in the Java
                           // namespace at ``Symbol.NIL''
                           // but is always present in the
                           // local namespace in its unadorned form for
                           // the convenience of the User.
        return false;
      }
      return true;
   }
\end{listing-java}

\subsubsection{Introspecting a LispObject}
\label{topic:Introspecting a LispObject}

We present various patterns for introspecting an an arbitrary
`LispObject` which can represent the result of every Lisp evaluation
into semantics that Java can meaningfully deal with.

\subsubsection{LispObject as \code{boolean}}

If the LispObject a generalized boolean values, one can use
\code{getBooleanValue()} to convert to Java:

\begin{listing-java}
     LispObject object = Symbol.NIL;
     boolean javaValue = object.getBooleanValue();
\end{listing-java}

Although since in Lisp, any value other than NIL means "true"
(so-called generalized Boolean), the use of Java equality it quite a
bit easier to type and more optimal in terms of information it conveys
to the compiler would be:

\begin{listing-java}
    boolean javaValue = (object != Symbol.NIL);
\end{listing-java}

\paragraph{LispObject is a list}

If LispObject is a list, it will have the type `Cons`.  One can then use
the \code{copyToArray} to make things a bit more suitable for Java
iteration.

\begin{listing-java}
    LispObject result = interpreter.eval("'(1 2 4 5)");
    if (result instanceof Cons) {
      LispObject array[] = ((Cons)result.copyToArray());
      ...
    }
\end{listing-java}

A more Lispy way to iterated down a list is to use the `cdr()` access
function just as like one would traverse a list in Lisp:;

\begin{listing-java}
    LispObject result = interpreter.eval("'(1 2 4 5)");
    while (result != Symbol.NIL) {
      doSomething(result.car());
      result = result.cdr();
    }
\end{listing-java}

\subsection{Java Scripting API (JSR-223)}

ABCL can be built with support for JSR-223, which offers a
language-agnostic API to invoke other languages from Java. The binary
distribution downloadable from ABCL's common-lisp.net home is built
with JSR-223 support. If you're building ABCL from source on a pre-1.6
JVM, you need to have a JSR-223 implementation in your CLASSPATH (such
as Apache Commons BSF 3.x or greater) in order to build ABCL with
JSR-223 support; otherwise, this feature will not be built.

This section describes the design decisions behind the ABCL JSR-223
support. It is not a description of what JSR-223 is or a tutorial on
how to use it. See
http://trac.common-lisp.net/armedbear/browser/trunk/abcl/examples/jsr-223
for example usage.

\subsubsection{Conversions}

In general, ABCL's implementation of the JSR-223 API performs implicit
conversion from Java objects to Lisp objects when invoking Lisp from
Java, and the opposite when returning values from Java to Lisp. This
potentially reduces coupling between user code and ABCL. To avoid such
conversions, wrap the relevant objects in \code{JavaObject} instances.

\subsubsection{Implemented JSR-223 interfaces}

JSR-223 defines three main interfaces, of which two (Invocable and
Compilable) are optional. ABCL implements all the three interfaces -
ScriptEngine and the two optional ones - almost completely. While the
JSR-223 API is not specific to a single scripting language, it was
designed with languages with a more or less Java-like object model in
mind: languages such as Javascript, Python, Ruby, which have a concept
of "class" or "object" with "fields" and "methods". Lisp is a bit
different, so certain adaptations were made, and in one case a method
has been left unimplemented since it does not map at all to Lisp.

\subsubsection{The ScriptEngine}

The main interface defined by JSR-223, javax.script.ScriptEngine, is
implemented by the class
\code{org.armedbear.lisp.scripting.AbclScriptEngine}. AbclScriptEngine
is a singleton, reflecting the fact that ABCL is a singleton as
well. You can obtain an instance of AbclScriptEngine using the
AbclScriptEngineFactory or by using the service provider mechanism
through ScriptEngineManager (refer to the javax.script documentation).

\subsubsection{Startup and configuration file}

At startup (i.e. when its constructor is invoked, as part of the
static initialization phase of AbclScriptEngineFactory) the ABCL
script engine attempts to load an "init file" from the classpath
(/abcl-script-config.lisp). If present, this file can be used to
customize the behaviour of the engine, by setting a number of
variables in the ABCL-SCRIPT package. Here is a list of the available
variables:

\begin{itemize}
\item *use-throwing-debugger* Controls whether ABCL uses a
  non-standard debugging hook function to throw a Java exception
  instead of dropping into the debugger in case of unhandled error
  conditions.
  \begin{itemize}
  \item Default value: T
  \item Rationale: it is more convenient for Java programmers using
    Lisp as a scripting language to have it return exceptions to Java
    instead of handling them in the Lisp world.
  \item Known Issues: the non-standard debugger hook has been reported
    to misbehave in certain circumstances, so consider disabling it if
    it doesn't work for you.
  \end{itemize}
\item *launch-swank-at-startup* If true, Swank will be launched at
  startup. See *swank-dir* and *swank-port*.
  \begin{itemize}
  \item Default value: NIL
  \end{itemize}
\item *swank-dir* The directory where Swank is installed. Must be set
  if *launch-swank-at-startup* is true.
\item *swank-port* The port where Swank will listen for
  connections. Must be set if *launch-swank-at-startup* is true.
  \begin{itemize}
  \item Default value: 4005
  \end{itemize}
\end{itemize}

Additionally, at startup the AbclScriptEngine will \code{(require
  'asdf)} - in fact, it uses asdf to load Swank.

\subsubsection{Evaluation}

Code is read and evaluated in the package ABCL-SCRIPT-USER. This
packages USEs the COMMON-LISP, JAVA and ABCL-SCRIPT packages. Future
versions of the script engine might make this default package
configurable. The \code{CL:LOAD} function is used under the hood for
evaluating code, and thus the same behavior of LOAD is
guaranteed. This allows, among other things, \code{IN-PACKAGE} forms
to change the package in which the loaded code is read.

It is possible to evaluate code in what JSR-223 calls a
"ScriptContext" (basically a flat environment of name->value
pairs). This context is used to establish special bindings for all the
variables defined in it; since variable names are strings from Java's
point of view, they are first interned using READ-FROM-STRING with, as
usual, ABCL-SCRIPT-USER as the default package. Variables are declared
special because CL's \code{LOAD}, \code{EVAL} and \code{COMPILE}
functions work in a null lexical environment and would ignore
non-special bindings.

Contrary to what the function \code{LOAD} does, evaluation of a series
of forms returns the value of the last form instead of T, so the
evaluation of short scripts does the Right Thing.

\subsubsection{Compilation}

AbclScriptEngine implements the \code{javax.script.Compilable}
interface. Currently it only supports compilation using temporary
files. Compiled code, returned as an instance of
javax.script.CompiledScript, is read, compiled and executed by default
in the ABCL-SCRIPT-USER package, just like evaluated code. Differently
from evaluated code, though, due to the way the ABCL compiler works,
compiled code contains no reference to top-level self-evaluating
objects (like numbers or strings). Thus, when evaluated, a piece of
compiled code will return the value of the last non-self-evaluating
form: for example the code "(do-something) 42" will return 42 when
interpreted, but will return the result of (do-something) when
compiled and later evaluated. To ensure consistency of behavior
between interpreted and compiled code, make sure the last form is
always a compound form - at least (identity some-literal-object). Note
that this issue should not matter in real code, where it is unlikely a
top-level self-evaluating form will appear as the last form in a file
(in fact, the Common Lisp load function always returns T upon success;
with JSR-223 this policy has been changed to make evaluation of small
code snippets work as intended).

\subsubsection{Invocation of functions and methods}

AbclScriptEngine implements the \code{javax.script.Invocable}
interface, which allows to directly call Lisp functions and methods,
and to obtain Lisp implementations of Java interfaces. This is only
partially possible with Lisp since it has functions, but not methods -
not in the traditional OO sense, at least, since Lisp methods are not
attached to objects but belong to generic functions. Thus, the method
\code{invokeMethod()} is not implemented and throws an
UnsupportedOperationException when called. The \code{invokeFunction()}
method should be used to call both regular and generic functions.

\subsubsection{Implementation of Java interfaces in Lisp}

ABCL can use the Java reflection-based proxy feature to implement Java
interfaces in Lisp. It has several built-in ways to implement an
interface, and supports definition of new ones. The
\code{JAVA:JMAKE-PROXY} generic function is used to make such
proxies. It has the following signature:

\code{jmake-proxy interface implementation \&optional lisp-this ==> proxy}

\code{interface} is a Java interface metaobject (e.g. obtained by
invoking \code{jclass}) or a string naming a Java
interface. \code{implementation} is the object used to implement the
interface - several built-in methods of jmake-proxy exist for various
types of implementations. \code{lisp-this} is an object passed to the
closures implementing the Lisp "methods" of the interface, and
defaults to \code{NIL}.

The returned proxy is an instance of the interface, with methods
implemented with Lisp functions.

Built-in interface-implementation types include:

\begin{itemize}
\item a single Lisp function which upon invocation of any method in
  the interface will be passed the method name, the Lisp-this object,
  and all the parameters. Useful for interfaces with a single method,
  or to implement custom interface-implementation strategies.
\item a hash-map of method-name -> Lisp function mappings. Function
  signature is \code{(lisp-this \&rest args)}.
\item a Lisp package. The name of the Java method to invoke is first
  transformed in an idiomatic Lisp name (\code{javaMethodName} becomes
  \code{JAVA-METHOD-NAME}) and a symbol with that name is searched in
  the package. If it exists and is fbound, the corresponding function
  will be called. Function signature is as the hash-table case.
\end{itemize}

This functionality is exposed by the AbclScriptEngine with the two
methods getInterface(Class) and getInterface(Object, Class). The
former returns an interface implemented with the current Lisp package,
the latter allows the programmer to pass an interface-implementation
object which will in turn be passed to the jmake-proxy generic
function.

\chapter{Implementation Dependent Extensions}

As outlined by the CLHS ANSI conformance guidelines, we document the
extensions to the Armed Bear Lisp implementation made accessible to
the user by virtue of being an exported symbol in the JAVA, THREADS,
or EXTENSIONS packages.

\section{JAVA}

\subsection{Modifying the JVM CLASSPATH}

The JAVA:ADD-TO-CLASSPATH generic functions allows one to add the
specified pathname or list of pathnames to the current classpath
used by ABCL, allowing the dynamic loading of JVM objects:

\begin{listing-lisp}
CL-USER> (add-to-classpath "/path/to/some.jar")
\end{listing-lisp}

N.b \code{ADD-TO-CLASSPATH} only affects the classloader used by ABCL
(the value of the special variable \code{JAVA:*CLASSLOADER*}. It has
no effect on Java code outside ABCL.

% include autogen docs for the JAVA package.
\include{java}

\section{THREADS}

The extensions for handling multithreaded execution are collected in
the \code{THREADS} package.  Most of the abstractions in Doug Lea's
excellent \code{java.util.concurrent} packages may be manipulated
directly via the JSS contrib to great effect.

% include autogen docs for the THREADS package.
\include{threads}

\section{EXTENSIONS}

The symbols in the EXTENSIONS package (nicknamed ``EXT'') constitutes
extensions to the ANSI standard that are potentially useful to the
user.  They include functions for manipulating network sockets,
running external programs, registering object finalizers, constructing
reference weakly held by the garbage collector and others.

See \ref{Rhodes2007} for a generic function interface to the native
JVM contract for \code{java.util.List}.

% include autogen docs for the EXTENSIONS package.
\include{extensions}

\chapter{Beyond ANSI}

Naturally, in striving to be a useful contemporary Common Lisp
implementation, ABCL endeavors to include extensions beyond the ANSI
specification which are either widely adopted or are especially useful
in working with the hosting JVM.

\section{Implementation Dependent}
\begin{enumerate}
  \item Compiler to JVM 5 bytecode
  \item Pathname extensions
\end{enumerate}

\section{Pathname}

We implement an extension to the Pathname that allows for the
description and retrieval of resources named in a URI scheme that the
JVM ``understands''.  Support is built-in to the ``http'' and
``https'' implementations but additional protocol handlers may be
installed at runtime by having JVM symbols present in the
sun.net.protocol.dynmamic pacakge. See Java2007 \cite{Java2007} for more
details.

ABCL has created specializations of the ANSI Pathname object to
enable to use of URIs to address dynamically loaded resources for the
JVM.  A URL-PATHNAME has a corresponding URL whose canonical
representation is defined to be the NAMESTRING of the Pathname.

%
\begin{verbatim}

# RDF description of type hierarchy 
% TODO Render via some LaTeX mode for graphviz?

  <jar-pathname> a <url-pathname>.
  <url-pathname> a <pathname>.
  <logical-pathname> a <pathname> .
\end{verbatim}

Both URL-PATHNAME and JAR-PATHNAME may be used anywhere a PATHNAME is
accepted with the following caveats:

\begin{itemize}

\item A stream obtained via OPEN on a URL-PATHNAME cannot be the
  target of write operations.

\item No canonicalization is performed on the underlying URI (i.e. the
implementation does not attempt to compute the current name of the
representing resource unless it is requested to be resolved.)  Upon
resolution, any cannoicalization procedures followed in resolving the
resource (e.g. following redirects) are discarded.  

\end{itemize}

The implementation of URL-PATHNAME allows the ABCL user to laod dynamically
code from the network.  For example, for Quicklisp (\cite{Xach2011}):

\begin{listing-lisp}
  CL-USER> (load "http://beta.quicklisp.org/quicklisp.lisp")
\end{listing-lisp}

will load and execute the Quicklisp setup code.

See \ref{_:XACH2011} on page \pageref{_:XACH2011}.

\subsubsection{Implementation}

\code{DEVICE} either a string denoting a drive letter under DOS or a cons
specifying a \code{URL-PATHNAME}.
         
\section{Extensible Sequences}

See Rhodes2007 \cite{RHODES2007} for the design.

The SEQUENCE package fully implements Christopher Rhodes' proposal for
extensible sequences.  These user extensible sequences are used
directly in \code{java-collections.lisp} provide these CLOS
abstractions on the standard Java collection classes as defined by the
\code{java.util.List} contract.

This extension is not automatically loaded by the implementation.   It
may be loaded via:

\begin{listing-lisp}
CL-USER> (require 'java-collections)
\end{listing-lisp}

if both extensible sequences and their application to Java collections
is required, or

\begin{listing-lisp}
CL-USER> (require 'extensible-sequences)
\end{listing-lisp}

if only the extensible sequences API as specified in \ref{RHODES2007} is
required.

Note that \code{(require 'java-collections)} must be issued before
\code{java.util.List} or any subclass is used as a specializer in a CLOS
method definition (see the section below).

\section{Extensions to CLOS}

There is an additional syntax for specializing the parameter of a
generic function on a java class, viz. \code{(java:jclass CLASS-STRING)}
where \code{CLASS-STRING} is a string naming a Java class in dotted package
form.

For instance the following specialization would perhaps allow one to
print more information about the contents of a java.util.Collection
object

\begin{listing-lisp}
(defmethod print-object ((coll (java:jclass "java.util.Collection"))
                         stream)
  ;;; ...
)
\end{listing-lisp}

If the class had been loaded via a classloader other than the original
the class you wish to specialize on, one needs to specify the
classloader as an optional third argument.

\begin{listing-lisp}

(defparameter *other-classloader*
  (jcall "getBaseLoader" cl-user::*classpath-manager*))
  
(defmethod print-object ((device-id (java:jclass "dto.nbi.service.hdm.alcatel.com.NBIDeviceID" *other-classloader*))
                         stream)
  ;;; ...
)
\end{listing-lisp}

\section{Extensions to the Reader}

We implement a special hexadecimal escape sequence for specifying
characters to the Lisp reader, namely we allow a sequences of the form
\# \textbackslash Uxxxx to be processed by the reader as character
whose code is specified by the hexadecimal digits ``xxxx''.  The
hexadecimal sequence must be exactly four digits long \footnote{This
  represents a compromise with contemporary in 2011 32bit hosting
  architecures for which we wish to make text processing efficient.
  Should the User require more control over UNICODE processing we
  recommend Edi Weisz' excellent work with FLEXI-STREAMS which we
  fully support}, padded by leading zeros for values less than 0x1000.

Note that this sequence is never output by the implementation.  Instead,
the corresponding Unicode character is output for characters whose
code is greater than 0x00ff.

\subsection{JSS optionally extends the Reader}

The JSS contrib consitutes an additional, optional extension to the
reader in the definition of the \#\" reader macro.  See
\ref{section:jss} on page \pageref{section:jss} for more information.

\section{ASDF}

asdf-2.017.22 is packaged as core component of ABCL, but not
initialized by default, as it relies on the CLOS subsystem which can
take a bit of time to start \footnote{While this time is ``merely'' on
  the order of seconds for contemporary 2011 machines, for
  applications that need to initialize quickly, for example a web
  server, this time might be unnecessarily long}.  ASDF may be loaded
by the \textsc{ANSI} \code{REQUIRE} mechanism as follows:

\begin{listing-lisp}
CL-USER> (require 'asdf)
\end{listing-lisp}

\chapter{Contrib}

The ABCL contrib is packaged as a separate jar archive usually named
\code{abcl-contrib.jar} or possibly something like
\code{abcl-contrib-1.0.0.jar}.  The contrib jar is not loaded by the
implementation by default, and must be first intialized by the
\code{REQUIRE} mechanism before using any specific contrib:

\begin{listing-lisp}
CL-USER> (require 'abcl-contrib)
\end{listing-lisp}

\section{abcl-asdf}

This contrib enables an additional syntax for \textsc{ASDF} system
definition which dynamically loads \textsc{JVM} artifacts such as jar
archives via encapsulation of the Maven build tool.  The Maven Aether
component can also be directly manipulated by the function associated
with the \code{ABCL-ASDF:RESOLVE-DEPENDENCIES} symbol.

%ABCL specific contributions to ASDF system definition mainly
%concerned with finding JVM artifacts such as jar archives to be
%dynamically loaded.


The following \textsc{ASDF} components are added: \code{JAR-FILE},
\code{JAR-DIRECTORY}, \code{CLASS-FILE-DIRECTORY} and \code{MVN}.


\subsection{Referencing Maven Artifacts via ASDF}

Maven artifacts may be referenced within \textsc{ASDF} system
definitions, as the following example references the
\code{log4j-1.4.9.jar} JVM artifact which provides a widely-used
abstraction for handling logging systems:

\begin{listing-lisp}
    ;;;; -*- Mode: LISP -*-
    (in-package :asdf)

    (defsystem :log4j
      :components ((:mvn "log4j/log4j" 
                    :version "1.4.9")))
\end{listing-lisp}

\subsection{API}

We define an API for \textsc{ABCL-ASDF} as consisting of the following
ASDF classes:

\code{JAR-DIRECTORY}, \code{JAR-FILE}, and
\code{CLASS-FILE-DIRECTORY} for JVM artifacts that have a currently
valid pathname representation.

Both the MVN and IRI classes descend from ASDF-COMPONENT, but do not
directly have a filesystem location.

For use outside of ASDF system definitions, we currently define one
method, \code{ABCL-ASDF:RESOLVE-DEPENDENCIES} which locates,
downloads, caches, and then loads into the currently executing JVM
process all recursive dependencies annotated in the Maven pom.xml
graph.

\subsection{Directly Instructing Maven to Download JVM Artifacts}

Bypassing \textsc{ASDF}, one can directly issue requests for the Maven
artifacts to be downloaded

\begin{listing-lisp}
CL-USER> (abcl-asdf:resolve-dependencies "com.google.gwt" "gwt-user")
WARNING: Using LATEST for unspecified version.
"/Users/evenson/.m2/repository/com/google/gwt/gwt-user/2.4.0-rc1/gwt-user-2.4.0-rc1.jar:/Users/evenson/.m2/repository/javax/validation/validation-api/1.0.0.GA/validation-api-1.0.0.GA.jar:/Users/evenson/.m2/repository/javax/validation/validation-api/1.0.0.GA/validation-api-1.0.0.GA-sources.jar"
\end{listing-lisp}

To actually load the dependency, use the \code{JAVA:ADD-TO-CLASSPATH} generic
function:

\begin{listing-lisp}
CL-USER> (java:add-to-classpath (abcl-asdf:resolve-dependencies "com.google.gwt" "gwt-user"))
\end{listing-lisp}

Notice that all recursive dependencies have been located and installed
locally from the network as well.

\section{asdf-jar}

The asdf-jar contrib provides a system for packaging ASDF systems into
jar archives for ABCL.  Given a running ABCL image with loadable ASDF
systems the code in this package will recursively package all the
required source and fasls in a jar archive.

\section{jss}
\label{section:jss}

To one used to a syntax that can construct macros the Java syntax
may be said to suck, so we introduce the \code{SHARPSIGN-DOUBLE-QUOTE} \#" macro.

\subsection{JSS usage}

Example:

\begin{listing-lisp}
CL-USER> (require 'jss)

CL-USER) (#"getProperties" 'java.lang.System)

CL-USER) (#"propertyNames" (#"getProperties" 'java.lang.System))
\end{listing-lisp}

\section{asdf-install}

The asdf-install contrib provides an implementation of ASDF-INSTALL.
Superseded by Quicklisp (see Xach2011 \cite{Xach2011}).

The \code{require} of the \code{asdf-install} symbol has the side
effect of pushing the directory ``~/.asdf-install-dir/systems/'' into
the value of the \textsc{ASDF} central registry in
\code{asdf:*central-registry*}, providing a convenient mechanism for
stashing \textsc{ABCL} specific system definitions for convenient
access.

\chapter{History}

\textsc{ABCL} was originally the extension language for the J editor, which was
started in 1998 by Peter Graves.  Sometime in 2003, a whole lot of
code that had previously not been released publically was suddenly
committed that enabled ABCL to be plausibly termed an emergent ANSI
Common Lisp implementation canidate.

From 2006 to 2008, Peter manned the development lists, incorporating
patches as made sense.  After a suitable search, Peter nominated Erik
H\"{u}lsmann to take over the project.

In 2008, the implementation was transferred to the current
maintainers, who have strived to improve its usability as a
contemporary Common Lisp implementation.

On October 22, 2011, with the publication of this Manual explicitly
stating the conformance of Armed Bear Common Lisp to \textsc{ANSI}, we released
abcl-1.0.0.



\begin{thebibliography}{9}

\label{_:1}
\bibitem{Java2000}
  ``A New Era for Java Protocol Handlers.''
  \url{http://java.sun.com/developer/onlineTraining/protocolhandlers/}

\label{_:XACH2011}
\bibitem{Xach2011}
  Zach Beene
  ``Quicklisp:  A system for quickly constructing Common Lisp''
  \url{http://www.quicklisp.org/}

\bibitem{Rhodes2007}
Christopher Rhodes
``User-extensible Sequences in Common Lisp''
ILC '07 Proceedings of the 2007 International Lisp Conference
% An early draft.  XXX where is the real one?
\url{http://jcsu.jesus.cam.ac.uk/~csr21/spec.pdf}

\end{thebibliography}

\printindex

\end{document}

% TODO
%   1.  Create mechanism for swigging DocString and Lisp docs into
%       sections ('grovel.lisp')

