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

Last change on this file since 13648 was 13648, checked in by Mark Evenson, 12 years ago

Manual editing, setting dates correctly.

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