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

Last change on this file since 11940 was 11940, checked in by astalla, 9 years ago

Fixed a bug in interpreted let* and do*: the environment used for bindings
was a single one, shared with all the initforms and the body. This caused
closures in initforms to capture newly-introduced bindings.
The fix amounts to creating a new extended environment for every binding.
In passing a typo was fixed in java.lisp.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 13.6 KB
Line 
1;;; java.lisp
2;;;
3;;; Copyright (C) 2003-2007 Peter Graves, Andras Simon
4;;; $Id: java.lisp 11940 2009-05-23 22:44:26Z astalla $
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
36(defun jregister-handler (object event handler &key data count)
37  (%jregister-handler object event handler data count))
38
39(defun jinterface-implementation (interface &rest method-names-and-defs)
40  "Creates and returns an implementation of a Java interface with
41   methods calling Lisp closures as given in METHOD-NAMES-AND-DEFS.
42
43   INTERFACE is either a Java interface or a string naming one.
44
45   METHOD-NAMES-AND-DEFS is an alternating list of method names
46   (strings) and method definitions (closures).
47
48   For missing methods, a dummy implementation is provided that
49   returns nothing or null depending on whether the return type is
50   void or not. This is for convenience only, and a warning is issued
51   for each undefined method."
52  (let ((interface (jclass interface))
53        (implemented-methods
54         (loop for m in method-names-and-defs
55           for i from 0
56           if (evenp i)
57           do (assert (stringp m) (m) "Method names must be strings: ~s" m) and collect m
58           else
59           do (assert (or (symbolp m) (functionp m)) (m) "Methods must be function designators: ~s" m)))
60        (null (make-immediate-object nil :ref)))
61    (loop for method across
62      (jclass-methods interface :declared nil :public t)
63      for method-name = (jmethod-name method)
64      when (not (member method-name implemented-methods :test #'string=))
65      do
66      (let* ((void-p (string= (jclass-name (jmethod-return-type method)) "void"))
67             (arglist (when (plusp (length (jmethod-params method))) '(&rest ignore)))
68             (def `(lambda
69                     ,arglist
70                     ,(when arglist '(declare (ignore ignore)))
71                     ,(if void-p '(values) null))))
72        (warn "Implementing dummy method ~a for interface ~a"
73              method-name (jclass-name interface))
74        (push (coerce def 'function) method-names-and-defs)
75        (push method-name method-names-and-defs)))
76    (apply #'%jnew-proxy interface method-names-and-defs)))
77
78(defun jmake-invocation-handler (function)
79  (%jmake-invocation-handler function))
80
81(when (autoloadp 'jmake-proxy)
82  (fmakunbound 'jmake-proxy))
83
84(defgeneric jmake-proxy (interface implementation &optional lisp-this)
85  (:documentation "Returns a proxy Java object implementing the provided interface 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."))
86
87(defmethod jmake-proxy (interface invocation-handler &optional lisp-this)
88  "Basic implementation that directly uses an invocation handler."
89  (%jmake-proxy (jclass interface) invocation-handler lisp-this))
90
91(defmethod jmake-proxy (interface (implementation function) &optional lisp-this)
92  "Implements a Java interface forwarding method calls to a Lisp function."
93  (%jmake-proxy (jclass interface) (jmake-invocation-handler implementation) lisp-this))
94
95(defmethod jmake-proxy (interface (implementation package) &optional lisp-this)
96  "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."
97  (flet ((java->lisp (name)
98     (with-output-to-string (str)
99       (let ((last-lower-p nil))
100         (map nil (lambda (char)
101        (let ((upper-p (char= (char-upcase char) char)))
102          (when (and last-lower-p upper-p)
103            (princ "-" str))
104          (setf last-lower-p (not upper-p))
105          (princ (char-upcase char) str)))
106        name)))))
107    (%jmake-proxy (jclass interface)
108      (jmake-invocation-handler 
109       (lambda (obj method &rest args)
110         (let ((sym (find-symbol
111         (java->lisp method)
112         implementation)))
113           (unless sym
114       (error "Symbol ~A, implementation of method ~A, not found in ~A"
115          (java->lisp method)
116          method
117          implementation))
118       (if (fboundp sym)
119           (apply (symbol-function sym) obj method args)
120           (error "Function ~A, implementation of method ~A, not found in ~A"
121            sym method implementation)))))
122      lisp-this)))
123
124(defmethod jmake-proxy (interface (implementation hash-table) &optional lisp-this)
125  "Implements a Java interface using closures in an hash-table keyed by Java method name."
126  (%jmake-proxy (jclass interface)
127    (jmake-invocation-handler 
128     (lambda (obj method &rest args)
129       (let ((fn (gethash method implementation)))
130         (if fn
131       (apply fn obj args)
132       (error "Implementation for method ~A not found in ~A"
133        method implementation)))))
134    lisp-this))
135
136(defun jobject-class (obj)
137  "Returns the Java class that OBJ belongs to"
138  (jcall (jmethod "java.lang.Object" "getClass") obj))
139
140(defun jclass-superclass (class)
141  "Returns the superclass of CLASS, or NIL if it hasn't got one"
142  (jcall (jmethod "java.lang.Class" "getSuperclass") (jclass class)))
143
144(defun jclass-interfaces (class)
145  "Returns the vector of interfaces of CLASS"
146  (jcall (jmethod "java.lang.Class" "getInterfaces") (jclass class)))
147
148(defun jclass-interface-p (class)
149  "Returns T if CLASS is an interface"
150  (jcall (jmethod "java.lang.Class" "isInterface") (jclass class)))
151
152(defun jclass-superclass-p (class-1 class-2)
153  "Returns T if CLASS-1 is a superclass or interface of CLASS-2"
154  (jcall (jmethod "java.lang.Class" "isAssignableFrom" "java.lang.Class")
155         (jclass class-1)
156         (jclass class-2)))
157
158(defun jclass-array-p (class)
159  "Returns T if CLASS is an array class"
160  (jcall (jmethod "java.lang.Class" "isArray") (jclass class)))
161
162(defun jarray-component-type (atype)
163  "Returns the component type of the array type ATYPE"
164  (assert (jclass-array-p atype))
165  (jcall (jmethod "java.lang.Class" "getComponentType") atype))
166
167(defun jarray-length (java-array)
168  (jstatic "getLength" "java.lang.reflect.Array" java-array)  )
169
170(defun (setf jarray-ref) (new-value java-array &rest indices)
171  (apply #'jarray-set java-array new-value indices))
172
173(defun jnew-array-from-array (element-type array)
174  "Returns a new Java array with base type ELEMENT-TYPE (a string or a class-ref)
175   initialized from ARRAY"
176  (flet
177    ((row-major-to-index (dimensions n)
178                         (loop for dims on dimensions
179                           with indices
180                           do
181                           (multiple-value-bind (m r) (floor n (apply #'* (cdr dims)))
182                             (push m indices)
183                             (setq n r))
184                           finally (return (nreverse indices)))))
185    (let* ((fill-pointer (when (array-has-fill-pointer-p array) (fill-pointer array)))
186           (dimensions (if fill-pointer (list fill-pointer) (array-dimensions array)))
187           (jarray (apply #'jnew-array element-type dimensions)))
188      (dotimes (i (if fill-pointer fill-pointer (array-total-size array)) jarray)
189        #+maybe_one_day
190        (setf (apply #'jarray-ref jarray (row-major-to-index dimensions i)) (row-major-aref array i))
191        (apply #'(setf jarray-ref) (row-major-aref array i) jarray (row-major-to-index dimensions i))))))
192
193(defun jclass-constructors (class)
194  "Returns a vector of constructors for CLASS"
195  (jcall (jmethod "java.lang.Class" "getConstructors") (jclass class)))
196
197(defun jconstructor-params (constructor)
198  "Returns a vector of parameter types (Java classes) for CONSTRUCTOR"
199  (jcall (jmethod "java.lang.reflect.Constructor" "getParameterTypes") constructor))
200
201(defun jclass-fields (class &key declared public)
202  "Returns a vector of all (or just the declared/public, if DECLARED/PUBLIC is true) fields of CLASS"
203  (let* ((getter (if declared "getDeclaredFields" "getFields"))
204         (fields (jcall (jmethod "java.lang.Class" getter) (jclass class))))
205    (if public (delete-if-not #'jmember-public-p fields) fields)))
206
207(defun jclass-field (class field-name)
208  "Returns the field named FIELD-NAME of CLASS"
209  (jcall (jmethod "java.lang.Class" "getField" "java.lang.String")
210         (jclass class) field-name))
211
212(defun jfield-type (field)
213  "Returns the type (Java class) of FIELD"
214  (jcall (jmethod "java.lang.reflect.Field" "getType") field))
215
216(defun jfield-name (field)
217  "Returns the name of FIELD as a Lisp string"
218  (jcall (jmethod "java.lang.reflect.Field" "getName") field))
219
220(defun jclass-methods (class &key declared public)
221  "Return a vector of all (or just the declared/public, if DECLARED/PUBLIC is true) methods of CLASS"
222  (let* ((getter (if declared "getDeclaredMethods" "getMethods"))
223         (methods (jcall (jmethod "java.lang.Class" getter) (jclass class))))
224    (if public (delete-if-not #'jmember-public-p methods) methods)))
225
226(defun jmethod-params (method)
227  "Returns a vector of parameter types (Java classes) for METHOD"
228  (jcall (jmethod "java.lang.reflect.Method" "getParameterTypes") method))
229
230;; (defun jmethod-return-type (method)
231;;   "Returns the result type (Java class) of the METHOD"
232;;   (jcall (jmethod "java.lang.reflect.Method" "getReturnType") method))
233
234(defun jmethod-name (method)
235  "Returns the name of METHOD as a Lisp string"
236  (jcall (jmethod "java.lang.reflect.Method" "getName") method))
237
238(defun jinstance-of-p (obj class)
239  "OBJ is an instance of CLASS (or one of its subclasses)"
240  (and (java-object-p obj)
241       (jcall (jmethod "java.lang.Class" "isInstance" "java.lang.Object") (jclass class) obj)))
242
243(defun jmember-static-p (member)
244  "MEMBER is a static member of its declaring class"
245  (jstatic (jmethod "java.lang.reflect.Modifier" "isStatic" "int")
246           "java.lang.reflect.Modifier"
247           (jcall (jmethod "java.lang.reflect.Member" "getModifiers") member)))
248
249(defun jmember-public-p (member)
250  "MEMBER is a public member of its declaring class"
251  (jstatic (jmethod "java.lang.reflect.Modifier" "isPublic" "int")
252           "java.lang.reflect.Modifier"
253           (jcall (jmethod "java.lang.reflect.Member" "getModifiers") member)))
254
255(defun jmember-protected-p (member)
256  "MEMBER is a protected member of its declaring class"
257  (jstatic (jmethod "java.lang.reflect.Modifier" "isProtected" "int")
258           "java.lang.reflect.Modifier"
259           (jcall (jmethod "java.lang.reflect.Member" "getModifiers") member)))
260
261(defmethod make-load-form ((object java-object) &optional environment)
262  (declare (ignore environment))
263  (let ((class-name (jclass-name (jclass-of object))))
264    (cond
265     ((string= class-name "java.lang.reflect.Constructor")
266      `(java:jconstructor ,(jclass-name
267                            (jcall (jmethod "java.lang.reflect.Constructor"
268                                            "getDeclaringClass") object))
269                          ,@(loop for arg-type across
270                              (jcall
271                               (jmethod "java.lang.reflect.Constructor"
272                                        "getParameterTypes")
273                               object)
274                              collecting
275                              (jclass-name arg-type))))
276     ((string= class-name "java.lang.reflect.Method")
277      `(java:jmethod ,(jclass-name
278                       (jcall (jmethod "java.lang.reflect.Method"
279                                       "getDeclaringClass") object))
280                     ,(jmethod-name object)
281                     ,@(loop for arg-type across
282                         (jcall
283                          (jmethod "java.lang.reflect.Method"
284                                   "getParameterTypes")
285                          object)
286                         collecting
287                         (jclass-name arg-type))))
288     ((jinstance-of-p object "java.lang.Class")
289      `(java:jclass ,(jcall (jmethod "java.lang.Class" "getName") object)))
290     (t
291      (error "Unknown load-form for ~A" class-name)))))
292
293(defun jproperty-value (obj prop)
294  (%jget-property-value obj prop))
295
296(defun (setf jproperty-value) (value obj prop)
297  (%jset-property-value obj prop value))
298
299(provide "JAVA-EXTENSIONS")
Note: See TracBrowser for help on using the repository browser.