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

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

Contributors section (needs formatting).

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