abcl.tex 59.8 KB
Newer Older
% -*- mode: latex; -*-
3 4

6 7 8
\usepackage{hyperref} % Put this one last, it redefines lots of internals

\title{Armed Bear Common Lisp User Manual}
\date{Version 1.4.0-dev\\
April 2015}
14 15
\author{Mark Evenson \and Erik H\"{u}lsmann \and Rudolf Schlatte \and
  Alessio Stalla \and Ville Voutilainen}

17 18

%%Preface to the Fourth edition, abcl-1.3.
\subsection{Preface to the Fourth Edition}

\textsc{ABCL} 1.3 now implements an optimized implementation of the
24 25
LispStack abstraction thanks to Dmitry Nadezhin which runs on ORCL
JVMs from 1.[5-8] conformantly.
26 27 28 29 30 31

%%Preface to the Third edition, abcl-1.2.
\subsection{Preface to the Third Edition}
The implementation now contains a performant and conformant
implementation of (A)MOP to the point of inclusion in CLOSER-MOP's
test suite.

%%Preface to the second edition, abcl-1.1.

35 36
\subsection{Preface to the Second Edition}

\textsc{ABCL} 1.1 now contains \textsc{(A)MOP}.  We hope you enjoy!  --The Mgmt.


41 42 43 44 45
Armed Bear Common Lisp (\textsc{ABCL}) is an implementation of Common
Lisp that runs on the Java Virtual Machine.  It compiles Common Lisp
to Java 5 bytecode \footnote{The class file version is ``49.0''.},
providing the following integration methods for interfacing with Java
code and libraries:
46 47 48 49 50 51 52 53 54 55 56
\item Lisp code can create Java objects and call their methods (see
  Section~\ref{sec:lisp-java}, page~\pageref{sec:lisp-java}).
\item Java code can call Lisp functions and generic functions, either
  directly (Section~\ref{sec:calling-lisp-from-java},
  page~\pageref{sec:calling-lisp-from-java}) or via \texttt{JSR-223}
\item \code{jinterface-implementation} creates Lisp-side implementations
  of Java interfaces that can be used as listeners for Swing classes and
57 58 59 60 61 62 63
\item \code{java:jnew-runtime-class} can inject fully synthetic Java
  classes--and their objects-- into the current JVM process whose
  behavior is specified via closures expressed in Common Lisp.. \footnote{Parts of
    the current implementation are not fully finished, so the status
    of some interfaces here should be treated with skepticism if you
    run into problems.}

65 66
\textsc{ABCL} is supported by the Lisp library manager
\textsc{QuickLisp}\footnote{\url{}} and can run many of the
67 68 69 70
programs and libraries provided therein out-of-the-box.


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

\item The generic function signatures of the \code{CL:DOCUMENTATION} symbol
  do not match the specification.
\item The \code{CL:TIME} form does not return a proper \code{CL:VALUES}
  environment to its caller.
\item When merging pathnames and the defaults point to a \code{EXT:JAR-PATHNAME},
82 83 84 85 86
  we set the \code{DEVICE} of the result to \code{:UNSPECIFIC} if the pathname to be
  be merged does not contain a specified \code{DEVICE}, does not contain a
  specified \code{HOST}, does contain a relative \code{DIRECTORY}, and we are
  not running on a \textsc{MSFT} Windows platform.\footnote{The intent of this
    rather arcane sounding deviation from conformance is so that the
    result of a merge won't fill in a \code{DEVICE} with the wrong "default
    device for the host" in the sense of the fourth paragraph in the
    \textsc{CLHS} description of MERGE-PATHNAMES (see in \cite{CLHS} the paragraph beginning
90 91 92 93 94
    "If the PATHNAME explicitly specifies a host and not a device…").
    A future version of the implementation may return to conformance
    by using the \code{HOST} value to reflect the type explicitly.


97 98 99 100 101
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 Common Lisp HyperSpec~\cite{CLHS}.  Clarifications to this point
are solicited.

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

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

111 112
The following known problems detract from \textsc{ABCL} being a proper
contemporary Common Lisp.
114 115 116 117 118 119
\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 Incomplete streams abstraction, in that \textsc{ABCL} needs
120 121 122 123 124 125
  suitable abstraction between \textsc{ANSI} and Gray
  streams.  \footnote{The streams could be optimized to the
    \textsc{JVM} NIO \cite{nio} abstractions at great profit for
    binary byte-level manipulations.}
\item Incomplete documentation (missing docstrings from exported
  symbols and the draft status of this user manual).
126 127 128 129 130


132 133 134
\textsc{ABCL} is licensed under the terms of the \textsc{GPL} v2 of
June 1991 with the ``classpath-exception'' (see the file
\texttt{COPYING} in the source distribution \footnote{See
  \url{}} for
136 137 138 139 140 141 142
the license, term 13 in the same file for the classpath exception).
This license broadly means that you must distribute the sources to
ABCL, including any changes you make, together with a program that
includes ABCL, but that you are not required to distribute the sources
of the whole program.  Submitting your changes upstream to the ABCL
development team is actively encouraged and very much appreciated, of


146 147 148 149 150
\item Philipp Marek \texttt{Thanks for the markup}
\item Douglas Miles \texttt{Thanks for the whacky IKVM stuff and keeping the flame alive
  in the dark years.}
\item Alan Ruttenberg \texttt{Thanks for JSS.}
151 152 153
\item and of course
\emph{Peter Graves}


\chapter{Running ABCL}


\textsc{ABCL} is packaged as a single jar file usually named either
\texttt{abcl.jar} or possibly something like \texttt{abcl-1.3.0.jar} if
161 162
using a versioned package on the local filesystem from your system
vendor.  This jar file can be executed from the command line to obtain a
163 164 165
\textsc{REPL}\footnote{Read-Eval Print Loop, a Lisp command-line}, viz:

166 167

  cmd$ java -jar abcl.jar
\end{listing-shell} %$ unconfuse Emacs syntax highlighting

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

174 175 176 177 178
To facilitate the use of ABCL in tool chains such as SLIME~\cite{slime}
(the Superior Lisp Interaction Mode for Emacs), we provide both a Bourne
shell script and a \textsc{DOS} batch file.  If you or your
administrator adjusted the path properly, ABCL may be executed simply
179 180

  cmd$ abcl
182 183 184

Probably the easiest way of setting up an editing environment using the
\textsc{Emacs} editor is to use \textsc{Quicklisp} and follow the instructions at
187 188 189


ABCL supports the following command line options:

192 193
\index{Command Line Options}

195 196 197 198 199 200 201 202 203
\item[\texttt{  --help}] displays a help message.
\item[\texttt{  --noinform}] Suppresses the printing of startup information and banner.
\item[\texttt{  --noinit}] suppresses the loading of the \verb+~/.abclrc+ startup file.
\item[\texttt{  --nosystem}] suppresses loading the \texttt{system.lisp} customization file. 
\item[\texttt{  --eval FORM}] evaluates FORM before initializing the REPL.
\item[\texttt{  --load FILE}] loads the file FILE before initializing the REPL.
\item[\texttt{  --load-system-file FILE}] loads the system file FILE before initializing the REPL.
\item[\texttt{  --batch}] evaluates forms specified by arguments and in
  the initialization file \verb+~/.abclrc+, and then exits without
  starting a \textsc{REPL}.
205 206 207 208 209

All of the command line arguments following the occurrence of \verb+--+
are passed unprocessed into a list of strings accessible via the
variable \code{EXT:*COMMAND-LINE-ARGUMENT-LIST*} from within ABCL.
210 211 212


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

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

\chapter{Interaction with the Hosting JVM}

225 226
%  Plan of Attack
227 228 229 230 231
% 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

232 233 234 235
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}

239 240 241 242 243
\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.

244 245 246 247 248 249 250 251 252 253 254 255 256
When calling Java routines, some values will automatically be
converted by the FFI\footnote{Foreign Function Interface, is the term
  of art for the part of a Lisp implementation which implements
  calling code written in other languages, typically normalized to the
  local C compiler calling conventions.}  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

\subsection{Low-level Java API}

260 261 262 263 264
This subsection covers the low-level API available after evaluating
\code{(require 'JAVA)}.  A higher level Java API, developed by Alan
Ruttenberg, is available in the \code{contrib/} directory and described
later in this document, see Section~\ref{section:jss} on page

\subsubsection{Calling Java Object Methods}

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

\item Call a specific method reference (which was previously acquired)
272 273 274
\item Dynamic dispatch using the method name and the call-specific
  arguments provided by finding the best match (see
275 276

277 278 279 280 281
\code{JAVA:JMETHOD} is used to acquire a specific method reference.  The
function takes two or more arguments. The first is a 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.

283 284 285
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.

287 288 289
When \code{JAVA:JMETHOD} 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 a method reference has been acquired, it can be invoked using
292 293 294 295
\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.
296 297 298 299 300 301 302 303 304 305

\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}

308 309 310 311 312 313
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:
314 315 316 317 318 319 320 321

ZipFile jar = new ZipFile("/path/to/some.jar");
Object els = jar.entries();
Method method = els.getClass().getMethod("hasMoreElements");

322 323
Even though the method \code{hasMoreElements()} is public in
\code{Enumeration}, the above code fails with
324 325 326

java.lang.IllegalAccessException: Class ... can
not access a member of class\$2 with modifiers
328 329 330 331 332 333
       at sun.reflect.Reflection.ensureMemberAccess(
       at java.lang.reflect.Method.invoke(
       at ...

334 335
This is because the method has been overridden by a non-public class and
the reflection API, unlike \texttt{javac}, is not able to handle such a case.
336 337 338 339 340 341 342 343 344 345 346 347

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:

(let ((jar (jnew "" "/path/to/some.jar")))
  (let ((els (jcall "entries" jar)))
    (jcall "hasMoreElements" els)))

except that the dynamic dispatch part is not shown.

To avoid such pitfalls, all Java objects in \textsc{ABCL} carry an extra
349 350 351 352 353 354 355 356 357
field representing the ``intended class'' of the object. That class 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 is the
return type of the \code{entries} method.
358 359 360 361 362 363 364

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}
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379

% \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}

380 381
\subsubsection{Calling Java class static methods}

382 383 384
Like non-static methods, references to static methods can be acquired by
using the \code{JAVA:JMETHOD} primitive. Static methods are called with
\code{JAVA:JSTATIC} instead of \code{JAVA:JCALL}.
385 386 387 388 389 390

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}

394 395
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

400 401 402
\subsubsection{Instantiating Java objects}

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

408 409 410
The obtained constructor is passed as an argument to \code{JAVA:JNEW},
together with any arguments.  \code{JAVA:JNEW} can also be invoked with
a string naming the class as its first argument.

\subsubsection{Accessing Java object and class fields}

414 415 416 417
Fields in Java objects can be accessed using the getter and setter
functions \code{JAVA:JFIELD} and \code{(SETF JAVA:JFIELD)}.  Static
(class) fields are accessed the same way, but with a class object or
string naming a class as first argument.
418 419

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
421 422
be converted.

\section{Java to Lisp}

425 426 427
This section describes the various ways that one interacts with Lisp
from Java code.  In order to access the Lisp world from Java, one needs
to be aware of a few things, the most important ones being listed below:
428 429

430 431 432 433
\item All Lisp values are descendants of \code{LispObject}.
\item Lisp symbols are accessible either via static members of the
  \code{Symbol} class, or by dynamically introspecting a \code{Package}
\item The Lisp dynamic environment may be saved via
435 436
  \code{LispThread.bindSpecial(Binding)} and restored via
437 438
\item Functions can be executed by invoking \code{LispObject.execute(args
439 440

\subsection{Calling Lisp from Java}

444 445 446 447
Note: the entire ABCL Lisp system resides in the
\texttt{org.armedbear.lisp} package, but the following code snippets do
not show the relevant import statements in the interest of brevity.  An
example of the import statement would be
  import org.armedbear.lisp.*;
451 452
to potentially import all the JVM symbol from the `org.armedbear.lisp'

454 455 456
There can only ever be a single Lisp interpreter per JVM instance.  A
reference to this interpreter is obtained by calling the static method

  Interpreter interpreter = Interpreter.createInstance();
461 462

If this method has already been invoked in the lifetime of the current
463 464 465
Java process it will return \texttt{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:

468 469 470 471
  Interpreter interpreter = Interpreter.getInstance();
  if (interpreter == null) {
    interpreter = Interpreter.createInstance();
472 473


The Lisp \code{eval} primitive may simply be passed strings for evaluation:

478 479
  String line = "(load \"file.lisp\")";
  LispObject result = interpreter.eval(line);
481 482 483

Notice that all possible return values from an arbitrary Lisp
computation are collapsed into a single return value.  Doing useful
484 485
further computation on the \code{LispObject} depends on knowing what the
result of the computation might be.  This usually involves some amount
of \code{instanceof} introspection, and forms a whole topic to itself
487 488
(see Section~\ref{topic:Introspecting a LispObject},
page~\pageref{topic:Introspecting a LispObject}).

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

497 498 499 500 501 502 503 504 505
  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()); 

508 509 510 511 512
If one is calling a function in the CL package, the syntax can become
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 \code{LispObject} is (Lisp) \texttt{NIL}, we can invoke the
CL function \code{NULL} in the following way:

515 516 517 518 519 520 521 522 523 524 525
  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;

528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551
\subsubsection{Multiple Values}

After a call to a function that returns Lisp multiple values, the
values are associated with the executing \code{LispThread} until the
next call into Lisp.  One may access the values object as a list of
\code{LispObject} instances via a call to \code{getValues()} on that
thread reference
as evidenced by the following code:


  org.armedbear.lisp.Package cl = Packages.findPackage("CL");
  Symbol valuesSymbol = cl.findAccessibleSymbol("VALUES");
  LispObject[] valuesArgs = {
    LispInteger.getInstance(1), LispInteger.getInstance(2)
  // equivalent to ``(values 1 2)''
  LispObject result = valuesSymbol.execute(valuesArgs); 
  LispObject[] values = LispThread.currentThread().getValues();
  for (LispObject value: values) {
    System.out.println("value ==> " + value.printObject());

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

555 556
We present various patterns for introspecting an arbitrary
\code{LispObject} which can hold the result of every Lisp evaluation
into semantics that Java can meaningfully deal with.

\paragraph{LispObject as \code{boolean}}

561 562
If the \code{LispObject} is to be interpreted as a generalized boolean
value, one can use \code{getBooleanValue()} to convert to Java:

565 566
   LispObject object = Symbol.NIL;
   boolean javaValue = object.getBooleanValue();

569 570 571
Since in Lisp any value other than \code{NIL} means "true", Java
equality can also be used, which is a bit easier to type and better in
terms of information it conveys to the compiler:

    boolean javaValue = (object != Symbol.NIL);

\paragraph{LispObject as a list}

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

584 585 586 587 588
  LispObject result = interpreter.eval("'(1 2 4 5)");
  if (result instanceof Cons) {
    LispObject array[] = ((Cons)result.copyToArray());

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

595 596 597 598 599
  LispObject result = interpreter.eval("'(1 2 4 5)");
  while (result != Symbol.NIL) {
    result = result.cdr();

602 603
\section{Java Scripting API (JSR-223)}

605 606 607 608 609 610 611
ABCL can be built with support for JSR-223~\cite{jsr-223}, which offers
a language-agnostic API to invoke other languages from Java. The binary
distribution download-able from ABCL's homepage 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.

613 614 615
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
for example usage.


621 622 623 624 625
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.

\subsection{Implemented JSR-223 interfaces}

629 630 631 632 633 634 635 636 637
JSR-223 defines three main interfaces, of which two (\code{Invocable}
and \code{Compilable}) are optional. ABCL implements all the three
interfaces - \code{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.
638 639 640

\subsubsection{The ScriptEngine}

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

\subsection{Start-up and configuration file}

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

660 661
\item[\texttt{*use-throwing-debugger*}] controls whether ABCL uses a
662 663 664
  non-standard debugging hook function to throw a Java exception
  instead of dropping into the debugger in case of unhandled error
  \item Default value: \texttt{T}
667 668 669 670 671 672
  \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.
674 675
\item[\texttt{*launch-swank-at-startup*}] If true, Swank will be launched at
  startup. See \texttt{*swank-dir*} and \texttt{*swank-port*}.
  \item Default value: \texttt{NIL}
679 680 681 682 683
\item[\texttt{*swank-dir*}] The directory where Swank is installed. Must be set
  if \texttt{*launch-swank-at-startup*} is true.
\item[\texttt{*swank-port*}] The port where Swank will listen for
  connections. Must be set if \texttt{*launch-swank-at-startup*} is
684 685 686
  \item Default value: 4005

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


694 695 696 697 698 699 700 701
Code is read and evaluated in the package \code{ABCL-SCRIPT-USER}. This
packages \texttt{USE}s the \code{COMMON-LISP}, \code{JAVA} and
\code{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 behavior of
\code{LOAD} is guaranteed. This allows, among other things,
\code{IN-PACKAGE} forms to change the package in which the loaded code
is read.
702 703

It is possible to evaluate code in what JSR-223 calls a
``ScriptContext'' (basically a flat environment of name$\rightarrow$value
705 706
pairs). This context is used to establish special bindings for all the
variables defined in it; since variable names are strings from Java's
707 708
point of view, they are first interned using \code{READ-FROM-STRING} with, as
usual, \code{ABCL-SCRIPT-USER} as the default package. Variables are declared
709 710 711 712 713 714 715
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.


AbclScriptEngine implements the \code{javax.script.Compilable}
720 721
interface. Currently it only supports compilation using temporary
files. Compiled code, returned as an instance of
722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739
\texttt{javax.script.CompiledScript}, is read, compiled and executed by
default in the \texttt{ABCL-SCRIPT-USER} package, just like evaluated
code.  In contrast to 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 ``\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 \code{(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 \texttt{T} upon success; with JSR-223 this policy has been changed
to make evaluation of small code snippets work as intended).

\subsection{Invocation of functions and methods}

741 742 743 744 745 746 747
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
\texttt{UnsupportedOperationException} when called. The \code{invokeFunction()}
method should be used to call both regular and generic functions.

\subsection{Implementation of Java interfaces in Lisp}

753 754 755 756 757
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:
758 759 760

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

761 762 763 764 765 766 767
\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}.

769 770
The returned proxy is an instance of the interface, with methods
implemented with Lisp functions.
771 772 773 774

Built-in interface-implementation types include:

775 776 777 778
\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 $\rightarrow$ Lisp function mappings. Function
780 781 782 783 784 785
  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.
786 787

788 789 790 791 792 793
This functionality is exposed by the class \code{AbclScriptEngine} via
the two methods \code{getInterface(Class)} and
\code{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 \code{jmake-proxy} generic function.

795 796 797 798 799
\subsection{Implementation of Java classes in Lisp}


\chapter{Implementation Dependent Extensions}

802 803 804 805 806 807 808 809 810 811
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.


\subsection{Modifying the JVM CLASSPATH}

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

CL-USER> (add-to-classpath "/path/to/some.jar")

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

823 824 825 826
\subsection{Creating a synthetic Java Class at Runtime}


% include autogen docs for the JAVA package.

830 831

832 833 834 835
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.


The symbols in the EXTENSIONS package (nicknamed ``EXT'') constitutes
extensions to the \textsc{ANSI} standard that are potentially useful to the
844 845 846
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 \cite{RHODES2007} for a generic function interface to the native
\textsc{JVM} contract for \code{java.util.List}.

% include autogen docs for the EXTENSIONS package.

\chapter{Beyond ANSI}
855 856 857 858

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 \textsc{JVM}.

861 862 863 864 865 866
\section{Compiler to Java 5 Bytecode}

The \code{CL:COMPILE-FILE} interface emits a packed fasl format whose
Pathname has the type  ``abcl''.  These fasls are operating system neutral
byte archives packaged by the zip compression format which contain
artifacts whose loading \code{CL:LOAD} understands.
867 868 869


870 871
We implement an extension to the \code{CL:PATHNAME} that allows for
the description and retrieval of resources named in a
\textsc{URI} \footnote{A \textsc{URI} is essentially a superset of
  what is commonly understood as a \textsc{URL} We sometime suse the
874 875 876
  term URL as shorthand in describing the URL Pathnames, even though
  the corresponding encoding is more akin to a URI as described in
  RFC3986 \cite{rfc3986}.}  scheme that the \textsc{JVM}
877 878 879
``understands''.  By definition, support is built-in into the JVM to
access the ``http'' and ``https'' schemes but additional protocol
handlers may be installed at runtime by having \textsc{JVM} symbols
880 881
present in the \code{} package. See
\cite{maso2000} for more details.
882 883 884 885

\textsc{ABCL} has created specializations of the ANSI
\code{CL:PATHNAME} object to enable to use of \textsc{URI}s to address
dynamically loaded resources for the JVM.  The \code{EXT:URL-PATHNAME}
specialization has a corresponding \textsc{URI} whose canonical
representation is defined to be the \code{NAMESTRING} of the
\code{CL:PATHNAME}. The \code{EXT:JAR-PATHNAME} extension further
889 890
specializes the the \code{EXT:URL-PATHNAME} to provide access to
components of zip archives.  
891 892

% RDF description of type hierarchy 
% TODO Render via some LaTeX mode for graphviz?
894 895
  @prefix ext:   <> .
  @prefix cl:    <> .
897 898 899
  <ext:jar-pathname> a <ext:url-pathname>.
  <ext:url-pathname> a <cl:pathname>.
  <cl:logical-pathname> a <cl:pathname> .
901 902

903 904 905 906 907 908


909 910 911
Both the \code{EXT:URL-PATHNAME} and \code{EXT:JAR-PATHNAME} objects
may be used anywhere a \code{CL:PATHNAME} is accepted with the
following caveats:


915 916
\item A stream obtained via \code{CL:OPEN} on a \code{CL:URL-PATHNAME}
  cannot be the target of write operations.

\item Any results of canonicalization procedures performed on the
920 921 922
  underlying \textsc{URI} are discarded between resolutions (i.e. the
  implementation does not attempt to cache the results of current name
  resolution of the representing resource unless it is requested to be
  resolved.)  Upon resolution, any canonicalization procedures
924 925
  followed in resolving the resource (e.g. following redirects) are
  discarded.  Users may programatically initiate a new, local
926 927
  computation of the resolution of the resource by applying the
  \code{CL:TRUENAME} function to a \code{EXT:URL-PATHNAME} object.
  Depending on the reliability and properties of your local
929 930 931
  \textsc{REST} infrastructure, these results may not necessarily be
  idempotent over time\footnote {See \cite{evenson2011} for the draft
    of the publication of the technical details}.

933 934

The implementation of \code{EXT:URL-PATHNAME} allows the \textsc{ABCL}
user to dynamically load code from the network.  For example,
937 938
\textsc{Quicklisp} (\cite{quicklisp}) may be completely installed from
the \textsc{REPL} as the single form:
939 940

  CL-USER> (load "")
942 943

will load and execute the Quicklisp setup code.

The implementation currently breaks \textsc{ANSI} conformance by allowing the
types able to be \code{CL:READ} for the \code{DEVICE} to return a possible \code{CONS} of
\code{CL:PATHNAME} objects.  %% citation from CLHS needed.

950 951 952 953
In order to ``smooth over'' the bit about types being \code{CL:READ}
from \code{CL:PATHNAME} components, we extend the semantics for the
usual PATHNAME merge semantics when \code{*DEFAULT-PATHNAME-DEFAULTS*}
contains a \code{EXT:JAR-PATHNAME} with the ``do what I mean''
algorithm described in \ref{section:conformance} on page

%See \ref{_:quicklisp} on page \pageref{_:quicklisp}.
958 959 960


The implementation of these extensions stores all the additional
information in the \code{CL:PATHNAME} object itself in ways that while strictly
963 964 965 966 967
speaking are conformant, nonetheless may trip up libraries that don't
expect the following:

\item \code{DEVICE} can be either a string denoting a drive letter
968 969 970 971 972
  under \textsc{DOS} or a list of exactly one or two elements.  If
  \code{DEVICE} is a list, it denotes a \code{EXT:JAR-PATHNAME}, with
  the entries containing \code{CL:PATHNAME} objects which describe the
  outer and (possibly inner) locations of the jar
  archive \footnote{The case of inner and outer
973 974 975
    \code{EXT:JAR-PATHNAME} \ref{EXT:JAR-PATHNAME} arises when zip
    archives themselves contain zip archives which is the case when
    the ABCL fasl is included in the abcl.jar zip archive.}.
976 977

\item A \code{EXT:URL-PATHNAME} always has a \code{HOST} component that is a
978 979 980 981 982 983 984 985 986 987 988
  property list.  The values of the \code{HOST} property list are
  always character strings.  The allowed keys have the following meanings:
  \item[:SCHEME] Scheme of URI ("http", "ftp", "bundle", etc.)
  \item[:AUTHORITY] Valid authority according to the URI scheme.  For
    "http" this could be "". 
  \item[:QUERY] The query of the \textsc{URI} 
  \item[:FRAGMENT] The fragment portion of the \textsc{URI}

\item In order to encapsulate the implementation decisions for these
  meanings, the following functions provide a SETF-able API for
990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
  reading and writing such values: \code{URL-PATHNAME-QUERY},
  \code{URL-PATHNAME-SCHEME}.  The specific subtype of a Pathname may
  be determined with the predicates \code{PATHNAME-URL-P} and







1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053
\section{Package-Local Nicknames}

ABCL allows giving packages local nicknames: they allow short and
easy-to-use names to be used without fear of name conflict associated
with normal nicknames.\footnote{Package-local nicknames were originally
developed in SBCL.}

A local nickname is valid only when inside the package for which it
has been specified. Different packages can use same local nickname for
different global names, or different local nickname for same global

Symbol \code{:package-local-nicknames} in \code{*features*} denotes the
support for this feature.

The options to \code{defpackage} are extended with a new option
\code{:local-nicknames (local-nickname actual-package-name)*}.

The new package has the specified local nicknames for the corresponding
actual packages.

(defpackage :bar (:intern "X"))
(defpackage :foo (:intern "X"))
(defpackage :quux (:use :cl)
  (:local-nicknames (:bar :foo) (:foo :bar)))
(find-symbol "X" :foo) ; => FOO::X
(find-symbol "X" :bar) ; => BAR::X
(let ((*package* (find-package :quux)))
  (find-symbol "X" :foo))               ; => BAR::X
(let ((*package* (find-package :quux)))
  (find-symbol "X" :bar))               ; => FOO::X

--- Function: \textbf{package-local-nicknames} [\textbf{ext}] \textit{package-designator}

  Returns an ALIST of \code{(local-nickname . actual-package)}
1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111
  describing the nicknames local to the designated package.

  When in the designated package, calls to \code{find-package} with any
  of the local-nicknames will return the corresponding actual-package
  instead. This also affects all implied calls to \code{find-package},
  including those performed by the reader.

  When printing a package prefix for a symbol with a package local
  nickname, the local nickname is used instead of the real name in order
  to preserve print-read consistency.

--- Function: \textbf{package-locally-nicknamed-by-list} [\textbf{ext}] \textit{package-designator}

Returns a list of packages which have a local nickname for the
designated package.

--- Function: \textbf{add-package-local-nickname} [\textbf{ext}] \textit{local-nickname actual-package \&optional package-designator}

  Adds \code{local-nickname} for \code{actual-package} in the designated
  package, defaulting to current package. \code{local-nickname} must be
  a string designator, and \code{actual-package} must be a package

  Returns the designated package.

  Signals an error if \code{local-nickname} is already a package local
  nickname for a different package, or if \code{local-nickname} is one
  of "CL", "COMMON-LISP", or, "KEYWORD", or if \code{local-nickname} is
  a global name or nickname for the package to which the nickname would
  be added.

  When in the designated package, calls to \code{find-package} with the
  \code{local-nickname} will return the package the designated
  \code{actual-package} instead. This also affects all implied calls to
  \code{find-package}, including those performed by the reader.

  When printing a package prefix for a symbol with a package local
  nickname, local nickname is used instead of the real name in order to
  preserve print-read consistency.

--- Function: \textbf{remove-package-local-nickname} [\textbf{ext}] \textit{old-nickname \&optional package-designator}

  If the designated package had \code{old-nickname} as a local nickname
  for another package, it is removed. Returns true if the nickname
  existed and was removed, and \code{nil} otherwise.

1112 1113
\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
1119 1120
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.

1123 1124
%% an Example of using java.util.Lisp in Lisp would be nice

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

1128 1129 1130 1131 1132 1133 1134
CL-USER> (require 'java-collections)

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

1135 1136 1137
CL-USER> (require 'extensible-sequences)

if only the extensible sequences API as specified in \cite{RHODES2007} is
1140 1141 1142

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

\section{Extensions to CLOS}

1148 1149
\subsection{Metaobject Protocol}

1150 1151 1152
\textsc{ABCL} implements the metaobject protocol for \textsc{CLOS} as
specified in \textsc{(A)MOP}.  The symbols are exported from the
package \code{MOP}.

1154 1155 1156 1157 1158
Contrary to the AMOP specification and following \textsc{SBCL}'s lead,
the metaclass \code{funcallable-standard-object} has
\code{funcallable-standard-class} as metaclass instead of

1159 1160
\subsection{Specializing on Java classes}

There is an additional syntax for specializing the parameter of a
1162 1163
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
1164 1165 1166 1167 1168 1169

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

1170 1171 1172 1173 1174 1175
(defmethod print-object ((coll (java:jclass "java.util.Collection"))
  ;;; ...
1176 1177 1178 1179 1180

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.


1183 1184 1185
(defparameter *other-classloader*
  (jcall "getBaseLoader" cl-user::*classpath-manager*))
1186 1187 1188 1189
(defmethod print-object
   ((device-id (java:jclass "" 
1190 1191 1192 1193 1194
  ;;; ...

\section{Extensions to the Reader}

1196 1197 1198 1199
We implement a special hexadecimal escape sequence for specifying 32
bit characters to the Lisp reader\footnote{This represents a
  compromise with contemporary in 2011 32bit hosting architecures for
  which we wish to make text processing efficient.  Should the User
1200 1201
  require more control over \textsc{UNICODE} processing we recommend Edi Weisz'
  excellent work with \textsc|{FLEXI-STREAMS}  which we fully support}, namely we
allow a sequences of the form \verb~#\U~\emph{\texttt{xxxx}} to be processed
by the reader as character whose code is specified by the hexadecimal
digits \emph{\texttt{xxxx}}.  The hexadecimal sequence may be one to four digits
long.  % Why doesn't ALEXANDRIA work?
1206 1207 1208 1209

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.

\section{Overloading of the CL:REQUIRE Mechanism}

1213 1214
The \code{CL:REQUIRE} mechanism is overloaded by attaching these
semantics to the execution of \code{REQUIRE} on the following symbols:
1215 1216 1217


1218 1219
    Loads the \textsc{ASDF} implementation shipped
1220 1221 1222 1223 1224 1225 1226
    with the implementation.  After \textsc{ASDF} has been loaded in
    this manner, symbols passed to \code{CL:REQUIRE} which are
    otherwise unresolved, are passed to ASDF for a chance for
    resolution.  This means, for instance if \code{CL-PPCRE} can be
    located as a loadable \textsc{ASDF} system \code{(require
      'cl-ppcre)} is equivalent to \code{(asdf:load-system

1228 1229
    Locates and pushes the toplevel contents of
    ``abcl-contrib.jar'' into the \textsc{ASDF} central registry.  

1233 1234
      \item \code{abcl-asdf} 
        Functions for loading JVM artifacts
        dynamically, hooking into ASDF 3 objects where possible.
1236 1237
      \item \code{asdf-jar} 
        Package addressable JVM artifacts via
1238 1239
        \code{abcl-asdf} descriptions as a single binary artifact
        including recursive dependencies.
1240 1241 1242
      \item \code{mvn} 
        These systems name common JVM artifacts from
        the distributed pom.xml graph of Maven Aether:
          \item \code{jna} 
            Dynamically load 'jna.jar' version 4.1.0
1246 1247 1248
            from the network \footnote{This loading can be inhibited
              if, at runtime, the Java class corresponding
              ``:classname'' clause of the system defition is present.}
      \item \code{quicklisp-abcl} Boot a local Quicklisp installation
1251 1252 1253 1254 1255 1256 1257 1258
        via the ASDF:IRI type introduced via ABCL-ASDF.

      \item \code{jfli} A descendent of Rich Hickey's pre-Clojure work
        on the JVM.
      \item \code{jss} Introduces dynamic inspection of present
        symbols via the \code{SHARPSIGN-DOUBLE-QUOTE} macros as Java Syntax
      \item \code{asdf-install} DEPRECATED.  Scheduled for removal in 1.4.0.

1261 1262

1263 1264 1265 1266 1267
The user may extend the \code{CL:REQUIRE} mechanism by pushing
function hooks into \code{SYSTEM:*MODULE-PROVIDER-FUNCTIONS*}.  Each
such hook function takes a single argument containing the symbol
passed to \code{CL:REQUIRE} and returns a non-\code{NIL} value if it
can successful resolve the symbol.

\section{JSS extension of the Reader by SHARPSIGN-DOUBLE-QUOTE}
1270 1271

The JSS contrib consitutes an additional, optional extension to the
1272 1273 1274
reader in the definition of the \code{SHARPSIGN-DOUBLE-QUOTE}
(``\#\"'') reader macro.  See section \ref{section:jss} on page
\pageref{section:jss} for more information.