close Warning: Failed to sync with repository "(default)": database is locked; repository information may be out of date. Look in the Trac log for more information including mitigation strategies.

source: trunk/abcl/contrib/jss/invoke.lisp @ 14911

Last change on this file since 14911 was 14911, checked in by Mark Evenson, 7 years ago

precompiler: possibly beta reduce form with function position lambda (Alan Ruttenberg)

Case 1: If the lambda has a single form in it, let someone define a
transform using:

define-function-position-lambda-transform (body-function-name (arglist form args) &body body)

body-function-name is the car of the single form in the lambda
arglist is the arglist of the lambda
form is the single form within the lambda
args are the arguments to which the lambda will be defined.

The function should check whether it can do a transform, and do it if
so, otherwise return nil signalling it couldn't

Case 2: If case 1 is not successful then if the arglist is a simple
one (no &key, &rest, &optional) then do a standard beta-reduction
binding the args to arglist using let (

If not, return and do the usual thing.

An example is in contrib/jss/optimize-java-call.lisp

To see benefits, (compile-file contrib/jss/test-optimize-java-call.lisp)
and then load the compiled file. You should see something like the below
which reports the timings for the optimized and unoptimized version of
10000 calls of (#"compile" 'regex.pattern ".*")


With optimization: (INVOKE-RESTARGS-MACRO "compile" (QUOTE REGEX.PATTERN) (LIST ".*") NIL T)
Without optimization: ((LAMBDA (#:G85648 &REST #:G85649) (INVOKE-RESTARGS "compile" #:G85648 #:G85649 NIL)) (QUOTE REGEX.PATTERN) ".*")

0.0 seconds real time
0 cons cells

0.011 seconds real time
0 cons cells

0.325 seconds real time
800156 cons cells

<> rdfs:seeAlso <>
<> rdfs:seeAlso <> .
<> :fixes <> .
<> :closes <> .
<> :closes <> .

File size: 30.2 KB
1;; Copyright (C) 2005 Alan Ruttenberg
2;; Copyright (C) 2011-2 Mark Evenson
4;; Since most of this code is derivative of the Jscheme System, it is
5;; licensed under the same terms, namely:
7;; This software is provided 'as-is', without any express or
8;; implied warranty.
10;; In no event will the author be held liable for any damages
11;; arising from the use of this software.
13;; Permission is granted to anyone to use this software for any
14;; purpose, including commercial applications, and to alter it
15;; and redistribute it freely, subject to the following
16;; restrictions:
18;; 1. The origin of this software must not be misrepresented; you
19;;    must not claim that you wrote the original software. If you
20;;    use this software in a product, an acknowledgment in the
21;;    product documentation would be appreciated but is not
22;;    required.
24;; 2. Altered source versions must be plainly marked as such, and
25;;    must not be misrepresented as being the original software.
27;; 3. This notice may not be removed or altered from any source
28;;    distribution.
31;; The dynamic dispatch of the java.lang.reflect package is used to
32;; make it real easy, if perhaps less efficient, to write Java code
33;; since you don't need to be bothered with imports, or with figuring
34;; out which method to call.  The only time that you need to know a
35;; class name is when you want to call a static method, or a
36;; constructor, and in those cases, you only need to know enough of
37;; the class name that is unique wrt to the classes on your classpath.
39;; Java methods look like this: #"toString". Java classes are
40;; represented as symbols, which are resolved to the appropriate java
41;; class name. When ambiguous, you need to be more specific. A simple example:
43;; (let ((sw (new 'StringWriter)))
44;;   (#"write" sw "Hello ")
45;;   (#"write" sw "World")
46;;   (print (#"toString" sw)))
48;; What's happened here? First, all the classes in all the jars in the
49;; classpath have been collected.  For each class a.b.C.d, we have
50;; recorded that b.c.d, b.C.d, C.d, c.d, and d potentially refer to
51;; this class. In your call to new, as long as the symbol can refer to
52;; only one class, we use that class. In this case, it is
53;; You could also have written (new
54;; 'io.stringwriter), (new '|io.StringWriter|), (new
55;; '
57;; the call (#"write" sw "Hello "), uses the code in to
58;; call the method named "write" with the arguments sw and "Hello ".
59;; JSS figures out the right java method to call, and calls it.
61;; If you want to do a raw java call, use #0"toString". Raw calls
62;; return their results as Java objects, avoiding doing the usual Java
63;; object to Lisp object conversions that ABCL does.
65;; (with-constant-signature ((name jname raw?)*) &body body)
66;; binds a macro which expands to a jcall, promising that the same method
67;; will be called every time. Use this if you are making a lot of calls and
68;; want to avoid the overhead of a the dynamic dispatch.
69;; e.g. (with-constant-signature ((tostring "toString"))
70;;        (time (dotimes (i 10000) (tostring "foo"))))
71;; runs about 3x faster than (time (dotimes (i 10000) (#"toString" "foo")))
73;; (with-constant-signature ((tostring "toString" t)) ...) will cause the
74;; toString to be a raw java call. see get-all-jar-classnames below for an example.
76;; Implementation is that the first time the function is called, the
77;; method is looked up based on the arguments passed, and thereafter
78;; that method is called directly.  Doesn't work for static methods at
79;; the moment (lazy)
81;; (japropos string) finds all class names matching string
82;; (jcmn class-name) lists the names of all methods for the class
84;; TODO
85;;   - Make with-constant-signature work for static methods too.
86;;   - #2"toString" to work like function scoped (with-constant-signature ((tostring "toString")) ...)
87;;   - #3"toString" to work like runtime scoped (with-constant-signature ((tostring "toString")) ...)
88;;      (both probably need compiler support to work)
89;;   - Maybe get rid of second " in reader macro. #"toString looks nicer, but might
90;;     confuse lisp mode.
91;;   - write jmap, analogous to map, but can take java collections, java arrays etc.
92;;   - write loop clauses for java collections.
93;;   - Register classes in .class files below classpath directories (when :wild-inferiors works)
94;;   - Make documentation like Edi Weitz
96;; Thanks: Peter Graves, Jscheme developers, Mike Travers for skij, 
97;; Andras Simon for jfli-abcl which bootstrapped me and taught me how to do
98;; get-all-jar-classnames
101;; changelog
103;; Sat January 28, 2006, alanr:
105;; Change imports strategy. Only index by last part of class name,
106;; case insensitive. Make the lookup-class-name logic be a bit more
107;; complicated. This substantially reduces the time it takes to do the
108;; auto imports and since class name lookup is relatively infrequent,
109;; and in any case cached, this doesn't effect run time speed.  (did
110;; try caching, but didn't pay - more time was spent reading and
111;; populating large hash table)
113;; Split class path by ";" in addition to ":" for windows.
115;; Tested on windows, linux.
117;; 2011-05-21 Mark Evenson
118;;   "ported" to native ABCL without needing the jscheme.jar or bsh-2.0b4.jar
120(in-package :jss)
122(eval-when (:compile-toplevel :load-toplevel :execute)
123  (defvar *do-auto-imports* t 
124    "Whether to automatically introspect all Java classes on the classpath when JSS is loaded."))
126(defvar *muffle-warnings* t) 
128(defvar *muffle-warnings* t) 
130(defvar *imports-resolved-classes* (make-hash-table :test 'equalp))
132(defun find-java-class (name)
133  "Returns the java.lang.Class representation of NAME.
135NAME can either string or a symbol according to the usual JSS conventions."
136  (jclass (maybe-resolve-class-against-imports name)))
138(defmacro invoke-add-imports (&rest imports)
139  "Push these imports onto the search path. If multiple, earlier in list take precedence"
140  `(eval-when (:compile-toplevel :load-toplevel :execute)
141     (clrhash *imports-resolved-classes*)
142     (dolist (i (reverse ',imports))
143       (setq *imports-resolved-classes* (delete i *imports-resolved-classes* :test 'equal))
144       )))
146(defun clear-invoke-imports ()
147  (clrhash *imports-resolved-classes*))
149(defun maybe-resolve-class-against-imports (classname)
150  (or (gethash (string classname) *imports-resolved-classes*)
151      (let ((found (lookup-class-name classname)))
152        (if found
153            (progn 
154              (setf (gethash classname *imports-resolved-classes*) found)
155              found)
156            (string classname)))))
158(defvar *class-name-to-full-case-insensitive* (make-hash-table :test 'equalp))
160;; This is the function that calls invoke to call your java
161;; method. The first argument is the method name or 'new. The second
162;; is the object you are calling it on, followed by the rest of the
163;; arguments. If the "object" is a symbol, then that symbol is assumed
164;; to be a java class, and a static method on the class is called,
165;; otherwise a regular method is called.
167(defun invoke (method object &rest args)
168  (invoke-restargs method object args))
170(defun invoke-restargs (method object args &optional (raw? nil))
171  (let* ((object-as-class-name 
172          (if (symbolp object) (maybe-resolve-class-against-imports object)))
173         (object-as-class 
174          (if object-as-class-name (find-java-class object-as-class-name))))
175    (if (eq method 'new)
176        (apply #'jnew (or object-as-class-name object) args)
177        (if raw?
178            (if (symbolp object)
179                (apply #'jstatic-raw method object-as-class  args)
180                (apply #'jcall-raw method object  args))
181            (if (symbolp object)
182                (apply #'jstatic method object-as-class args)
183                (apply #'jcall method object args))))))
185(defconstant +set-accessible+ 
186  (jmethod "java.lang.reflect.AccessibleObject" "setAccessible" "boolean"))
188(defun invoke-find-method (method object args)
189  (let ((result 
190         (if (symbolp object)
191                ;;; static method
192             (apply #'jmethod (lookup-class-name object) 
193                    method (mapcar #'jobject-class args))
194                  ;;; instance method
195             (apply #'jresolve-method 
196                    method object args))))
197    (jcall +set-accessible+ result +true+)
198    result))
200;; This is the reader macro for java methods. it translates the method
201;; into a lambda form that calls invoke. Which is nice because you
202;; can, e.g. do this: (mapcar #"toString" list-of-java-objects). The reader
203;; macro takes one arg. If 0, then jstatic-raw is called, so that abcl doesn't
204;; automagically convert the returned java object into a lisp object. So
205;; #0"toString" returns a java.lang.String object, where as #"toString" returns
206;; a regular Lisp string as ABCL converts the Java string to a Lisp string.
208(eval-when (:compile-toplevel :load-toplevel :execute)
209  (defun read-invoke (stream char arg) 
210    (unread-char char stream)
211    (let ((name (read stream)))
212      (let ((object-var (gensym))
213            (args-var (gensym)))
214        `(lambda (,object-var &rest ,args-var) 
215           (invoke-restargs ,name  ,object-var ,args-var ,(eql arg 0))))))
216  (set-dispatch-macro-character #\# #\" 'read-invoke))
218(defmacro with-constant-signature (fname-jname-pairs &body body)
219  "Expand all references to FNAME-JNAME-PAIRS in BODY into static function calls promising that the same function bound in the FNAME-JNAME-PAIRS will be invoked with the same argument signature.
221FNAME-JNAME-PAIRS is a list of (symbol function &optional raw)
222elements where symbol will be the symbol bound to the method named by
223the string function.  If the optional parameter raw is non-nil, the
224result will be the raw JVM object, uncoerced by the usual conventions.
226Use this macro if you are making a lot of calls and
227want to avoid the overhead of the dynamic dispatch."
229  (if (null fname-jname-pairs)
230      `(progn ,@body)
231      (destructuring-bind ((fname jname &optional raw) &rest ignore) fname-jname-pairs
232        (declare (ignore ignore))
233        (let ((varname (gensym)))
234          `(let ((,varname nil))
235             (macrolet ((,fname (&rest args)
236                          `(if ,',varname
237                               (if ,',raw
238                                   (jcall-raw ,',varname ,@args)
239                                   (jcall ,',varname ,@args))
240                               (progn
241                                 (setq ,',varname (invoke-find-method ,',jname ,(car args) (list ,@(rest args))))
242                                 (if ,',raw
243                                     (jcall-raw ,',varname ,@args)
244                                     (jcall ,',varname ,@args))))))
245               (with-constant-signature ,(cdr fname-jname-pairs)
246                 ,@body)))))))
248(defun lookup-class-name (name &key (muffle *muffle-warnings*))
249  (setq name (string name))
250  (let* (;; cant (last-name-pattern (#"compile" '|java.util.regex.Pattern| ".*?([^.]*)$"))
251         ;; reason: bootstrap - the class name would have to be looked up...
252         (last-name-pattern (load-time-value (jstatic (jmethod "java.util.regex.Pattern" "compile"
253                                                               (jclass "java.lang.String"))
254                                                      (jclass "java.util.regex.Pattern") 
255                                                      ".*?([^.]*)$")))
256         (last-name 
257          (let ((matcher (#0"matcher" last-name-pattern name)))
258            (#"matches" matcher)
259            (#"group" matcher 1))))
260    (let* ((bucket (gethash last-name *class-name-to-full-case-insensitive*))
261           (bucket-length (length bucket)))
262      (or (find name bucket :test 'equalp)
263          (flet ((matches-end (end full test)
264                   (= (+ (or (search end full :from-end t :test test) -10)
265                         (length end))
266                      (length full)))
267                 (ambiguous (choices)
268                   (error "Ambiguous class name: ~a can be ~{~a~^, ~}" name choices)))
269            (if (zerop bucket-length)
270    (progn (unless muffle (warn "can't find class named ~a" name)) nil)
271                (let ((matches (loop for el in bucket when (matches-end name el 'char=) collect el)))
272                  (if (= (length matches) 1)
273                      (car matches)
274                      (if (= (length matches) 0)
275                          (let ((matches (loop for el in bucket when (matches-end name el 'char-equal) collect el)))
276                            (if (= (length matches) 1)
277                                (car matches)
278                                (if (= (length matches) 0)
279            (progn (unless muffle (warn "can't find class named ~a" name)) nil)
280                                    (ambiguous matches))))
281                          (ambiguous matches))))))))))
283(defun get-all-jar-classnames (jar-file-name)
284  (let* ((jar (jnew (jconstructor "java.util.jar.JarFile" (jclass "java.lang.String")) (namestring (truename jar-file-name))))
285         (entries (#"entries" jar)))
286    (with-constant-signature ((matcher "matcher" t) (substring "substring")
287                              (jreplace "replace" t) (jlength "length")
288                              (matches "matches") (getname "getName" t)
289                              (next "nextElement" t) (hasmore "hasMoreElements")
290                              (group "group"))
291      (loop while (hasmore entries)
292         for name =  (getname (next entries))
293         with class-pattern = (jstatic "compile" "java.util.regex.Pattern" ".*\\.class$")
294         with name-pattern = (jstatic "compile" "java.util.regex.Pattern" ".*?([^.]*)$")
295         when (matches (matcher class-pattern name))
296         collect
297           (let* ((fullname (substring (jreplace name #\/ #\.) 0 (- (jlength name) 6)))
298                  (matcher (matcher name-pattern fullname))
299                  (name (progn (matches matcher) (group matcher 1))))
300             (cons name fullname))
301           ))))
303(defun jar-import (file)
304  "Import all the Java classes contained in the pathname FILE into the JSS dynamic lookup cache."
305  (when (probe-file file)
306    (loop for (name . full-class-name) in (get-all-jar-classnames file)
307       do 
308         (pushnew full-class-name (gethash name *class-name-to-full-case-insensitive*) 
309                  :test 'equal))))
311(defun new (class-name &rest args)
312  "Invoke the Java constructor for CLASS-NAME with ARGS.
314CLASS-NAME may either be a symbol or a string according to the usual JSS conventions."
315  (invoke-restargs 'new class-name args))
317(defvar *running-in-osgi* (ignore-errors (jclass "org.osgi.framework.BundleActivator")))
319(define-condition no-such-java-field (error)
320  ((field-name
321    :initarg :field-name
322    :reader field-name
323    )
324   (object
325    :initarg :object
326    :reader object
327    ))
328  (:report (lambda (c stream)
329             (format stream "Unable to find a FIELD named ~a for ~a"
330                     (field-name c) (object c))))
331  )
333(defun get-java-field (object field &optional (try-harder *running-in-osgi*))
334  "Get the value of the FIELD contained in OBJECT.
335If OBJECT is a symbol it names a dot qualified static FIELD."
336  (if try-harder
337      (let* ((class (if (symbolp object)
338                        (setq object (find-java-class object))
339                        (if (equal "java.lang.Class" (jclass-name (jobject-class object)))
340                            object
341                            (jobject-class object))))
342             (jfield (if (java-object-p field)
343                         field
344                         (or (find-declared-field field class)
345                             (error 'no-such-java-field :field-name field :object object)))))
346        (#"setAccessible" jfield +true+)
347        (values (#"get" jfield object) jfield))
348      (if (symbolp object)
349          (let ((class (find-java-class object)))
350            (jfield class field))
351          (jfield field object))))
353(defun find-declared-field (field class)
354  "Return a FIELD object corresponding to the definition of FIELD
355\(a string\) visible at CLASS. *Not* restricted to public classes, and checks
356all superclasses of CLASS.
357   Returns NIL if no field object is found."
358  (loop while class
359     for field-obj = (get-declared-field class field)
360     if field-obj
361     do (return-from find-declared-field field-obj)
362     else
363     do (setf class (jclass-superclass class)))
364  nil)
366(defun get-declared-field (class fieldname)
367  (find fieldname (#"getDeclaredFields" class)
368        :key 'jfield-name :test 'equal))
370;; TODO use #"getSuperclass" and #"getInterfaces" to see whether there
371;; are fields in superclasses that we might set
372(defun set-java-field (object field value &optional (try-harder *running-in-osgi*))
373  "Set the FIELD of OBJECT to VALUE.
374If OBJECT is a symbol, it names a dot qualified Java class to look for
375a static FIELD.  If OBJECT is an instance of java:java-object, the
376associated is used to look up the static FIELD."
377  (if try-harder
378      (let* ((class (if (symbolp object)
379                        (setq object (find-java-class object))
380                        (if (equal "java.lang.Class" (jclass-name (jobject-class object)) )
381                            object
382                            (jobject-class object))))
383             (jfield (if (java-object-p field)
384                         field
385                         (or (find-declared-field field class)
386                             (error 'no-such-java-field :field-name field :object object)))))
387        (#"setAccessible" jfield +true+)
388        (values (#"set" jfield object value) jfield))
389      (if (symbolp object)
390          (let ((class (find-java-class object)))
391            (setf (jfield (#"getName" class) field) value))
392          (if (typep object 'java-object)
393              (setf (jfield (jclass-of object) field) value)
394              (setf (jfield object field) value)))))
396(defun (setf get-java-field) (value object field &optional (try-harder *running-in-osgi*))
397  (set-java-field object field value try-harder))
400(defconstant +for-name+ 
401  (jmethod "java.lang.Class" "forName" "java.lang.String" "boolean" "java.lang.ClassLoader"))
403(defun find-java-class (name)
404  (or (jstatic +for-name+ "java.lang.Class" 
405               (maybe-resolve-class-against-imports name) +true+ java::*classloader*)
406      (ignore-errors (jclass (maybe-resolve-class-against-imports name)))))
408(defmethod print-object ((obj (jclass "java.lang.Class")) stream) 
409  (print-unreadable-object (obj stream :identity nil)
410    (format stream "java class ~a" (jclass-name obj))))
412(defmethod print-object ((obj (jclass "java.lang.reflect.Method")) stream) 
413  (print-unreadable-object (obj stream :identity nil)
414    (format stream "method ~a" (#"toString" obj))))
416(defun do-auto-imports ()
417  (labels ((expand-paths (cp)
418             (loop :for s :in cp
419                :appending (loop :for entry 
420                              :in (let ((p (pathname s)))
421                                    (if (wild-pathname-p p)
422                                        (directory p)
423                                        (list p)))
424                              :collecting entry)))
425           (import-classpath (cp)
426             (mapcar 
427              (lambda (p) 
428                (when *load-verbose*
429                  (format t ";; Importing ~A~%" p))
430                (cond 
431                  ((file-directory-p p) )
432                  ((equal (pathname-type p) "jar")
433                   (jar-import (merge-pathnames p
434                                                (format nil "~a/" (jstatic "getProperty" "java.lang.System" "user.dir")))))))
435              cp))
436           (split-classpath (cp)
437             (coerce 
438              (jcall "split" cp 
439                     (string (jfield (jclass "") "pathSeparatorChar")))
440              'cons))
441           (do-imports (cp)
442             (import-classpath (expand-paths (split-classpath cp)))))
443    (do-imports (jcall "getClassPath" (jstatic "getRuntimeMXBean" '||)))
444    (do-imports (jcall "getBootClassPath" (jstatic "getRuntimeMXBean" '||)))))
446(eval-when (:load-toplevel :execute)
447  (when *do-auto-imports* 
448    (do-auto-imports)))
450(defun japropos (string)
451  "Output the names of all Java class names loaded in the current process which match STRING.."
452  (setq string (string string))
453  (let ((matches nil))
454    (maphash (lambda(key value) 
455               (declare (ignore key))
456               (loop for class in value
457                  when (search string class :test 'string-equal)
458                  do (pushnew (list class "Java Class") matches :test 'equal)))
459             *class-name-to-full-case-insensitive*)
460    (loop for (match type) in (sort matches 'string-lessp :key 'car)
461       do (format t "~a: ~a~%" match type))
462    ))
464(defun jclass-method-names (class &optional full)
465  (if (java-object-p class)
466      (if (equal (jclass-name (jobject-class class)) "java.lang.Class")
467          (setq class (jclass-name class))
468          (setq class (jclass-name (jobject-class class)))))
469  (union
470   (remove-duplicates (map 'list (if full #"toString" 'jmethod-name) (#"getMethods" (find-java-class class))) :test 'equal)
471   (ignore-errors (remove-duplicates (map 'list (if full #"toString" 'jmethod-name) (#"getConstructors" (find-java-class class))) :test 'equal))))
473(defun java-class-method-names (class &optional stream)
474  "Return a list of the public methods encapsulated by the JVM CLASS.
476If STREAM non-nil, output a verbose description to the named output stream.
478CLASS may either be a string naming a fully qualified JVM class in dot
479notation, or a symbol resolved against all class entries in the
480current classpath."
481  (if stream
482      (dolist (method (jclass-method-names class t))
483        (format stream "~a~%" method))
484      (jclass-method-names class)))
486(setf (symbol-function 'jcmn) 'java-class-method-names)
488(defun path-to-class (classname)
489  (let ((full (lookup-class-name classname)))
490    (#"toString" 
491     (#"getResource" 
492      (find-java-class full)
493      (concatenate 'string "/" (substitute #\/ #\. full) ".class")))))
497(defun all-loaded-classes ()
498  (let ((classes-field 
499         (find "classes" (#"getDeclaredFields" (jclass "java.lang.ClassLoader"))
500               :key #"getName" :test 'equal)))
501    (#"setAccessible" classes-field +true+)
502    (loop for classloader in (mapcar #'first (dump-classpath))
503       append
504         (loop with classesv = (#"get" classes-field classloader)
505            for i below (#"size" classesv)
506            collect (#"getName" (#"elementAt" classesv i)))
507       append
508         (loop with classesv = (#"get" classes-field (#"getParent" classloader))
509            for i below (#"size" classesv)
510            collect (#"getName" (#"elementAt" classesv i))))))
512(defun get-dynamic-class-path ()
513  (rest 
514   (find-if (lambda (loader) 
515              (string= "org.armedbear.lisp.JavaClassLoader"
516                       (jclass-name (jobject-class loader))))
517            (dump-classpath)
518            :key #'car)))
520(defun java-gc ()
521  (#"gc" (#"getRuntime" 'java.lang.runtime))
522  (#"runFinalization" (#"getRuntime" 'java.lang.runtime))
523  (#"gc" (#"getRuntime" 'java.lang.runtime))
524  (java-room))
526(defun java-room ()
527  (let ((rt (#"getRuntime" 'java.lang.runtime)))
528    (values (- (#"totalMemory" rt) (#"freeMemory" rt))
529            (#"totalMemory" rt)
530            (#"freeMemory" rt)
531            (list :used :total :free))))
533(defun verbose-gc (&optional (new-value nil new-value-supplied))
534  (if new-value-supplied
535      (progn (#"setVerbose" (#"getMemoryMXBean"  ' new-value) new-value)
536      (#"isVerbose" (#"getMemoryMXBean"  '
538(defun all-jars-below (directory) 
539  (loop with q = (system:list-directory directory) 
540     while q for top = (pop q)
541     if (null (pathname-name top)) do (setq q (append q (all-jars-below top))) 
542     if (equal (pathname-type top) "jar") collect top))
544(defun all-classfiles-below (directory) 
545  (loop with q = (system:list-directory directory) 
546     while q for top = (pop q)
547     if (null (pathname-name top)) do (setq q (append q (all-classfiles-below top ))) 
548     if (equal (pathname-type top) "class")
549     collect top
550       ))
552(defun all-classes-below-directory (directory)
553  (loop for file in (all-classfiles-below directory) collect
554       (format nil "~{~a.~}~a"
555               (subseq (pathname-directory file) (length (pathname-directory directory)))
556               (pathname-name file))
557       ))
559(defun classfiles-import (directory)
560  "Load all Java classes recursively contained under DIRECTORY in the current process."
561  (setq directory (truename directory))
562  (loop for full-class-name in (all-classes-below-directory directory)
563     for name = (#"replaceAll" full-class-name "^.*\\." "")
564     do
565       (pushnew full-class-name (gethash name *class-name-to-full-case-insensitive*) 
566                :test 'equal)))
568(defun set-to-list (set)
569  (declare (optimize (speed 3) (safety 0)))
570  (with-constant-signature ((iterator "iterator" t) (hasnext "hasNext") (next "next"))
571    (loop with iterator = (iterator set)
572       while (hasNext iterator)
573       for item = (next iterator)
574       collect item)))
576(defun jlist-to-list (list)
577  "Convert a LIST implementing java.util.List to a Lisp list."
578  (declare (optimize (speed 3) (safety 0)))
579  (loop :for i :from 0 :below (jcall "size" list)
580     :collecting (jcall "get" list i)))
582(defun jarray-to-list (jarray)
583  "Convert the Java array named by JARRARY into a Lisp list."
584  (declare (optimize (speed 3) (safety 0)))
585  (loop :for i :from 0 :below (jarray-length jarray)
586     :collecting (jarray-ref jarray i)))
588;;; Deprecated
590;;; XXX unclear what sort of list this would actually work on, as it
591;;; certainly doesn't seem to be any of the Java collection types
592;;; (what implements getNext())?
593(defun list-to-list (list)
594  (declare (optimize (speed 3) (safety 0)))
595  (with-constant-signature ((isEmpty "isEmpty") (getfirst "getFirst")
596                            (getNext "getNext"))
597    (loop until (isEmpty list)
598       collect (getFirst list)
599       do (setq list (getNext list)))))
601;; Contribution of Luke Hope. (Thanks!)
603(defun iterable-to-list (iterable)
604  "Return the items contained the java.lang.Iterable ITERABLE as a list."
605  (declare (optimize (speed 3) (safety 0)))
606  (let ((it (#"iterator" iterable)))
607    (with-constant-signature ((has-next "hasNext")
608                              (next "next"))
609      (loop :while (has-next it)
610         :collect (next it)))))
612(defun vector-to-list (vector)
613  "Return the elements of java.lang.Vector VECTOR as a list."
614  (declare (optimize (speed 3) (safety 0)))
615  (with-constant-signature ((has-more "hasMoreElements")
616                            (next "nextElement"))
617    (let ((elements (#"elements" vector)))
618      (loop :while (has-more elements)
619         :collect (next elements)))))
621(defun hashmap-to-hashtable (hashmap &rest rest &key (keyfun #'identity) (valfun #'identity) (invert? nil)
622                                                  table 
623                             &allow-other-keys )
624  "Converts the a HASHMAP reference to a java.util.HashMap object to a Lisp hashtable.
626The REST paramter specifies arguments to the underlying MAKE-HASH-TABLE call.
628KEYFUN and VALFUN specifies functions to be run on the keys and values
629of the HASHMAP right before they are placed in the hashtable.
631If INVERT? is non-nil than reverse the keys and values in the resulting hashtable."
632  (let ((keyset (#"keySet" hashmap))
633        (table (or table (apply 'make-hash-table
634                                (loop for (key value) on rest by #'cddr
635                                   unless (member key '(:invert? :valfun :keyfun :table)) 
636                                   collect key and collect value)))))
637    (with-constant-signature ((iterator "iterator" t) (hasnext "hasNext") (next "next"))
638      (loop with iterator = (iterator keyset)
639         while (hasNext iterator)
640         for item = (next iterator)
641         do (if invert?
642                (setf (gethash (funcall valfun (#"get" hashmap item)) table) (funcall keyfun item))
643                (setf (gethash (funcall keyfun item) table) (funcall valfun (#"get" hashmap item)))))
644      table)))
646(defun jclass-all-interfaces (class)
647  "Return a list of interfaces the class implements"
648  (unless (java-object-p class)
649    (setq class (find-java-class class)))
650  (loop for aclass = class then (#"getSuperclass" aclass)
651     while aclass
652     append (coerce (#"getInterfaces" aclass) 'list)))
654(defun safely (f name)
655  (let ((fname (gensym)))
656    (compile fname
657             `(lambda(&rest args)
658                (with-simple-restart (top-level
659                                      "Return from lisp method implementation for ~a." ,name)
660                  (apply ,f args))))
661    (symbol-function fname)))
663(defun jdelegating-interface-implementation (interface dispatch-to &rest method-names-and-defs)
664  "Creates and returns an implementation of a Java interface with
665   methods calling Lisp closures as given in METHOD-NAMES-AND-DEFS.
667   INTERFACE is an interface
669   DISPATCH-TO is an existing Java object
671   METHOD-NAMES-AND-DEFS is an alternating list of method names
672   (strings) and method definitions (closures).
674   For missing methods, a dummy implementation is provided that
675   calls the method on DISPATCH-TO."
676  (let ((implemented-methods
677         (loop for m in method-names-and-defs
678            for i from 0
679            if (evenp i) 
680            do (assert (stringp m) (m) "Method names must be strings: ~s" m) and collect m
681            else
682            do (assert (or (symbolp m) (functionp m)) (m) "Methods must be function designators: ~s" m))))
683    (let ((safe-method-names-and-defs 
684           (loop for (name function) on method-names-and-defs by #'cddr
685              collect name collect (safely function name))))
686      (loop for method across
687           (jclass-methods interface :declared nil :public t)
688         for method-name = (jmethod-name method)
689         when (not (member method-name implemented-methods :test #'string=))
690         do
691           (let* ((def  `(lambda
692                             (&rest args)
693                           (invoke-restargs ,(jmethod-name method) ,dispatch-to args t)
694                           )))
695             (push (coerce def 'function) safe-method-names-and-defs)
696             (push method-name safe-method-names-and-defs)))
697      (apply #'java::%jnew-proxy  interface safe-method-names-and-defs))))
Note: See TracBrowser for help on using the repository browser.