source: branches/1.0.x/abcl/doc/manual/abcl.tex @ 13659

Last change on this file since 13659 was 13659, checked in by Mark Evenson, 10 years ago

Correct history to note 2008 as the transfer from Peter Graves to Erik Huelsmann.

File size: 40.0 KB
Line 
1% -*- mode: latex; -*-
2% http://en.wikibooks.org/wiki/LaTeX/
3\documentclass[10pt]{book}
4\usepackage{abcl}
5
6\begin{document}
7\title{A Manual for Armed Bear Common Lisp}
8\date{October 21, 2011}
9\author{Mark~Evenson, Erik~Huelsmann, Alessio~Stalla, Ville~Voutilainen}
10
11\maketitle
12
13\chapter{Introduction}
14
15Armed Bear is a (mostly) conforming implementation of the ANSI Common
16Lisp standard.  This manual documents the Armed Bear Common Lisp
17implementation for users of the system.
18
19\subsection{Version}
20This manual corresponds to abcl-1.0.0, released on October 22, 2011.
21
22\subsection{License}
23
24The implementation is licensed under the terms of the GPL v2 of June
251991 with the ``classpath-exception'' that makes its deployment in
26commercial settings quite reasonable.  The license is viral in the
27sense that if you change the implementation, and redistribute those
28changes, you are required to provide the source to those changes back
29to be merged with the public trunk.
30
31\subsection{Contributors}
32
33% TODO format this better, optionally link to URI
34
35% Thanks for the markup
36Philipp Marek
37
38% Thanks for the whacky IKVM stuff and keeping the flame alive
39Douglas Miles
40
41% Thanks for JSS
42Alan Ruttenberg
43
44and of course
45
46Peter Graves
47
48\chapter{Running}
49
50\textsc{ABCL} is packaged as a single jar file usually named either
51``abcl.jar'' or possibly``abcl-1.0.0.jar'' if one is using a versioned
52package from your system vendor.  This byte archive can be executed
53under the control of a suitable JVM by using the ``-jar'' option to
54parse the manifest, and select the named class
55(\code{org.armedbear.lisp.Main}) for execution, viz:
56
57\begin{listing-shell}
58  cmd$ java -jar abcl.jar
59\end{listing-shell}
60
61N.b. for the proceeding command to work, the ``java'' executable needs
62to be in your path.
63
64To make it easier to facilitate the use of ABCL in tool chains (such
65as SLIME \footnote{SLIME is the Superior Lisp Mode for Interaction
66  under Emacs}) the invocation is wrapped in a Bourne shell script
67under UNIX or a DOS command script under Windows so that ABCL may be
68executed simply as:
69
70\begin{listing-shell}
71  cmd$ abcl
72\end{listing-shell}
73
74\section{Options}
75
76ABCL supports the following command line options:
77
78\begin{verbatim}
79--help
80    Displays this message.
81--noinform
82    Suppresses the printing of startup information and banner.
83--noinit
84    Suppresses the loading of the '~/.abclrc' startup file.
85--nosystem
86    Suppresses loading the 'system.lisp' customization file.
87--eval <FORM>
88    Evaluates the <FORM> before initializing REPL.
89--load <FILE>
90    Loads the file <FILE> before initializing REPL.
91--load-system-file <FILE>
92    Loads the system file <FILE> before initializing REPL.
93--batch
94    The process evaluates forms specified by arguments and possibly by those
95    by those in the intialization file '~/.abcl', and then exits.
96
97The occurance of '--' copies the remaining arguments, unprocessed, into
98the variable EXTENSIONS:*COMMAND-LINE-ARGUMENT-LIST*.
99\end{verbatim}
100
101All of the command line arguments which follow the occurrence of ``----''
102are passed into a list bound to the EXT:*COMMAND-LINE-ARGUMENT-LIST*
103variable.
104
105\section{Initialization}
106
107If the ABCL process is started without the ``--noinit'' flag, it
108attempts to load a file named ``.abclrc'' located in the user's home
109directory and then interpret its contents. 
110
111The user's home directory is determined by the value of the JVM system
112property ``user.home''.  This value may--or may not--correspond to the
113value of the HOME system environment variable at the discretion of the
114JVM implementation that \textsc{ABCL} finds itself hosted upon.
115
116\chapter{Conformance}
117
118\section{ANSI Common Lisp}
119\textsc{ABCL} is currently a (non)-conforming ANSI Common Lisp
120implementation due to the following known issues:
121
122\begin{itemize}
123  \item The generic function signatures of the DOCUMENTATION symbol do
124    not match the CLHS.
125  \item The TIME form does not return a proper VALUES environment to
126    its caller.
127\end{itemize}
128
129Somewhat confusingly, this statement of non-conformance in the
130accompanying user documentation fullfills the requirements that
131\textsc{ABCL} is a conforming ANSI Common Lisp implementation
132according to the CLHS \footnote{Common Lisp Hyperspec language
133  reference document.}.  Clarifications to this point are solicited.
134
135ABCL aims to be be a fully conforming ANSI Common Lisp implementation.
136Any other behavior should be reported as a bug.
137
138\section{Contemporary Common Lisp}
139In addition to ANSI conformance, \textsc{ABCL} strives to implement features
140expected of a contemporary Common Lisp \footnote{i.e. a Lisp of the
141  post 2005 Renaissance}
142
143\subsection{Deficiencies}
144The following known problems detract from \textsc{ABCL} being a proper
145contemporary Comon Lisp.
146\begin{itemize}
147  \item An incomplete implementation of a properly named metaobject
148    protocol (viz. (A)MOP \footnote{Another Metaobject Protocol} )
149
150    % N.b.
151    % TODO go through AMOP with symbols, starting by looking for
152    % matching function signature.
153    % XXX is this really blocking ANSI conformance?  Answer: we have
154    % to start with such a ``census'' to determine what we have.
155
156  \item Incomplete streams abstraction, in that \textsc{ABCL} needs suitable
157    abstraction between ANSI and Gray streams.  The streams could be
158    optimized to the JVM NIO abstractions at great profit for binary
159    byte-level manipulations.
160   
161  \item Incomplete documentation (missing docstrings from exported
162      symbols.
163
164\end{itemize}
165
166\chapter{Interaction with Hosting JVM}
167
168%  Plan of Attack
169%
170% describe calling Java from Lisp, and calling Lisp from Java,
171% probably in two separate sections.  Presumably, we can partition our
172% audience into those who are more comfortable with Java, and those
173% that are more comforable with Lisp
174
175The Armed Bear Common Lisp implementation is hosted on a Java Virtual
176Machine.  This chapter describes the mechanisms by which the
177implementation interacts with that hosting mechanism.
178
179\section{Lisp to Java}
180
181\textsc{ABCL} offers a number of mechanisms to interact with Java from its
182Lisp environment. It allows calling both instance and static methods
183of Java objects, manipulation of instance and static fields on Java
184objects, and construction of new Java objects.
185
186When calling Java routines, some values will automatically be
187converted by the FFI \footnote{FFI stands for Foreign Function
188  Interface which is the term of art which describes how a Lisp
189  implementation encapsulates invocation in other languages.}  from
190Lisp values to Java values. These conversions typically apply to
191strings, integers and floats. Other values need to be converted to
192their Java equivalents by the programmer before calling the Java
193object method. Java values returned to Lisp are also generally
194converted back to their Lisp counterparts. Some operators make an
195exception to this rule and do not perform any conversion; those are
196the ``raw'' counterparts of certain FFI functions and are recognizable
197by their name ending with \code{-RAW}.
198
199\subsection{Low-level Java API}
200
201We define a higher level Java API in the \ref{topic:Higher level Java
202  API: JSS}(JSS package) which is available in the \code{contrib/} \ref{topic:contrib}
203directory. This package is described later in this document.  This
204section covers the lower level API directly available after evaluating
205\code{(require 'JAVA)}.
206
207\subsubsection{Calling Java Object Methods}
208
209There are two ways to call a Java object method in the low-level (basic) API:
210
211\begin{itemize}
212\item Call a specific method reference (which was previously acquired)
213\item Dynamic dispatch using the method name and
214  the call-specific arguments provided by finding the
215  \ref{section:Parameter matching for FFI dynamic dispatch}{best match}.
216\end{itemize}
217
218The dynamic dispatch variant is discussed in the next section.
219
220\code{JAVA:JMETHOD} is used to acquire a specific method reference.
221The function takes at two or more arguments. The first is Java class designator
222(a \code{JAVA:JAVA-CLASS} object returned by \code{JAVA:JCLASS} or a string naming
223a Java class). The second is a string naming the method.
224
225Any arguments beyond the first two should be strings naming Java classes with
226one exception as listed in the next paragraph. These
227classes specify the types of the arguments for the method to be returned.
228
229There's additional calling convention to the \code{JAVA:JMETHOD} function:
230When the method is called with three parameters and the last parameter is an
231integer, the first method by that name and matching number of parameters is
232returned.
233
234Once one has a reference to the method, one may invoke it using
235\code{JAVA:JCALL}, which takes the method as the first argument. The
236second argument is the object instance to call the method on, or
237\code{NIL} in case of a static method.  Any remaining parameters are
238used as the remaining arguments for the call.
239
240\subsubsection{Calling Java object methods: dynamic dispatch}
241
242The second way of calling Java object methods is by using dynamic dispatch.
243In this case \code{JAVA:JCALL} is used directly without acquiring a method
244reference first. In this case, the first argument provided to \code{JAVA:JCALL}
245is a string naming the method to be called. The second argument is the instance
246on which the method should be called and any further arguments are used to
247select the best matching method and dispatch the call.
248
249\subsubsection{Dynamic dispatch: Caveats}
250
251Dynamic dispatch is performed by using the Java reflection
252API \footnote{The Java reflection API is found in the
253  \code{java.lang.reflect} package}. Generally the dispatch works
254fine, but there are corner cases where the API does not correctly
255reflect all the details involved in calling a Java method. An example
256is the following Java code:
257
258\begin{listing-java}
259ZipFile jar = new ZipFile("/path/to/some.jar");
260Object els = jar.entries();
261Method method = els.getClass().getMethod("hasMoreElements");
262method.invoke(els);
263\end{listing-java}
264
265even though the method \code{hasMoreElements()} is public in \code{Enumeration},
266the above code fails with
267
268\begin{listing-java}
269java.lang.IllegalAccessException: Class ... can
270not access a member of class java.util.zip.ZipFile\$2 with modifiers
271"public"
272       at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:65)
273       at java.lang.reflect.Method.invoke(Method.java:583)
274       at ...
275\end{listing-java}
276
277because the method has been overridden by a non-public class and the
278reflection API, unlike javac, is not able to handle such a case.
279
280While code like that is uncommon in Java, it is typical of ABCL's FFI
281calls. The code above corresponds to the following Lisp code:
282
283\begin{listing-lisp}
284(let ((jar (jnew "java.util.zip.ZipFile" "/path/to/some.jar")))
285  (let ((els (jcall "entries" jar)))
286    (jcall "hasMoreElements" els)))
287\end{listing-lisp}
288
289except that the dynamic dispatch part is not shown.
290
291To avoid such pitfalls, all Java objects in \textsc{ABCL} carry an extra
292field representing the ``intended class'' of the object. That is the class
293that is used first by \code{JAVA:JCALL} and similar to resolve methods;
294the actual class of the object is only tried if the method is not found
295in the intended class. Of course, the intended class is always a super-class
296of the actual class - in the worst case, they coincide. The intended class
297is deduced by the return type of the method that originally returned
298the Java object; in the case above, the intended class of \code{ELS}
299is \code{java.util.Enumeration} because that's the return type of
300the \code{entries} method.
301
302While this strategy is generally effective, there are cases where the
303intended class becomes too broad to be useful. The typical example
304is the extraction of an element from a collection, since methods in
305the collection API erase all types to \code{Object}. The user can
306always force a more specific intended class by using the \code{JAVA:JCOERCE}
307operator.
308
309% \begin{itemize}
310% \item Java values are accessible as objects of type JAVA:JAVA-OBJECT.
311% \item The Java FFI presents a Lisp package (JAVA) with many useful
312%   symbols for manipulating the artifacts of expectation on the JVM,
313%   including creation of new objects \ref{JAVA:JNEW}, \ref{JAVA:JMETHOD}), the
314%   introspection of values \ref{JAVA:JFIELD}, the execution of methods
315%   (\ref{JAVA:JCALL}, \ref{JAVA:JCALL-RAW}, \ref{JAVA:JSTATIC})
316% \item The JSS package (\ref{JSS}) in contrib introduces a convenient macro
317%   syntax \ref{JSS:SHARPSIGN_DOUBLEQUOTE_MACRO} for accessing Java
318%   methods, and additional convenience functions.
319% \item Java classes and libraries may be dynamically added to the
320%   classpath at runtime (JAVA:ADD-TO-CLASSPATH).
321% \end{itemize}
322
323\subsubsection{Calling Java class static methods}
324
325Like with non-static methods, references to static methods can be acquired
326by using the \code{JAVA:JMETHOD} primitive. In order to call this method,
327it's not possible to use the \code{JAVA:JCALL} primitive however: there's a
328separate API to retrieve a reference to static methods. This
329primitive is called \code{JAVA:JSTATIC}.
330
331Like \code{JAVA:JCALL}, \code{JAVA:JSTATIC} supports dynamic dispatch by
332passing the name of the method as a string instead of passing a method reference.
333The parameter values should be values to pass in the function call instead of
334a specification of classes for each parameter.
335
336\subsubsection{Parameter matching for FFI dynamic dispatch}
337
338The algorithm used to resolve the best matching method given the name
339and the arguments' types is the same as described in the Java Language
340Specification. Any deviation should be reported as a bug.
341
342% ###TODO reference to correct JLS section
343
344\subsubsection{Instantiating Java objects}
345
346Java objects can be instantiated (created) from Lisp by calling
347a constructor from the class of the object to be created. The same way
348\code{JAVA:JMETHOD} is used to acquire a method reference, the
349\code{JAVA:JCONSTRUCTOR} primitive can be used to acquire a constructor
350reference. It's arguments specify the types of arguments of the constructor
351method the same way as with \code{JAVA:JMETHOD}.
352
353The constructor can't be passed to \code{JAVA:JCALL}, but instead should
354be passed as an argument to \code{JAVA:JNEW}.
355
356\section{Lisp from Java}
357
358In order to access the Lisp world from Java, one needs to be aware
359of a few things. The most important ones are listed below.
360
361\begin{itemize}
362\item All Lisp values are descendants of LispObject.java
363\item In order to
364\item Lisp symbols are accessible via either directly referencing the
365  Symbol.java instance or by dynamically introspecting the
366  corresponding Package.java instance.
367\item The Lisp dynamic environment may be saved via
368  \code{LispThread.bindSpecial(Binding)} and restored via
369  \code{LispThread.resetSpecialBindings(Mark)}.
370\item Functions may be executed by invocation of the
371  Function.execute(args [...])
372\end{itemize}
373
374\subsection{Lisp FFI}
375
376FFI stands for "Foreign Function Interface" which is the phase which
377the contemporary Lisp world refers to methods of "calling out" from
378Lisp into "foreign" languages and environments.  This document
379describes the various ways that one interacts with Lisp world of ABCL
380from Java, considering the hosted Lisp as the "Foreign Function" that
381needs to be "Interfaced".
382
383\subsection{Calling Lisp from Java}
384
385Note: As the entire ABCL Lisp system resides in the org.armedbear.lisp
386package the following code snippets do not show the relevant import
387statements in the interest of brevity.  An example of the import
388statement would be
389
390\begin{listing-java}
391  import org.armedbear.lisp.*;
392\end{listing-java}
393
394to potentially import all the JVM symbol from the `org.armedbear.lisp'
395namespace.
396
397Per JVM, there can only ever be a single Lisp interpreter.  This is
398started by calling the static method `Interpreter.createInstance()`.
399
400\begin{listing-java}
401  Interpreter interpreter = Interpreter.createInstance();
402\end{listing-java}
403
404If this method has already been invoked in the lifetime of the current
405Java process it will return null, so if you are writing Java whose
406life-cycle is a bit out of your control (like in a Java servlet), a
407safer invocation pattern might be:
408
409\begin{listing-java}
410  Interpreter interpreter = Interpreter.getInstance();
411  if (interpreter == null) {
412    interpreter = Interpreter.createInstance();
413  }
414\end{listing-java}
415
416
417The Lisp \code{eval} primitive may be simply passed strings for evaluation,
418as follows
419
420\begin{listing-java}
421  String line = "(load \"file.lisp\")";
422  LispObject result = interpreter.eval(line);
423\end{listing-java}
424
425Notice that all possible return values from an arbitrary Lisp
426computation are collapsed into a single return value.  Doing useful
427further computation on the ``LispObject'' depends on knowing what the
428result of the computation might be, usually involves some amount
429of \code{instanceof} introspection, and forms a whole topic to itself
430(c.f. [Introspecting a LispObject])
431
432Using \code{eval} involves the Lisp interpreter.  Lisp functions may
433be directly invoked by Java method calls as follows.  One simply
434locates the package containing the symbol, then obtains a reference to
435the symbol, and then invokes the \code{execute()} method with the
436desired parameters.
437
438\begin{listing-java}
439    interpreter.eval("(defun foo (msg) (format nil \"You told me '~A'~%\" msg))");
440    Package pkg = Packages.findPackage("CL-USER");
441    Symbol foo = pkg.findAccessibleSymbol("FOO");
442    Function fooFunction = (Function)foo.getSymbolFunction();
443    JavaObject parameter = new JavaObject("Lisp is fun!");
444    LispObject result = fooFunction.execute(parameter);
445    // How to get the "naked string value"?
446    System.out.println("The result was " + result.writeToString());
447\end{listing-java}
448
449If one is calling an primitive function in the CL package the syntax
450becomes considerably simpler.  If we can locate the instance of
451definition in the ABCL Java source, we can invoke the symbol directly.
452For instance, to tell if a `LispObject` contains a reference to a symbol.
453
454\begin{listing-java}
455    boolean nullp(LispObject object) {
456      LispObject result = Primitives.NULL.execute(object);
457      if (result == NIL) { // the symbol 'NIL' is explicitly named in the Java
458                           // namespace at ``Symbol.NIL''
459                           // but is always present in the
460                           // local namespace in its unadorned form for
461                           // the convenience of the User.
462        return false;
463      }
464      return true;
465   }
466\end{listing-java}
467
468\subsubsection{Introspecting a LispObject}
469\label{topic:Introspecting a LispObject}
470
471We present various patterns for introspecting an an arbitrary
472`LispObject` which can represent the result of every Lisp evaluation
473into semantics that Java can meaningfully deal with.
474
475\subsubsection{LispObject as \code{boolean}}
476
477If the LispObject a generalized boolean values, one can use
478\code{getBooleanValue()} to convert to Java:
479
480\begin{listing-java}
481     LispObject object = Symbol.NIL;
482     boolean javaValue = object.getBooleanValue();
483\end{listing-java}
484
485Although since in Lisp, any value other than NIL means "true"
486(so-called generalized Boolean), the use of Java equality it quite a
487bit easier to type and more optimal in terms of information it conveys
488to the compiler would be:
489
490\begin{listing-java}
491    boolean javaValue = (object != Symbol.NIL);
492\end{listing-java}
493
494\paragraph{LispObject is a list}
495
496If LispObject is a list, it will have the type `Cons`.  One can then use
497the \code{copyToArray} to make things a bit more suitable for Java
498iteration.
499
500\begin{listing-java}
501    LispObject result = interpreter.eval("'(1 2 4 5)");
502    if (result instanceof Cons) {
503      LispObject array[] = ((Cons)result.copyToArray());
504      ...
505    }
506\end{listing-java}
507
508A more Lispy way to iterated down a list is to use the `cdr()` access
509function just as like one would traverse a list in Lisp:;
510
511\begin{listing-java}
512    LispObject result = interpreter.eval("'(1 2 4 5)");
513    while (result != Symbol.NIL) {
514      doSomething(result.car());
515      result = result.cdr();
516    }
517\end{listing-java}
518
519\subsection{Java Scripting API (JSR-223)}
520
521ABCL can be built with support for JSR-223, which offers a
522language-agnostic API to invoke other languages from Java. The binary
523distribution downloadable from ABCL's common-lisp.net home is built
524with JSR-223 support. If you're building ABCL from source on a pre-1.6
525JVM, you need to have a JSR-223 implementation in your CLASSPATH (such
526as Apache Commons BSF 3.x or greater) in order to build ABCL with
527JSR-223 support; otherwise, this feature will not be built.
528
529This section describes the design decisions behind the ABCL JSR-223
530support. It is not a description of what JSR-223 is or a tutorial on
531how to use it. See
532http://trac.common-lisp.net/armedbear/browser/trunk/abcl/examples/jsr-223
533for example usage.
534
535\subsubsection{Conversions}
536
537In general, ABCL's implementation of the JSR-223 API performs implicit
538conversion from Java objects to Lisp objects when invoking Lisp from
539Java, and the opposite when returning values from Java to Lisp. This
540potentially reduces coupling between user code and ABCL. To avoid such
541conversions, wrap the relevant objects in \code{JavaObject} instances.
542
543\subsubsection{Implemented JSR-223 interfaces}
544
545JSR-223 defines three main interfaces, of which two (Invocable and
546Compilable) are optional. ABCL implements all the three interfaces -
547ScriptEngine and the two optional ones - almost completely. While the
548JSR-223 API is not specific to a single scripting language, it was
549designed with languages with a more or less Java-like object model in
550mind: languages such as Javascript, Python, Ruby, which have a concept
551of "class" or "object" with "fields" and "methods". Lisp is a bit
552different, so certain adaptations were made, and in one case a method
553has been left unimplemented since it does not map at all to Lisp.
554
555\subsubsection{The ScriptEngine}
556
557The main interface defined by JSR-223, javax.script.ScriptEngine, is
558implemented by the class
559\code{org.armedbear.lisp.scripting.AbclScriptEngine}. AbclScriptEngine
560is a singleton, reflecting the fact that ABCL is a singleton as
561well. You can obtain an instance of AbclScriptEngine using the
562AbclScriptEngineFactory or by using the service provider mechanism
563through ScriptEngineManager (refer to the javax.script documentation).
564
565\subsubsection{Startup and configuration file}
566
567At startup (i.e. when its constructor is invoked, as part of the
568static initialization phase of AbclScriptEngineFactory) the ABCL
569script engine attempts to load an "init file" from the classpath
570(/abcl-script-config.lisp). If present, this file can be used to
571customize the behaviour of the engine, by setting a number of
572variables in the ABCL-SCRIPT package. Here is a list of the available
573variables:
574
575\begin{itemize}
576\item *use-throwing-debugger* Controls whether ABCL uses a
577  non-standard debugging hook function to throw a Java exception
578  instead of dropping into the debugger in case of unhandled error
579  conditions.
580  \begin{itemize}
581  \item Default value: T
582  \item Rationale: it is more convenient for Java programmers using
583    Lisp as a scripting language to have it return exceptions to Java
584    instead of handling them in the Lisp world.
585  \item Known Issues: the non-standard debugger hook has been reported
586    to misbehave in certain circumstances, so consider disabling it if
587    it doesn't work for you.
588  \end{itemize}
589\item *launch-swank-at-startup* If true, Swank will be launched at
590  startup. See *swank-dir* and *swank-port*.
591  \begin{itemize}
592  \item Default value: NIL
593  \end{itemize}
594\item *swank-dir* The directory where Swank is installed. Must be set
595  if *launch-swank-at-startup* is true.
596\item *swank-port* The port where Swank will listen for
597  connections. Must be set if *launch-swank-at-startup* is true.
598  \begin{itemize}
599  \item Default value: 4005
600  \end{itemize}
601\end{itemize}
602
603Additionally, at startup the AbclScriptEngine will \code{(require
604  'asdf)} - in fact, it uses asdf to load Swank.
605
606\subsubsection{Evaluation}
607
608Code is read and evaluated in the package ABCL-SCRIPT-USER. This
609packages USEs the COMMON-LISP, JAVA and ABCL-SCRIPT packages. Future
610versions of the script engine might make this default package
611configurable. The \code{CL:LOAD} function is used under the hood for
612evaluating code, and thus the same behavior of LOAD is
613guaranteed. This allows, among other things, \code{IN-PACKAGE} forms
614to change the package in which the loaded code is read.
615
616It is possible to evaluate code in what JSR-223 calls a
617"ScriptContext" (basically a flat environment of name->value
618pairs). This context is used to establish special bindings for all the
619variables defined in it; since variable names are strings from Java's
620point of view, they are first interned using READ-FROM-STRING with, as
621usual, ABCL-SCRIPT-USER as the default package. Variables are declared
622special because CL's \code{LOAD}, \code{EVAL} and \code{COMPILE}
623functions work in a null lexical environment and would ignore
624non-special bindings.
625
626Contrary to what the function \code{LOAD} does, evaluation of a series
627of forms returns the value of the last form instead of T, so the
628evaluation of short scripts does the Right Thing.
629
630\subsubsection{Compilation}
631
632AbclScriptEngine implements the \code{javax.script.Compilable}
633interface. Currently it only supports compilation using temporary
634files. Compiled code, returned as an instance of
635javax.script.CompiledScript, is read, compiled and executed by default
636in the ABCL-SCRIPT-USER package, just like evaluated code. Differently
637from evaluated code, though, due to the way the ABCL compiler works,
638compiled code contains no reference to top-level self-evaluating
639objects (like numbers or strings). Thus, when evaluated, a piece of
640compiled code will return the value of the last non-self-evaluating
641form: for example the code "(do-something) 42" will return 42 when
642interpreted, but will return the result of (do-something) when
643compiled and later evaluated. To ensure consistency of behavior
644between interpreted and compiled code, make sure the last form is
645always a compound form - at least (identity some-literal-object). Note
646that this issue should not matter in real code, where it is unlikely a
647top-level self-evaluating form will appear as the last form in a file
648(in fact, the Common Lisp load function always returns T upon success;
649with JSR-223 this policy has been changed to make evaluation of small
650code snippets work as intended).
651
652\subsubsection{Invocation of functions and methods}
653
654AbclScriptEngine implements the \code{javax.script.Invocable}
655interface, which allows to directly call Lisp functions and methods,
656and to obtain Lisp implementations of Java interfaces. This is only
657partially possible with Lisp since it has functions, but not methods -
658not in the traditional OO sense, at least, since Lisp methods are not
659attached to objects but belong to generic functions. Thus, the method
660\code{invokeMethod()} is not implemented and throws an
661UnsupportedOperationException when called. The \code{invokeFunction()}
662method should be used to call both regular and generic functions.
663
664\subsubsection{Implementation of Java interfaces in Lisp}
665
666ABCL can use the Java reflection-based proxy feature to implement Java
667interfaces in Lisp. It has several built-in ways to implement an
668interface, and supports definition of new ones. The
669\code{JAVA:JMAKE-PROXY} generic function is used to make such
670proxies. It has the following signature:
671
672\code{jmake-proxy interface implementation \&optional lisp-this ==> proxy}
673
674\code{interface} is a Java interface metaobject (e.g. obtained by
675invoking \code{jclass}) or a string naming a Java
676interface. \code{implementation} is the object used to implement the
677interface - several built-in methods of jmake-proxy exist for various
678types of implementations. \code{lisp-this} is an object passed to the
679closures implementing the Lisp "methods" of the interface, and
680defaults to \code{NIL}.
681
682The returned proxy is an instance of the interface, with methods
683implemented with Lisp functions.
684
685Built-in interface-implementation types include:
686
687\begin{itemize}
688\item a single Lisp function which upon invocation of any method in
689  the interface will be passed the method name, the Lisp-this object,
690  and all the parameters. Useful for interfaces with a single method,
691  or to implement custom interface-implementation strategies.
692\item a hash-map of method-name -> Lisp function mappings. Function
693  signature is \code{(lisp-this \&rest args)}.
694\item a Lisp package. The name of the Java method to invoke is first
695  transformed in an idiomatic Lisp name (\code{javaMethodName} becomes
696  \code{JAVA-METHOD-NAME}) and a symbol with that name is searched in
697  the package. If it exists and is fbound, the corresponding function
698  will be called. Function signature is as the hash-table case.
699\end{itemize}
700
701This functionality is exposed by the AbclScriptEngine with the two
702methods getInterface(Class) and getInterface(Object, Class). The
703former returns an interface implemented with the current Lisp package,
704the latter allows the programmer to pass an interface-implementation
705object which will in turn be passed to the jmake-proxy generic
706function.
707
708\chapter{Implementation Dependent Extensions}
709
710As outlined by the CLHS ANSI conformance guidelines, we document the
711extensions to the Armed Bear Lisp implementation made accessible to
712the user by virtue of being an exported symbol in the JAVA, THREADS,
713or EXTENSIONS packages.
714
715\section{JAVA}
716
717\subsection{Modifying the JVM CLASSPATH}
718
719The JAVA:ADD-TO-CLASSPATH generic functions allows one to add the
720specified pathname or list of pathnames to the current classpath
721used by ABCL, allowing the dynamic loading of JVM objects:
722
723\begin{listing-lisp}
724CL-USER> (add-to-classpath "/path/to/some.jar")
725\end{listing-lisp}
726
727N.b \code{add-to-classpath} only affects the classloader used by ABCL
728(the value of the special variable \code{JAVA:*CLASSLOADER*}. It has
729no effect on Java code outside ABCL.
730
731\subsection{API}
732
733% include autogen docs for the JAVA package.
734\include{java}
735
736\section{THREADS}
737
738The extensions for handling multithreaded execution are collected in
739the \code{THREADS} package.  Most of the abstractions in Doug Lea's
740excellent \code{java.util.concurrent} packages may be manipulated
741directly via the JSS contrib to great effect.
742
743\subsection{API}
744
745% include autogen docs for the THREADS package.
746\include{threads}
747
748\section{EXTENSIONS}
749
750The symbols in the EXTENSIONS package (nicknamed ``EXT'') constitutes
751extensions to the ANSI standard that are potentially useful to the
752user.  They include functions for manipulating network sockets,
753running external programs, registering object finalizers, constructing
754reference weakly held by the garbage collector and others.
755
756See \ref{Extensible Sequences} for a generic function interface to
757the native JVM contract for \code{java.util.List}.
758
759\subsection{API}
760
761% include autogen docs for the EXTENSIONS package.
762\include{extensions}
763
764\chapter{Beyond ANSI}
765
766Naturally, in striving to be a useful contemporary Common Lisp
767implementation, ABCL endeavors to include extensions beyond the ANSI
768specification which are either widely adopted or are especially useful
769in working with the hosting JVM.
770
771\section{Implementation Dependent}
772\begin{enumerate}
773  \item Compiler to JVM 5 bytecode
774  \item Pathname extensions
775\end{enumerate}
776
777\section{Pathname}
778
779We implement an extension to the Pathname that allows for the
780description and retrieval of resources named in a URI scheme that the
781JVM ``understands''.  Support is built-in to the ``http'' and
782``https'' implementations but additional protocol handlers may be
783installed at runtime by having JVM symbols present in the
784sun.net.protocol.dynmamic pacakge. See [JAVA2006] for more details.
785
786ABCL has created specializations of the ANSI Pathname object to
787enable to use of URIs to address dynamically loaded resources for the
788JVM.  A URL-PATHNAME has a corresponding URL whose cannoical
789representation is defined to be the NAMESTRING of the Pathname.
790
791\begin{verbatim}
792  JAR-PATHNAME isa URL-PATHNAME isa PATHNAME
793\end{verbatim}
794
795Both URL-PATHNAME and JAR-PATHNAME may be used anywhere a PATHNAME is
796accepted with the following caveats:
797
798\begin{itemize}
799
800\item A stream obtained via OPEN on a URL-PATHNAME cannot be the
801  target of write operations.
802
803\item No canonicalization is performed on the underlying URI (i.e. the
804implementation does not attempt to compute the current name of the
805representing resource unless it is requested to be resolved.)  Upon
806resolution, any cannoicalization procedures followed in resolving the
807resource (e.g. following redirects) are discarded. 
808
809\end{itemize}
810
811The implementation of URL-PATHNAME allows the ABCL user to laod dynamically
812code from the network.  For example, for Quicklisp.
813
814\begin{listing-lisp}
815  CL-USER> (load "http://beta.quicklisp.org/quicklisp.lisp")
816\end{listing-lisp}
817
818will load and execute the Quicklisp setup code.
819
820\ref{XACH2011}
821
822\subsubsection{Implementation}
823
824\textsc{DEVICE} either a string denoting a drive letter under DOS or a cons
825specifying a \textsc{URL-PATHNAME}.
826         
827\section{Extensible Sequences}
828
829See \ref{RHODES2007} RHODES2007 for the design.
830
831The SEQUENCE package fully implements Christopher Rhodes' proposal for
832extensible sequences.  These user extensible sequences are used
833directly in \code{java-collections.lisp} provide these CLOS
834abstractions on the standard Java collection classes as defined by the
835\code{java.util.List} contract.
836
837This extension is not automatically loaded by the implementation.   It
838may be loaded via:
839
840\begin{listing-lisp}
841CL-USER> (require 'java-collections)
842\end{listing-lisp}
843
844if both extensible sequences and their application to Java collections
845is required, or
846
847\begin{listing-lisp}
848CL-USER> (require 'extensible-sequences)
849\end{listing-lisp}
850
851if only the extensible sequences API as specified in \ref{RHODES2007} is
852required.
853
854Note that \code{(require 'java-collections)} must be issued before
855\code{java.util.List} or any subclass is used as a specializer in a CLOS
856method definition (see the section below).
857
858\section{Extensions to CLOS}
859
860There is an additional syntax for specializing the parameter of a
861generic function on a java class, viz. \code{(java:jclass CLASS-STRING)}
862where \code{CLASS-STRING} is a string naming a Java class in dotted package
863form.
864
865For instance the following specialization would perhaps allow one to
866print more information about the contents of a java.util.Collection
867object
868
869\begin{listing-lisp}
870(defmethod print-object ((coll (java:jclass "java.util.Collection"))
871                         stream)
872  ;;; ...
873)
874\end{listing-lisp}
875
876If the class had been loaded via a classloader other than the original
877the class you wish to specialize on, one needs to specify the
878classloader as an optional third argument.
879
880\begin{listing-lisp}
881
882(defparameter *other-classloader*
883  (jcall "getBaseLoader" cl-user::*classpath-manager*))
884 
885(defmethod print-object ((device-id (java:jclass "dto.nbi.service.hdm.alcatel.com.NBIDeviceID" *other-classloader*))
886                         stream)
887  ;;; ...
888)
889\end{listing-lisp}
890
891\section{Extensions to the Reader}
892
893We implement a special hexadecimal escape sequence for specifying
894characters to the Lisp reader, namely we allow a sequences of the form
895\# \textbackslash Uxxxx to be processed by the reader as character
896whose code is specified by the hexadecimal digits ``xxxx''.  The
897hexadecimal sequence must be exactly four digits long \footnote{This
898  represents a compromise with contemporary in 2011 32bit hosting
899  architecures for which we wish to make text processing efficient.
900  Should the User require more control over UNICODE processing we
901  recommend Edi Weisz' excellent work with FLEXI-STREAMS which we
902  fully support}, padded by leading zeros for values less than 0x1000.
903
904Note that this sequence is never output by the implementation.  Instead,
905the corresponding Unicode character is output for characters whose
906code is greater than 0x00ff.
907
908\subsection{JSS optionally extends the Reader}
909
910The JSS contrib consitutes an additional, optional extension to the
911reader in the definition of the \#\" reader macro.
912
913\section{ASDF}
914
915asdf-2.017.22 is packaged as core component of ABCL, but not
916intialized by default, as it relies on the CLOS subsystem which can
917take a bit of time to initialize.  It may be initialized by the ANSI
918\textsc{REQUIRE} mechanism as follows:
919
920\begin{listing-lisp}
921CL-USER> (require 'asdf)
922\end{listing-lisp}
923
924\chapter{Contrib}
925
926\section{abcl-asdf}
927
928This contrib to ABCL enables an additional syntax for ASDF system
929definition which dynamically loads JVM artifacts such as jar archives
930via a Maven encapsulation.  The Maven Aether can also be directly
931manipulated by the function associated with the RESOLVE-DEPENDENCIES symbol.
932
933%ABCL specific contributions to ASDF system definition mainly concerned
934%with finding JVM artifacts such as jar archives to be dynamically loaded.
935
936
937The following ASDF components are added: \textsc{JAR-FILE}, \textsc{JAR-DIRECTORY},
938\textsc{CLASS-FILE-DIRECTORY} and \textsc{MVN}.
939
940
941
942\subsection{ABCL-ASDF Examples}
943
944\begin{listing-lisp}
945    ;;;; -*- Mode: LISP -*-
946    (in-package :asdf)
947
948    (defsystem :log4j
949      :components ((:mvn "log4j/log4j"
950                    :version "1.4.9")))
951\end{listing-lisp}
952
953\subsection{abcl-asdf API}
954
955We define an API as consisting of the following ASDF classes:
956
957\textsc{JAR-DIRECTORY}, \textsc{JAR-FILE}, and
958\textsc{CLASS-FILE-DIRECTORY} for JVM artifacts that have a currently
959valid pathname representation
960
961And the MVN and IRI classes descend from ASDF-COMPONENT, but do not
962directly have a filesystem location.
963
964For use outside of ASDF, we currently define one method,
965\textsc{RESOLVE-DEPENDENCIES} which locates, downloads, caches, and then loads
966into the currently executing JVM process all recursive dependencies
967annotated in the Maven pom.xml graph.
968
969\subsection{ABCL-ASDF Example 2}
970
971Bypassing ASDF, one can directly issue requests for the Maven
972artifacts to be downloaded
973
974\begin{listing-lisp}
975    CL-USER> (abcl-asdf:resolve-dependencies "com.google.gwt" "gwt-user")
976    WARNING: Using LATEST for unspecified version.
977    "/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"
978\end{listing-lisp}
979
980To actually load the dependency, use the JAVA:ADD-TO-CLASSPATH generic
981function:
982
983\begin{listing-lisp}
984    CL-USER> (java:add-to-classpath (abcl-asdf:resolve-dependencies "com.google.gwt" "gwt-user"))
985\end{listing-lisp}
986
987Notice that all recursive dependencies have been located and installed
988locally from the network as well.
989
990
991\section{asdf-jar}
992
993ASDF-JAR provides a system for packaging ASDF systems into jar
994archives for ABCL.  Given a running ABCL image with loadable ASDF
995systems the code in this package will recursively package all the
996required source and fasls in a jar archive.
997
998\section{jss}
999
1000To one used to a syntax that can construct macros, the Java syntax
1001sucks, so we introduce the \#" macro.
1002
1003\subsection{JSS usage}
1004
1005Example:
1006
1007\begin{listing-lisp}
1008  CL-USER> (require 'jss)
1009
1010  CL-USER) (#"getProperties" 'java.lang.System)
1011
1012  CL-USER) (#"propertyNames" (#"getProperties" 'java.lang.System))
1013\end{listing-lisp}
1014
1015\section{asdf-install}
1016
1017An implementation of ASDF-INSTALL.  Superseded by Quicklisp (qv.)
1018
1019\chapter{History}
1020
1021ABCL was originally the extension language for the J editor, which was
1022started in 1998 by Peter Graves.  Sometime in 2003, a whole lot of
1023code that had previously not been released publically was suddenly
1024committed that enabled ABCL to be plausibly termed an emergent ANSI
1025Common Lisp implementation canidate.
1026
1027From 2006 to 2008, Peter manned the development lists, incorporating
1028patches as made sense.  After a suitable search, Peter nominated Erik
1029Huelsmann to take over the project.
1030
1031In 2008, the implementation was transferred to the current
1032maintainers, who have strived to improve its usability as a
1033contemporary Common Lisp implementation.
1034
1035On October 22, 2011, with the publication of this Manual explicitly
1036stating the conformance of Armed Bear Common Lisp to ANSI, we released
1037abcl-1.0.0.
1038
1039
1040
1041
1042\section{References}
1043
1044[Java2000]:  A New Era for Java Protocol Handlers.
1045\url{http://java.sun.com/developer/onlineTraining/protocolhandlers/}
1046
1047[Xach2011]:  Quicklisp:  A system for quickly constructing Common Lisp
1048libraries.  \url{http://www.quicklisp.org/}
1049
1050[RHODES2007]:  Christopher Rhodes
1051
1052
1053\end{document}
1054
1055% TODO
1056%   1.  Create mechanism for swigging DocString and Lisp docs into
1057%       sections ('grovel.lisp')
1058
Note: See TracBrowser for help on using the repository browser.