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

Last change on this file since 13393 was 13393, checked in by Mark Evenson, 10 years ago

JAVA:JARRAY-FROM-LIST infers the type of the Java array.

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