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

Last change on this file since 13785 was 13785, checked in by astalla, 11 years ago

Refactoring in runtime-class.
Added annotations on class.
Added fields (with annotations as well).

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