source: trunk/abcl/src/org/armedbear/lisp/runtime-class.lisp @ 13792

Last change on this file since 13792 was 13792, checked in by astalla, 12 years ago

A small reorganization of compiler/jvm code. Runtime-class wasn't autoloading properly in certain situations due to a wrong dependency graph among some system files.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 12.8 KB
Line 
1(require "JVM")
2
3;;The package is set to :jvm for convenience, since most of the symbols used
4;;here come from that package. However, the functions we're definining belong
5;;to the :java package.
6(in-package :jvm)
7
8(defconstant +abcl-java-object+ (make-jvm-class-name "org.armedbear.lisp.JavaObject"))
9
10(defun java:jnew-runtime-class
11    (class-name &rest args &key (superclass "java.lang.Object")
12     interfaces constructors methods fields (access-flags '(:public)) annotations)
13  "Creates and loads a Java class with methods calling Lisp closures
14   as given in METHODS.  CLASS-NAME and SUPER-NAME are strings,
15   INTERFACES is a list of strings, CONSTRUCTORS, METHODS and FIELDS are
16   lists of constructor, method and field definitions.
17
18   Constructor definitions - currently NOT supported - are lists of the form
19   (argument-types function &optional super-invocation-arguments)
20   where argument-types is a list of strings and function is a lisp function of
21   (1+ (length argument-types)) arguments; the instance (`this') is passed in as
22   the last argument. The optional super-invocation-arguments is a list of numbers
23   between 1 and (length argument-types), where the number k stands for the kth argument
24   to the just defined constructor. If present, the constructor of the superclass
25   will be called with the appropriate arguments. E.g., if the constructor definition is
26   ((\"java.lang.String\" \"int\") #'(lambda (string i this) ...) (2 1))
27   then the constructor of the superclass with argument types (int, java.lang.String) will
28   be called with the second and first arguments.
29
30   Method definitions are lists of the form
31   (method-name return-type argument-types function &key modifiers annotations)
32   where method-name is a string, return-type and argument-types are strings or keywords for
33   primitive types (:void, :int, etc.), and function is a Lisp function of minimum arity
34   (1+ (length argument-types)); the instance (`this') is passed in as the first argument.
35
36   Field definitions are lists of the form (field-name type &key modifiers annotations)."
37  (declare (ignorable superclass interfaces constructors methods fields access-flags annotations))
38  (let ((stream (sys::%make-byte-array-output-stream))
39         ;;TODO provide constructor in MemoryClassLoader
40        (memory-class-loader (java:jnew "org.armedbear.lisp.MemoryClassLoader" "")))
41    (multiple-value-bind (class-file method-implementation-fields)
42        (apply #'java::%jnew-runtime-class class-name stream args)
43      (sys::put-memory-function memory-class-loader
44                                class-name (sys::%get-output-stream-bytes stream))
45      (let ((jclass (java:jcall "loadClass" memory-class-loader class-name)))
46        (dolist (method method-implementation-fields)
47          (setf (java:jfield jclass (car method)) (cdr method)))
48        jclass))))
49
50(defun java::%jnew-runtime-class
51    (class-name stream &key (superclass "java.lang.Object")
52     interfaces constructors methods fields (access-flags '(:public)) annotations)
53  "Actual implementation of jnew-runtime-class. Writes the class bytes to a stream. Returns two values: the finalized class-file structure and the alist of method implementation fields."
54  (let* ((jvm-class-name (make-jvm-class-name class-name))
55         (class-file (make-class-file jvm-class-name (make-jvm-class-name superclass) access-flags))
56         method-implementation-fields)
57    (setf (class-file-interfaces class-file)
58          (mapcar #'make-jvm-class-name interfaces))
59    (when annotations
60      (class-add-attribute class-file (make-runtime-visible-annotations-attribute
61                                       :list (mapcar #'parse-annotation annotations))))
62    (setf method-implementation-fields (java::runtime-class-add-methods class-file methods))
63    (java::runtime-class-add-fields class-file fields)
64    (if (null constructors)
65      (let ((ctor (make-jvm-method :constructor :void nil :flags '(:public))))
66        (class-add-method class-file ctor)
67        (with-code-to-method (class-file ctor)
68          (aload 0)
69          (emit-invokespecial-init (class-file-superclass class-file) nil)
70          (emit 'return)))
71      (error "constructors not supported"))
72    (finalize-class-file class-file)
73    (write-class-file class-file stream)
74    (finish-output stream)
75    #+test-record-generated-class-file
76    (with-open-file (f (format nil "~A.class" class-name) :direction :output :element-type '(signed-byte 8))
77      (write-sequence (java::list-from-jarray (sys::%get-output-stream-bytes stream)) f))
78    (values class-file method-implementation-fields)))
79
80(defun java::make-accessor-name (prefix name)
81  (let ((initial (char-upcase (aref name 0)))
82        (rest (subseq name 1)))
83    (format nil "~A~A~A" prefix initial rest)))
84
85(defun java::runtime-class-add-methods (class-file methods)
86  (let (method-implementation-fields)
87    (dolist (m methods)
88      (destructuring-bind (name return-type argument-types function &key (modifiers '(:public)) annotations) m
89        (let* ((argument-types (mapcar #'make-jvm-class-name argument-types))
90               (argc (length argument-types))
91               (return-type (if (keywordp return-type)
92                                return-type
93                                (make-jvm-class-name return-type)))
94               (jmethod (make-jvm-method name return-type argument-types :flags modifiers))
95               (field-name (string (gensym name))))
96          (class-add-method class-file jmethod)
97          (let ((field (make-field field-name +lisp-object+ :flags '(:public :static))))
98            (class-add-field class-file field)
99            (push (cons field-name function) method-implementation-fields))
100          (when annotations
101            (method-add-attribute jmethod (make-runtime-visible-annotations-attribute
102                                           :list (mapcar #'parse-annotation annotations))))
103          (with-code-to-method (class-file jmethod)
104            ;;Allocate registers (2 * argc to load and store arguments + 2 to box "this")
105            (dotimes (i (* 2 (1+ argc)))
106              (allocate-register nil))
107            ;;Box "this" (to be passed as the first argument to the Lisp function)
108            (aload 0)
109            (emit 'iconst_1) ;;true
110            (emit-invokestatic +abcl-java-object+ "getInstance"
111                               (list +java-object+ :boolean) +lisp-object+)
112            (astore (1+ argc))
113            ;;Box each argument
114            (loop
115               :for arg-type :in argument-types
116               :for i :from 1
117               :do (progn
118                     (cond
119                       ((keywordp arg-type)
120                        (error "Unsupported arg-type: ~A" arg-type))
121                       ((eq arg-type :int) :todo)
122                       (t (aload i)
123                          (emit 'iconst_1) ;;true
124                          (emit-invokestatic +abcl-java-object+ "getInstance"
125                                             (list +java-object+ :boolean) +lisp-object+)))
126                     (astore (+ i (1+ argc)))))
127            ;;Load the Lisp function from its static field
128            (emit-getstatic (class-file-class class-file) field-name +lisp-object+)
129            (if (<= (1+ argc) call-registers-limit)
130                (progn
131                  ;;Load the boxed this
132                  (aload (1+ argc))
133                  ;;Load each boxed argument
134                  (dotimes (i argc)
135                    (aload (+ argc 2 i))))
136                (error "execute(LispObject[]) is currently not supported"))
137            (emit-call-execute (1+ (length argument-types)))
138            (cond
139              ((eq return-type :void)
140               (emit 'pop)
141               (emit 'return))
142              ((eq return-type :int)
143               (emit-invokevirtual +lisp-object+ "intValue" nil :int)
144               (emit 'ireturn))
145              ((jvm-class-name-p return-type)
146               (emit-invokevirtual +lisp-object+ "javaInstance" nil +java-object+)
147               (emit-checkcast return-type)
148               (emit 'areturn))
149              (t
150               (error "Unsupported return type: ~A" return-type)))))))
151    method-implementation-fields))
152
153(defun java::runtime-class-add-fields (class-file fields)
154  (dolist (field-spec fields)
155    (destructuring-bind (name type &key (modifiers '(:public)) annotations
156                              (getter nil getter-p) (setter nil setter-p)
157                              (property (and (not getter-p) (not setter-p))))
158        field-spec
159      (let* ((type (if (keywordp type) type (make-jvm-class-name type)))
160             (field (make-field name type :flags modifiers)))
161        (when (member :static modifiers)
162          (setf property nil getter nil setter nil))
163        (when annotations
164          (field-add-attribute field (make-runtime-visible-annotations-attribute
165                                      :list (mapcar #'parse-annotation annotations))))
166        (class-add-field class-file field)
167        (when (or getter property)
168          (unless (stringp getter)
169            (setf getter (java::make-accessor-name "get" (if (stringp property) property name))))
170          (let ((jmethod (make-jvm-method getter type nil :flags '(:public))))
171            (class-add-method class-file jmethod)
172            (with-code-to-method (class-file jmethod)
173              (aload 0)
174              (emit-getfield (class-file-class class-file) name type)
175              (cond
176                ((jvm-class-name-p type) (emit 'areturn))
177                ((eq type :int) (emit 'ireturn))
178                (t (error "Unsupported getter return type: ~A" type))))))
179        (when (or setter property)
180          (unless (stringp setter)
181            (setf setter (java::make-accessor-name "set" (if (stringp property) property name))))
182          (let ((jmethod (make-jvm-method setter :void (list type) :flags '(:public))))
183            (class-add-method class-file jmethod)
184            (with-code-to-method (class-file jmethod)
185              (aload 0)
186              (cond
187                ((jvm-class-name-p type) (aload 1))
188                ((eq type :int) (emit 'iload 1))
189                (t (error "Unsupported setter parameter type: ~A" type)))
190              (emit-putfield (class-file-class class-file) name type)
191              (emit 'return))))))))
192
193(defmacro java:define-java-class () :todo)
194
195(defun parse-annotation (annotation)
196  (when (annotation-p annotation)
197    (return-from parse-annotation annotation))
198  (destructuring-bind (class &rest elements) (if (listp annotation) annotation (list annotation))
199    (let (actual-elements)
200      (dolist (elem elements)
201        (push (parse-annotation-element elem) actual-elements))
202      (make-annotation :type class :elements (nreverse actual-elements)))))
203
204(defun parse-annotation-element (elem)
205  (cond
206    ((annotation-element-p elem) elem)
207    ((atom elem) (make-primitive-or-string-annotation-element :name nil :value elem))
208    ((keywordp (car elem)) (parse-annotation-element `("value" ,@elem)))
209    (t
210     (destructuring-bind (name &key value enum annotation) elem
211       (cond
212         (enum (make-enum-value-annotation-element :name name :type enum :value value))
213         (annotation
214          (make-annotation-value-annotation-element :name name :value (parse-annotation annotation)))
215         ((listp value)
216          (make-array-annotation-element :name name :values (mapcar #'parse-annotation-element value)))
217         (t (make-primitive-or-string-annotation-element :name name :value value)))))))
218
219;;TODO:
220;; - Returning nil as null is broken
221;; - Function calls with 8+ args
222;; - super method invocation. Idea: generate companion methods super_... to use with plain jcall. Add a flag per method to optionally disable this when not needed.
223;; - Constructors
224;; - optional accessors (CLOS methods) for properties?
225
226#+example
227(java:jnew-runtime-class
228 "Foo"
229 :interfaces (list "java.lang.Comparable")
230 :fields (list '("someField" "java.lang.String") '("anotherField" "java.lang.Object" :getter t))
231 :methods (list
232           (list "foo" :void '("java.lang.Object")
233                 (lambda (this that) (print (list this that)))
234                 :annotations (list "java.lang.Deprecated"
235                                    '("java.lang.annotation.Retention"
236                                      (:enum "java.lang.annotation.RetentionPolicy" :value "RUNTIME"))
237                                    '("javax.xml.bind.annotation.XmlAttribute" ("required" :value t))
238                                    '("com.manydesigns.portofino.system.model.users.annotations.RequiresPermissions"
239                                      ("level"
240                                       :enum "com.manydesigns.portofino.model.pages.AccessLevel"
241                                       :value "EDIT")
242                                      ("permissions" :value ("foo" "bar")))))
243           (list "bar" :int '("java.lang.Object")
244                 (lambda (this that) (print (list this that)) 23))))
245
246(provide "RUNTIME-CLASS")
Note: See TracBrowser for help on using the repository browser.