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

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

Add some documentation to the Java->Lisp and Lisp->Java sections.

File size: 20.4 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 2, 2011}
9\author{Mark~Evenson, Erik~Huelsmann, Alessio~Stallo, 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
24ABCL is packaged as a single jar file usually named either
25``abcl.jar'' or something like``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(org.armedbear.lisp.Main) for excution:
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 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}
90ABCL is currently a non-conforming ANSI Common Lisp implementation due
91to the following issues:
92
93\begin{itemize}
94  \item Missing statement of conformance in accompanying documentation
95  \item The generic function sigatures of the DOCUMENTATION symbol do
96    not match the CLHS.
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, 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
126ABCL offers a number of mechanisms to interact with Java from
127its lisp environment. It allows calling methods (and static methods) of
128Java objects, manipulation of fields and static fields and construction
129of new Java objects.
130
131When calling Java routines, some values will automatically be converted
132by the FFI from Lisp values to Java values. These conversions typically
133apply to strings, integers and floats. Other values need to be converted
134to their Java equivalents by the programmer before calling the Java
135object method.
136
137\subsection{Lowlevel Java API}
138
139There's a higher level Java API defined in the
140\ref{topic:Higher level Java API: JSS}(JSS package) which is available
141in the contrib/ directory. This package is described later in this
142document.  This section covers the lower level API directly available
143after evaluating \code{(require 'JAVA)}.
144
145\subsubsection{Calling Java object methods}
146
147There are two ways to call a Java object method in the basic API:
148
149\begin{itemize}
150\item Call a specific method reference (pre-acquired)
151\item Dynamic dispatch using the method name and
152  the call-specific arguments provided by finding the
153  \ref{section:Parameter matching for FFI dynamic dispatch}{best match}.
154\end{itemize}
155
156The dynamic dispatch variant is discussed in the next section.
157
158\code{JAVA:JMETHOD} is used to acquire a specific method reference.
159The function takes at two or more arguments. The first is Java class designator
160(a \code{JAVA:JAVA-CLASS} object returned by \code{JAVA:JCLASS} or a string naming
161a Java class). The second is a string naming the method.
162
163Any arguments beyond the first two should be strings naming Java classes with
164one exception as listed in the next paragraph. These
165classes specify the types of the arguments for the method to be returned.
166
167There's additional calling convention to the \code{JAVA:JMETHOD} function:
168When the method is called with three parameters and the last parameter is an
169integer, the first method by that name and matching number of parameters is
170returned.
171
172Once you have a reference to the method, you can call it using \code{JAVA:JCALL},
173which takes the method as the first argument. The second argument is the
174object instance to call the method on. Any remaining parameters are used
175as the remaining arguments for the call.
176
177\subsubsection{Calling Java object methods: dynamic dispatch}
178
179The second way of calling Java object methods is by using dynamic dispatch.
180In this case \code{JAVA:JCALL} is used directly without acquiring a method
181reference first. In this case, the first argument provided to \code{JAVA:JCALL}
182is a string naming the method to be called. The second argument is the instance
183on which the method should be called and any further arguments are used to
184select the best matching method and dispatch the call.
185
186% ###TODO document ``intended class''
187
188% \begin{itemize}
189% \item Java values are accessible as objects of type JAVA:JAVA-OBJECT.
190% \item The Java FFI presents a Lisp package (JAVA) with many useful
191%   symbols for manipulating the artifacts of expectation on the JVM,
192%   including creation of new objects \ref{JAVA:JNEW}, \ref{JAVA:JMETHOD}), the
193%   introspection of values \ref{JAVA:JFIELD}, the execution of methods
194%   (\ref{JAVA:JCALL}, \ref{JAVA:JCALL-RAW}, \ref{JAVA:JSTATIC})
195% \item The JSS package (\ref{JSS}) in contrib introduces a convenient macro
196%   syntax \ref{JSS:SHARPSIGN_DOUBLEQUOTE_MACRO} for accessing Java
197%   methods, and additional convenience functions.
198% \item Java classes and libraries may be dynamically added to the
199%   classpath at runtime (JAVA:ADD-TO-CLASSPATH).
200% \end{itemize}
201
202\subsubsection{Parameter matching for FFI dynamic dispatch}
203
204
205...
206
207\section{Lisp from Java}
208
209In order to access the Lisp world from Java, one needs to be aware
210of a few things. The most important ones are listed below.
211
212\begin{itemize}
213\item All Lisp values are descendants of LispObject.java
214\item In order to
215\item Lisp symbols are accessible via either directly referencing the
216  Symbol.java instance or by dynamically introspecting the
217  corresponding Package.java instance.
218\item The Lisp dynamic environment may be saved via
219  \code{LispThread.bindSpecial(Binding)} and restored via
220  \code{LispThread.resetSpecialBindings(Mark)}.
221\item Functions may be executed by invocation of the
222  Function.execute(args [...])
223\end{itemize}
224
225\subsection{Lisp FFI}
226
227FFI stands for "Foreign Function Interface" which is the phase which
228the contemporary Lisp world refers to methods of "calling out" from
229Lisp into "foreign" languages and environments.  This document
230describes the various ways that one interacts with Lisp world of ABCL
231from Java, considering the hosted Lisp as the "Foreign Function" that
232needs to be "Interfaced".
233
234\subsection{Calling Lisp from Java}
235
236Note: As the entire ABCL Lisp system resides in the org.armedbear.lisp
237package the following code snippets do not show the relevant import
238statements in the interest of brevity.  An example of the import
239statement would be
240
241\begin{listing-java}
242  import org.armedbear.lisp.*;
243\end{listing-java}
244
245to potentially import all the JVM symbol from the `org.armedbear.lisp'
246namespace.
247
248Per JVM, there can only ever be a single Lisp interpreter.  This is
249started by calling the static method `Interpreter.createInstance()`.
250
251\begin{listing-java}
252  Interpreter interpreter = Interpreter.createInstance();
253\end{listing-java}
254
255If this method has already been invoked in the lifetime of the current
256Java process it will return null, so if you are writing Java whose
257life-cycle is a bit out of your control (like in a Java servlet), a
258safer invocation pattern might be:
259
260\begin{listing-java}
261  Interpreter interpreter = Interpreter.getInstance();
262  if (interpreter == null) {
263    interpreter = Interpreter.createInstance();
264  }
265\end{listing-java}
266
267
268The Lisp \code{eval} primitive may be simply passed strings for evaluation,
269as follows
270
271\begin{listing-java}
272  String line = "(load \"file.lisp\")";
273  LispObject result = interpreter.eval(line);
274\end{listing-java}
275
276Notice that all possible return values from an arbitrary Lisp
277computation are collapsed into a single return value.  Doing useful
278further computation on the ``LispObject'' depends on knowing what the
279result of the computation might be, usually involves some amount
280of \code{instanceof} introspection, and forms a whole topic to itself
281(c.f. [Introspecting a LispObject])
282
283Using \code{eval} involves the Lisp interpreter.  Lisp functions may
284be directly invoked by Java method calls as follows.  One simply
285locates the package containing the symbol, then obtains a reference to
286the symbol, and then invokes the \code{execute()} method with the
287desired parameters.
288
289\begin{listing-java}
290    interpreter.eval("(defun foo (msg) (format nil \"You told me '~A'~%\" msg))");
291    Package pkg = Packages.findPackage("CL-USER");
292    Symbol foo = pkg.findAccessibleSymbol("FOO");
293    Function fooFunction = (Function)foo.getSymbolFunction();
294    JavaObject parameter = new JavaObject("Lisp is fun!");
295    LispObject result = fooFunction.execute(parameter);
296    // How to get the "naked string value"?
297    System.out.println("The result was " + result.writeToString());
298\end{listing-java}
299
300If one is calling an primitive function in the CL package the syntax
301becomes considerably simpler.  If we can locate the instance of
302definition in the ABCL Java source, we can invoke the symbol directly.
303For instnace, to tell if a `LispObject` contains a reference to a symbol.
304
305\begin{listing-java}
306    boolean nullp(LispObject object) {
307      LispObject result = Primitives.NULL.execute(object);
308      if (result == NIL) { // the symbol 'NIL' is explicity named in the Java
309                           // namespace at ``Symbol.NIL''
310                           // but is always present in the
311                           // localnamespace in its unadorned form for
312                           // the convenience of the User.
313        return false;
314      }
315      return true;
316   }
317\end{listing-java}
318
319\subsubsection{Introspecting a LispObject}
320\label{topic:Introspecting a LispObject}
321
322We present various patterns for introspecting an an arbitrary
323`LispObject` which can represent the result of every Lisp evaluation
324into semantics that Java can meaningfully deal with.
325
326\subsubsection{LispObject as \code{boolean}}
327
328If the LispObject a generalized boolean values, one can use
329\code{getBooleanValue()} to convert to Java:
330
331\begin{listing-java}
332     LispObject object = Symbol.NIL;
333     boolean javaValue = object.getBooleanValue();
334\end{listing-java}
335
336Although since in Lisp, any value other than NIL means "true"
337(so-called generalized Boolean), the use of Java equality it quite a
338bit easier to type and more optimal in terms of information it conveys
339to the compiler would be:
340
341\begin{listing-java}
342    boolean javaValue = (object != Symbol.NIL);
343\end{listing-java}
344
345\paragraph{LispObject is a list}
346
347If LispObject is a list, it will have the type `Cons`.  One can then use
348the \code{copyToArray} to make things a bit more suitable for Java
349iteration.
350
351\begin{listing-java}
352    LispObject result = interpreter.eval("'(1 2 4 5)");
353    if (result instanceof Cons) {
354      LispObject array[] = ((Cons)result.copyToArray());
355      ...
356    }
357\end{listing-java}
358   
359A more Lispy way to iterated down a list is to use the `cdr()` access
360function just as like one would traverse a list in Lisp:;
361
362\begin{listing-java}
363    LispObject result = interpreter.eval("'(1 2 4 5)");
364    while (result != Symbol.NIL) {
365      doSomething(result.car());
366      result = result.cdr();
367    }
368\end{listing-java}
369
370\chapter{Implementation Dependent Extensions}
371
372As outlined by the CLHS ANSI conformance guidelines, we document the
373extensions to the Armed Bear Lisp implementation made accessible to
374the user by virtue of being an exported symbol in the JAVA, THREADS,
375or EXTENSIONS packages.
376
377\section{JAVA}
378
379\subsection{Modifying the JVM CLASSPATH}
380
381The JAVA:ADD-TO-CLASSPATH generic functions allows one to add the
382specified pathname or list of pathnames to the current JVM classpath
383allowing the dynamic loading of JVM objects:
384
385\begin{listing-lisp}
386CL-USER> (add-to-classpath "/path/to/some.jar")
387\end{listing-lisp}
388
389\subsection{API}
390
391% include autogen docs for the JAVA package.
392\include{java}
393
394\section{THREADS}
395
396Multithreading
397
398\subsection{API}
399
400% include autogen docs for the THREADS package.
401\include{threads}
402
403\section{EXTENSIONS}
404
405The symbols in the EXTENSIONS package (nicknamed ``EXT'') constitutes
406extensions to the ANSI standard that are potentially useful to the
407user.  They include functions for manipulating network sockets,
408running external programs, registering object finalizers, constructing
409reference weakly held by the garbage collector and others.
410
411See \ref{Extensible Sequences} for a generic function interface to
412the native JVM contract for \code{java.util.List}.
413
414\subsection{API}
415
416% include autogen docs for the EXTENSIONS package.
417\include{extensions}
418
419\chapter{Beyond ANSI}
420
421Naturally, in striving to be a useful contemporary Common Lisp
422implementation, ABCL endeavors to include extensions beyond the ANSI
423specification which are either widely adopted or are especially useful
424in working with the hosting JVM.
425
426\section{Implementation Dependent}
427\begin{enumerate}
428  \item Compiler to JVM 5 bytecode
429  \item Pathname extensions
430\end{enumerate}
431
432\section{Pathname}
433
434We implment an extension to the Pathname that allows for the
435description and retrieval of resources named in a URI scheme that the
436JVM ``understands''.  Support is built-in to the ``http'' and
437``https'' implementations but additional protocol handlers may be
438installed at runtime by having JVM symbols present in the
439sun.net.protocol.dynmamic pacakge. See [JAVA2006] for more details.
440
441ABCL has created specializations of the ANSI Pathname object to
442enable to use of URIs to address dynamically loaded resources for the
443JVM.  A URL-PATHNAME has a corresponding URL whose cannoical
444representation is defined to be the NAMESTRING of the Pathname.
445
446PATHNAME : URL-PATHNAME : JAR-PATHNAME
447
448Both URL-PATHNAME and JAR-PATHNAME may be used anu where will a
449PATHNAME is accepted witht the following caveats
450
451A stream obtained via OPEN on a URL-PATHNAME cannot be the target of
452write operations.
453
454No canonicalization is performed on the underlying URI (i.e. the
455implementation does not attempt to compute the current name of the
456representing resource unless it is requested to be resolved.)  Upon
457resolution, any cannoicalization procedures followed in resolving the
458resource (e.g. following redirects) are discarded. 
459
460The implementation of URL-PATHNAME allows the ABCL user to laod dynamically
461code from the network.  For example, for Quicklisp.
462
463\begin{listing-lisp}
464  CL-USER> (load "http://beta.quicklisp.org/quicklisp.lisp")
465\end{listing-lisp}
466
467will load and execute the Quicklisp setup code.
468
469\ref{XACH2011}
470         
471\section{Extensible Sequences}
472
473\ref{RHODES2007}
474
475The SEQUENCE package fully implements Christopher Rhodes' proposal for
476extensible sequences.  These user extensible sequences are used
477directly in \code{java-collections.lisp} provide these CLOS
478abstractions on the standard Java collection classes as defined by the
479\code{java.util.List} contract.
480
481This extension is not automatically loaded by the implementation.   It
482may be loaded via:
483
484\begin{listing-lisp}
485CL-USER> (require 'extensible-sequences)
486\end{listing-lisp}
487
488\section{Extensions to CLOS}
489
490There is an additional syntax for specializing the parameter of a
491generic function on a java class, viz. \code{(java:jclass CLASS-STRING)}
492where \code{CLASS-STRING} is a string naming a Java class in dotted package
493form.
494
495For instance the following specialization would perhaps allow one to
496print more information about the contents of a java.util.Collection
497object
498
499\begin{listing-lisp}
500(defmethod print-object ((coll (java:jclass "java.util.Collection"))
501                         stream)
502  ;;; ...
503)
504\end{listing-lisp}
505
506If the class had been loaded via a classloader other than the original
507the class you wish to specialize on, one needs to specify the
508classloader as an optional third argument.
509
510\begin{listing-lisp}
511
512(defparameter *other-classloader*
513  (jcall "getBaseLoader" cl-user::*classpath-manager*))
514 
515(defmethod print-object ((device-id (java:jclass "dto.nbi.service.hdm.alcatel.com.NBIDeviceID" *other-classloader*))
516                         stream)
517  ;;; ...
518)
519\end{listing-lisp}
520
521\section{Extensions to the Reader}
522
523We implement a special hexadecimal escape sequence for specifying
524characters to the Lisp reader, namely we allow a sequences of the form
525\# \textbackslash Uxxxx to be processed by the reader as character whose code is
526specified by the hexadecimal digits ``xxxx''.  The hexadecimal sequence
527must be exactly four digits long, padded by leading zeros for values
528less than 0x1000.
529
530Note that this sequence is never output by the implementation.  Instead,
531the corresponding Unicode character is output for characters whose
532code is greater than 0x00ff.
533
534\section{ASDF}
535
536asdf-2.017 is packaged as core component of ABCL.  By default, ASDF is
537not loaded, as it relies on the CLOS subsystem which can take a bit of
538time to initialize.
539
540\begin{listing-lisp}
541CL-USER> (require 'asdf)
542\end{listing-lisp}
543
544\chapter{Contrib}
545
546\section{abcl-asdf} 
547
548Allow ASDF system definition which dynamically loads JVM artifacts
549such as jar archives via a Maven encapsulation.
550
551ASDF components added:  JAR-FILE, JAR-DIRECTORY, CLASS-FILE-DIRECTORY
552and MVN.
553
554\section{asdf-install}
555
556An implementation of ASDF-INSTALL.  Superceded by Quicklisp (qv.)
557
558\section{asdf-jar}
559
560ASDF-JAR provides a system for packaging ASDF systems into jar
561archives for ABCL.  Given a running ABCL image with loadable ASDF
562systems the code in this package will recursively package all the
563required source and fasls in a jar archive.
564
565\section{jss}
566
567Java Syntax sucks, so we introduce the \#" macro.
568
569
570\chapter{History}
571
572ABCL was originally the extension language for the J editor, which was
573started in 1998 by Peter Graves.  Sometime in 2003, it seems that a
574lot of code that had previously not been released publically was
575suddenly committed that enabled ABCL to be plausibly termed an ANSI
576Common Lisp implementation. 
577
578In 2006, the implementation was transferred to the current
579maintainers, who have strived to improve its usability as a
580contemporary Common Lisp implementation.
581
582In 201x, with the publication of this Manual explicitly stating the
583conformance of Armed Bear Common Lisp to ANSI, we release abcl-1.0.
584
585
586
587
588\section{References}
589
590[Java2000]:  A New Era for Java Protocol Handlers.
591\url{http://java.sun.com/developer/onlineTraining/protocolhandlers/}
592
593[Xach2011]:  Quicklisp:  A system for quickly constructing Common Lisp
594libraries.  \url{http://www.quicklisp.org/}
595
596
597\end{document}
598
599% TODO
600%   1.  Create mechanism for swigging DocString and Lisp docs into
601%       sections.
602
Note: See TracBrowser for help on using the repository browser.