source: trunk/abcl/src/org/armedbear/lisp/java.lisp @ 13102

Last change on this file since 13102 was 13102, checked in by ehuelsmann, 11 years ago

Add more type-conversion helpers to java.lisp.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 21.0 KB
Line 
1;;; java.lisp
2;;;
3;;; Copyright (C) 2003-2007 Peter Graves, Andras Simon
4;;; $Id: java.lisp 13102 2010-12-25 11:03:50Z ehuelsmann $
5;;;
6;;; This program is free software; you can redistribute it and/or
7;;; modify it under the terms of the GNU General Public License
8;;; as published by the Free Software Foundation; either version 2
9;;; of the License, or (at your option) any later version.
10;;;
11;;; This program is distributed in the hope that it will be useful,
12;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
13;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14;;; GNU General Public License for more details.
15;;;
16;;; You should have received a copy of the GNU General Public License
17;;; along with this program; if not, write to the Free Software
18;;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
19;;;
20;;; As a special exception, the copyright holders of this library give you
21;;; permission to link this library with independent modules to produce an
22;;; executable, regardless of the license terms of these independent
23;;; modules, and to copy and distribute the resulting executable under
24;;; terms of your choice, provided that you also meet, for each linked
25;;; independent module, the terms and conditions of the license of that
26;;; module.  An independent module is a module which is not derived from
27;;; or based on this library.  If you modify this library, you may extend
28;;; this exception to your version of the library, but you are not
29;;; obligated to do so.  If you do not wish to do so, delete this
30;;; exception statement from your version.
31
32(in-package "JAVA")
33
34(require "CLOS")
35(require "PRINT-OBJECT")
36
37(defvar *classloader* (get-default-classloader))
38
39(defun add-url-to-classpath (url &optional (classloader *classloader*))
40  (jcall "addUrl" classloader url))
41
42(defun add-urls-to-classpath (&rest urls)
43  (dolist (url urls)
44    (add-url-to-classpath url)))
45
46(defun jregister-handler (object event handler &key data count)
47  (%jregister-handler object event handler data count))
48
49(defun jinterface-implementation (interface &rest method-names-and-defs)
50  "Creates and returns an implementation of a Java interface with
51   methods calling Lisp closures as given in METHOD-NAMES-AND-DEFS.
52
53   INTERFACE is either a Java interface or a string naming one.
54
55   METHOD-NAMES-AND-DEFS is an alternating list of method names
56   (strings) and method definitions (closures).
57
58   For missing methods, a dummy implementation is provided that
59   returns nothing or null depending on whether the return type is
60   void or not. This is for convenience only, and a warning is issued
61   for each undefined method."
62  (let ((interface (jclass interface))
63        (implemented-methods
64         (loop for m in method-names-and-defs
65           for i from 0
66           if (evenp i)
67           do (assert (stringp m) (m) "Method names must be strings: ~s" m) and collect m
68           else
69           do (assert (or (symbolp m) (functionp m)) (m) "Methods must be function designators: ~s" m)))
70        (null (make-immediate-object nil :ref)))
71    (loop for method across
72      (jclass-methods interface :declared nil :public t)
73      for method-name = (jmethod-name method)
74      when (not (member method-name implemented-methods :test #'string=))
75      do
76      (let* ((void-p (string= (jclass-name (jmethod-return-type method)) "void"))
77             (arglist (when (plusp (length (jmethod-params method))) '(&rest ignore)))
78             (def `(lambda
79                     ,arglist
80                     ,(when arglist '(declare (ignore ignore)))
81                     ,(if void-p '(values) null))))
82        (warn "Implementing dummy method ~a for interface ~a"
83              method-name (jclass-name interface))
84        (push (coerce def 'function) method-names-and-defs)
85        (push method-name method-names-and-defs)))
86    (apply #'%jnew-proxy interface method-names-and-defs)))
87
88(defun jmake-invocation-handler (function)
89  (%jmake-invocation-handler function))
90
91(when (autoloadp 'jmake-proxy)
92  (fmakunbound 'jmake-proxy))
93
94(defgeneric jmake-proxy (interface implementation &optional lisp-this)
95  (:documentation "Returns a proxy Java object implementing the provided interface(s) using methods implemented in Lisp - typically closures, but implementations are free to provide other mechanisms. You can pass an optional 'lisp-this' object that will be passed to the implementing methods as their first argument. If you don't provide this object, NIL will be used. The second argument of the Lisp methods is the name of the Java method being implemented. This has the implication that overloaded methods are merged, so you have to manually discriminate them if you want to. The remaining arguments are java-objects wrapping the method's parameters."))
96
97(defun canonicalize-jproxy-interfaces (ifaces)
98  (if (listp ifaces)
99      (mapcar #'jclass ifaces)
100      (list (jclass ifaces))))
101
102
103(defmethod jmake-proxy (interface invocation-handler &optional lisp-this)
104  "Basic implementation that directly uses an invocation handler."
105  (%jmake-proxy (canonicalize-jproxy-interfaces interface) invocation-handler lisp-this))
106
107(defmethod jmake-proxy (interface (implementation function) &optional lisp-this)
108  "Implements a Java interface forwarding method calls to a Lisp function."
109  (%jmake-proxy (canonicalize-jproxy-interfaces interface) (jmake-invocation-handler implementation) lisp-this))
110
111(defmethod jmake-proxy (interface (implementation package) &optional lisp-this)
112  "Implements a Java interface mapping Java method names to symbols in a given package. javaMethodName is mapped to a JAVA-METHOD-NAME symbol. An error is signaled if no such symbol exists in the package, or if the symbol exists but does not name a function."
113  (flet ((java->lisp (name)
114     (with-output-to-string (str)
115       (let ((last-lower-p nil))
116         (map nil (lambda (char)
117        (let ((upper-p (char= (char-upcase char) char)))
118          (when (and last-lower-p upper-p)
119            (princ "-" str))
120          (setf last-lower-p (not upper-p))
121          (princ (char-upcase char) str)))
122        name)))))
123    (%jmake-proxy (canonicalize-jproxy-interfaces interface)
124      (jmake-invocation-handler 
125       (lambda (obj method &rest args)
126         (let ((sym (find-symbol
127         (java->lisp method)
128         implementation)))
129           (unless sym
130       (error "Symbol ~A, implementation of method ~A, not found in ~A"
131          (java->lisp method)
132          method
133          implementation))
134       (if (fboundp sym)
135           (apply (symbol-function sym) obj method args)
136           (error "Function ~A, implementation of method ~A, not found in ~A"
137            sym method implementation)))))
138      lisp-this)))
139
140(defmethod jmake-proxy (interface (implementation hash-table) &optional lisp-this)
141  "Implements a Java interface using closures in an hash-table keyed by Java method name."
142  (%jmake-proxy (canonicalize-jproxy-interfaces interface)
143    (jmake-invocation-handler 
144     (lambda (obj method &rest args)
145       (let ((fn (gethash method implementation)))
146         (if fn
147       (apply fn obj args)
148       (error "Implementation for method ~A not found in ~A"
149        method implementation)))))
150    lisp-this))
151
152(defun jequal (obj1 obj2)
153  "Compares obj1 with obj2 using java.lang.Object.equals()"
154  (jcall (jmethod "java.lang.Object" "equals" "java.lang.Object")
155   obj1 obj2))
156
157(defun jobject-class (obj)
158  "Returns the Java class that OBJ belongs to"
159  (jcall (jmethod "java.lang.Object" "getClass") obj))
160
161(defun jclass-superclass (class)
162  "Returns the superclass of CLASS, or NIL if it hasn't got one"
163  (jcall (jmethod "java.lang.Class" "getSuperclass") (jclass class)))
164
165(defun jclass-interfaces (class)
166  "Returns the vector of interfaces of CLASS"
167  (jcall (jmethod "java.lang.Class" "getInterfaces") (jclass class)))
168
169(defun jclass-interface-p (class)
170  "Returns T if CLASS is an interface"
171  (jcall (jmethod "java.lang.Class" "isInterface") (jclass class)))
172
173(defun jclass-superclass-p (class-1 class-2)
174  "Returns T if CLASS-1 is a superclass or interface of CLASS-2"
175  (jcall (jmethod "java.lang.Class" "isAssignableFrom" "java.lang.Class")
176         (jclass class-1)
177         (jclass class-2)))
178
179(defun jclass-array-p (class)
180  "Returns T if CLASS is an array class"
181  (jcall (jmethod "java.lang.Class" "isArray") (jclass class)))
182
183(defun jarray-component-type (atype)
184  "Returns the component type of the array type ATYPE"
185  (assert (jclass-array-p atype))
186  (jcall (jmethod "java.lang.Class" "getComponentType") atype))
187
188(defun jarray-length (java-array)
189  (jstatic "getLength" "java.lang.reflect.Array" java-array)  )
190
191(defun (setf jarray-ref) (new-value java-array &rest indices)
192  (apply #'jarray-set java-array new-value indices))
193
194(defun jnew-array-from-array (element-type array)
195  "Returns a new Java array with base type ELEMENT-TYPE (a string or a class-ref)
196   initialized from ARRAY"
197  (flet
198    ((row-major-to-index (dimensions n)
199                         (loop for dims on dimensions
200                           with indices
201                           do
202                           (multiple-value-bind (m r) (floor n (apply #'* (cdr dims)))
203                             (push m indices)
204                             (setq n r))
205                           finally (return (nreverse indices)))))
206    (let* ((fill-pointer (when (array-has-fill-pointer-p array) (fill-pointer array)))
207           (dimensions (if fill-pointer (list fill-pointer) (array-dimensions array)))
208           (jarray (apply #'jnew-array element-type dimensions)))
209      (dotimes (i (if fill-pointer fill-pointer (array-total-size array)) jarray)
210        #+maybe_one_day
211        (setf (apply #'jarray-ref jarray (row-major-to-index dimensions i)) (row-major-aref array i))
212        (apply #'(setf jarray-ref) (row-major-aref array i) jarray (row-major-to-index dimensions i))))))
213
214(defun jnew-array-from-list (element-type list)
215  (let ((jarray (jnew-array element-type (length list)))
216  (i 0))
217    (dolist (x list)
218      (setf (jarray-ref jarray i) x
219      i (1+ i)))
220    jarray))
221
222(defun list-from-jarray (jarray)
223  "Returns a list with the elements of `jarray`."
224  (loop for i from 0 below (jarray-length jarray)
225        collect (jarray-ref jarray i)))
226
227(defun vector-from-jarray (jarray)
228  "Returns a vector with the elements of `jarray`."
229  (loop with vec = (make-array (jarray-length jarray))
230        for i from 0 below (jarray-length jarray)
231        do (setf (aref vec i) (jarray-ref jarray i))
232        finally (return vec)))
233
234(defun list-from-jenumeration (jenumeration)
235  "Returns a list with the elements returned by successive `nextElement`
236calls on the java.util.Enumeration `jenumeration`."
237  (loop while (jcall jenumeration
238                     (jmethod "java.util.Enumeration" "hasMoreElements"))
239        collect (jcall jenumeration
240                       (jmethod "java.util.Enumeration" "nextElement"))))
241
242(defun jclass-constructors (class)
243  "Returns a vector of constructors for CLASS"
244  (jcall (jmethod "java.lang.Class" "getConstructors") (jclass class)))
245
246(defun jconstructor-params (constructor)
247  "Returns a vector of parameter types (Java classes) for CONSTRUCTOR"
248  (jcall (jmethod "java.lang.reflect.Constructor" "getParameterTypes") constructor))
249
250(defun jclass-fields (class &key declared public)
251  "Returns a vector of all (or just the declared/public, if DECLARED/PUBLIC is true) fields of CLASS"
252  (let* ((getter (if declared "getDeclaredFields" "getFields"))
253         (fields (jcall (jmethod "java.lang.Class" getter) (jclass class))))
254    (if public (delete-if-not #'jmember-public-p fields) fields)))
255
256(defun jclass-field (class field-name)
257  "Returns the field named FIELD-NAME of CLASS"
258  (jcall (jmethod "java.lang.Class" "getField" "java.lang.String")
259         (jclass class) field-name))
260
261(defun jfield-type (field)
262  "Returns the type (Java class) of FIELD"
263  (jcall (jmethod "java.lang.reflect.Field" "getType") field))
264
265(defun jfield-name (field)
266  "Returns the name of FIELD as a Lisp string"
267  (jcall (jmethod "java.lang.reflect.Field" "getName") field))
268
269
270(defun (setf jfield) (newvalue class-ref-or-field field-or-instance
271          &optional (instance nil instance-supplied-p) unused-value)
272  (declare (ignore unused-value))
273  (if instance-supplied-p
274      (jfield class-ref-or-field field-or-instance instance newvalue)
275      (jfield class-ref-or-field field-or-instance newvalue)))
276
277(defun jclass-methods (class &key declared public)
278  "Return a vector of all (or just the declared/public, if DECLARED/PUBLIC is true) methods of CLASS"
279  (let* ((getter (if declared "getDeclaredMethods" "getMethods"))
280         (methods (jcall (jmethod "java.lang.Class" getter) (jclass class))))
281    (if public (delete-if-not #'jmember-public-p methods) methods)))
282
283(defun jmethod-params (method)
284  "Returns a vector of parameter types (Java classes) for METHOD"
285  (jcall (jmethod "java.lang.reflect.Method" "getParameterTypes") method))
286
287(defun jmethod-return-type (method)
288  "Returns the result type (Java class) of the METHOD"
289  (jcall (jmethod "java.lang.reflect.Method" "getReturnType") method))
290
291(defun jmethod-declaring-class (method)
292  "Returns the Java class declaring METHOD"
293  (jcall (jmethod "java.lang.reflect.Method" "getDeclaringClass") method))
294
295(defun jmethod-name (method)
296  "Returns the name of METHOD as a Lisp string"
297  (jcall (jmethod "java.lang.reflect.Method" "getName") method))
298
299(defun jinstance-of-p (obj class)
300  "OBJ is an instance of CLASS (or one of its subclasses)"
301  (and (java-object-p obj)
302       (jcall (jmethod "java.lang.Class" "isInstance" "java.lang.Object") (jclass class) obj)))
303
304(defun jmember-static-p (member)
305  "MEMBER is a static member of its declaring class"
306  (jstatic (jmethod "java.lang.reflect.Modifier" "isStatic" "int")
307           "java.lang.reflect.Modifier"
308           (jcall (jmethod "java.lang.reflect.Member" "getModifiers") member)))
309
310(defun jmember-public-p (member)
311  "MEMBER is a public member of its declaring class"
312  (jstatic (jmethod "java.lang.reflect.Modifier" "isPublic" "int")
313           "java.lang.reflect.Modifier"
314           (jcall (jmethod "java.lang.reflect.Member" "getModifiers") member)))
315
316(defun jmember-protected-p (member)
317  "MEMBER is a protected member of its declaring class"
318  (jstatic (jmethod "java.lang.reflect.Modifier" "isProtected" "int")
319           "java.lang.reflect.Modifier"
320           (jcall (jmethod "java.lang.reflect.Member" "getModifiers") member)))
321
322(defmethod make-load-form ((object java-object) &optional environment)
323  (declare (ignore environment))
324  (let ((class-name (jclass-name (jclass-of object))))
325    (cond
326     ((string= class-name "java.lang.reflect.Constructor")
327      `(java:jconstructor ,(jclass-name
328                            (jcall (jmethod "java.lang.reflect.Constructor"
329                                            "getDeclaringClass") object))
330                          ,@(loop for arg-type across
331                              (jcall
332                               (jmethod "java.lang.reflect.Constructor"
333                                        "getParameterTypes")
334                               object)
335                              collecting
336                              (jclass-name arg-type))))
337     ((string= class-name "java.lang.reflect.Method")
338      `(java:jmethod ,(jclass-name
339                       (jcall (jmethod "java.lang.reflect.Method"
340                                       "getDeclaringClass") object))
341                     ,(jmethod-name object)
342                     ,@(loop for arg-type across
343                         (jcall
344                          (jmethod "java.lang.reflect.Method"
345                                   "getParameterTypes")
346                          object)
347                         collecting
348                         (jclass-name arg-type))))
349     ((jinstance-of-p object "java.lang.Class")
350      `(java:jclass ,(jcall (jmethod "java.lang.Class" "getName") object)))
351     (t
352      (error "Unknown load-form for ~A" class-name)))))
353
354(defun jproperty-value (obj prop)
355  (%jget-property-value obj prop))
356
357(defun (setf jproperty-value) (value obj prop)
358  (%jset-property-value obj prop value))
359
360;;; higher-level operators
361
362(defmacro chain (target op &rest ops)
363  "Performs chained method invocations. `target' is the receiver object (when the first call is a virtual method call) or a list in the form (:static <jclass>) when the first method call is a static method call. `op' and each of the `ops' are either method designators or lists in the form (<method designator> &rest args), where a method designator is either a string naming a method, or a jmethod object. `chain' will perform the method call specified by `op' on `target'; then, for each of the `ops', `chain' will perform the specified method call using the object returned by the previous method call as the receiver, and will ultimately return the result of the last method call.
364  For example, the form:
365
366  (chain (:static \"java.lang.Runtime\") \"getRuntime\" (\"exec\" \"ls\"))
367
368  is equivalent to the following Java code:
369
370  java.lang.Runtime.getRuntime().exec(\"ls\");"
371  (labels ((canonicalize-op (op) (if (listp op) op (list op)))
372     (compose-arglist (target op) `(,(car op) ,target ,@(cdr op)))
373     (make-binding-for (form) `(,(gensym) ,form))
374     (make-binding (bindings next-op &aux (target (caar bindings)))
375       (cons (make-binding-for
376        `(jcall ,@(compose-arglist target
377                 (canonicalize-op next-op))))
378       bindings)))
379    (let* ((first (if (and (consp target) (eq (first target) :static))
380          `(jstatic ,@(compose-arglist (cadr target) (canonicalize-op op)))
381          `(jcall ,@(compose-arglist target (canonicalize-op op)))))
382     (bindings (nreverse
383          (reduce #'make-binding ops
384            :initial-value (list (make-binding-for first))))))
385      `(let* ,bindings
386   (declare (ignore ,@(mapcar #'car bindings)))))))
387
388(defmacro jmethod-let (bindings &body body)
389  (let ((args (gensym)))
390    `(let ,(mapcar (lambda (binding)
391         `(,(car binding) (jmethod ,@(cdr binding))))
392       bindings)
393       (macrolet ,(mapcar (lambda (binding)
394          `(,(car binding) (&rest ,args)
395             `(jcall ,,(car binding) ,@,args)))
396        bindings)
397   ,@body))))
398
399;;; print-object
400
401(defmethod print-object ((obj java:java-object) stream)
402  (write-string (sys::%write-to-string obj) stream))
403
404(defmethod print-object ((e java:java-exception) stream)
405  (if *print-escape*
406      (print-unreadable-object (e stream :type t :identity t)
407        (format stream "~A"
408                (java:jcall (java:jmethod "java.lang.Object" "toString")
409                            (java:java-exception-cause e))))
410      (format stream "Java exception '~A'."
411              (java:jcall (java:jmethod "java.lang.Object" "toString")
412                          (java:java-exception-cause e)))))
413
414;;; JAVA-CLASS support
415(defconstant +java-lang-object+ (jclass "java.lang.Object"))
416
417(defclass java-class (standard-class)
418  ((jclass :initarg :java-class
419     :initform (error "class is required")
420     :reader java-class-jclass)))
421
422;;init java.lang.Object class
423(defconstant +java-lang-object-class+
424  (%register-java-class +java-lang-object+
425      (mop::ensure-class (make-symbol "java.lang.Object")
426             :metaclass (find-class 'java-class)
427             :direct-superclasses (list (find-class 'java-object))
428             :java-class +java-lang-object+)))
429
430(defun jclass-additional-superclasses (jclass)
431  "Extension point to put additional CLOS classes on the CPL of a CLOS Java class."
432  (let ((supers nil))
433    (when (jclass-interface-p jclass)
434      (push (find-class 'java-object) supers))
435    (when (jequal jclass (jclass "java.util.List"))
436      (push (find-class 'sequence) supers))
437    supers))
438
439(defun ensure-java-class (jclass)
440  (let ((class (%find-java-class jclass)))
441    (if class
442  class
443  (%register-java-class
444   jclass (mop::ensure-class
445     (make-symbol (jclass-name jclass))
446     :metaclass (find-class 'java-class)
447     :direct-superclasses
448     (let ((supers
449      (mapcar #'ensure-java-class
450        (delete nil
451          (concatenate 'list
452                 (list (jclass-superclass jclass))
453                 (jclass-interfaces jclass))))))
454       (append supers (jclass-additional-superclasses jclass)))
455     :java-class jclass)))))
456
457(defmethod mop::compute-class-precedence-list ((class java-class))
458  "Sort classes this way:
459   1. Java classes (but not java.lang.Object)
460   2. Java interfaces
461   3. java.lang.Object
462   4. other classes
463   Rationale:
464   1. Concrete classes are the most specific.
465   2. Then come interfaces.
466     So if a generic function is specialized both on an interface and a concrete class,
467     the concrete class comes first.
468   3. because everything is an Object.
469   4. to handle base CLOS classes.
470   Note: Java interfaces are not sorted among themselves in any way, so if a
471   gf is specialized on two different interfaces and you apply it to an object that
472   implements both, it is unspecified which method will be called."
473  (let ((cpl (nreverse (mop::collect-superclasses* class))))
474    (flet ((score (class)
475       (if (not (typep class 'java-class))
476     4
477     (cond
478       ((jcall (jmethod "java.lang.Object" "equals" "java.lang.Object")
479         (java-class-jclass class) +java-lang-object+) 3)
480       ((jclass-interface-p (java-class-jclass class)) 2)
481       (t 1)))))
482      (stable-sort cpl #'(lambda (x y)
483         (< (score x) (score y)))))))
484   
485(defmethod make-instance ((class java-class) &rest initargs &key &allow-other-keys)
486  (declare (ignore initargs))
487  (error "make-instance not supported for ~S" class))
488
489(provide "JAVA")
Note: See TracBrowser for help on using the repository browser.