source: trunk/abcl/doc/manual/abcl.tex @ 13657

Last change on this file since 13657 was 13657, checked in by ehuelsmann, 12 years ago

Change date of transfer of maintainership.
Add description of more JAVA package primitives.

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