summaryrefslogtreecommitdiff
path: root/src/genclass.clj
blob: 5453b8e27939a707dd10f42c9ce4dcbaf0fe92b2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
;   Copyright (c) Rich Hickey. All rights reserved.
;   The use and distribution terms for this software are covered by the
;   Common Public License 1.0 (http://opensource.org/licenses/cpl.php)
;   which can be found in the file CPL.TXT at the root of this distribution.
;   By using this software in any fashion, you are agreeing to be bound by
;   the terms of this license.
;   You must not remove this notice, or any other, from this software.

(import '(java.lang.reflect Modifier Constructor)
        '(clojure.asm ClassWriter ClassVisitor Opcodes Type)
        '(clojure.asm.commons Method GeneratorAdapter)
        '(clojure.lang IPersistentMap))

(defn method-sig [#^java.lang.reflect.Method meth]
  [(. meth (getName)) (seq (. meth (getParameterTypes)))])

(defn non-private-methods [#^Class c]
  (loop [mm {}
         considered #{}
         c c]
    (if c
      (let [[mm considered]
            (loop [mm mm
                   considered considered
                   meths (concat
                          (seq (. c (getDeclaredMethods)))
                          (seq (. c (getMethods))))]
              (if meths
                (let [#^Method meth (first meths)
                      mods (. meth (getModifiers))
                      mk (method-sig meth)]
                  (if (or (considered mk)
                          (. Modifier (isPrivate mods))
                          (. Modifier (isStatic mods))
                          (. Modifier (isFinal mods)))
                    (recur mm (conj considered mk) (rest meths))
                    (recur (assoc mm mk meth) (conj considered mk) (rest meths))))
                [mm considered]))]
        (recur mm considered (. c (getSuperclass))))
      mm)))

(defn ctor-sigs [super]
  (for [#^Constructor ctor (. super (getDeclaredConstructors))
        :when (not (. Modifier (isPrivate (. ctor (getModifiers)))))]
    (apply vector (. ctor (getParameterTypes)))))

(distinct (map first(keys (mapcat non-private-methods [Object IPersistentMap]))))

(defn gen-class
  ([name [super & interfaces :as supers]]
   (gen-class name supers (zipmap (ctor-sigs super) (ctor-sigs super))))
  ([name [super & interfaces :as supers] ctor-sig-map]
   (let [cv (new ClassWriter (. ClassWriter COMPUTE_MAXS))
         cname (. name (replace "." "/"))
         ctype (. Type (getObjectType cname))
         iname (fn [c] (.. Type (getType c) (getInternalName)))
         totype (fn [c] (. Type (getType c)))
         to-types (fn [cs] (if (pos? (count cs))
                             (into-array (map totype cs))
                             (make-array Type 0)))
         obj-type (totype Object)
         arg-types (fn [n] (if (pos? n)
                             (into-array (replicate n obj-type))
                             (make-array Type 0)))
         super-type (totype super)
         init-name "__init"
         factory-name "__create"
         state-name "__state"
         main-name "main"
         var-name (fn [s] (str s "__var"))
         rt-type  (totype clojure.lang.RT)
         var-type  (totype clojure.lang.Var)
         ifn-type (totype clojure.lang.IFn)
         ex-type  (totype java.lang.UnsupportedOperationException)
         var-fields (list* init-name factory-name main-name
                                         (distinct (map first (keys (mapcat non-private-methods supers)))))
         emit-get-var (fn [gen v]
                        (let [false-label (. gen newLabel)
                              end-label (. gen newLabel)]
                          (. gen getStatic ctype (var-name v) var-type)
                          (. gen invokeVirtual var-type (. Method (getMethod "boolean isBound()")))
                          (. gen ifZCmp (GeneratorAdapter.EQ) false-label)
                          (. gen getStatic ctype (var-name v) var-type)
                          (. gen goTo end-label)
                          (. gen mark false-label)
                          (. gen visitInsn (Opcodes.ACONST_NULL))
                          (. gen mark end-label)))
         emit-forwarding-method
                (fn [#^java.lang.reflect.Method meth else-gen]
                  (let [pclasses (. meth (getParameterTypes))
                        ptypes (to-types pclasses)
                        rtype (totype (. meth (getReturnType)))
                        m (new Method (. meth (getName)) rtype ptypes)
                        gen (new GeneratorAdapter (. Opcodes ACC_PUBLIC) m nil nil cv)
                        else-label (. gen (newLabel))
                        end-label (. gen (newLabel))
                        decl-type (. Type (getType (. meth (getDeclaringClass))))]
                    (. gen (visitCode))
                    (emit-get-var gen (. meth (getName)))
                    (. gen (dup))
                    (. gen (ifNull else-label))
                                        ;if found
                    (. gen (loadThis))
                                        ;box args
                    (dotimes i (count ptypes)
                      (. gen (loadArg i))
                      (. clojure.lang.Compiler$HostExpr (emitBoxReturn nil gen (nth pclasses i))))
                                        ;call fn
                    (. gen (invokeInterface ifn-type (new Method "invoke" obj-type 
                                                          (into-array (cons obj-type 
                                                                            (replicate (count ptypes) obj-type))))))
                                        ;unbox return
                    (. gen (unbox rtype))
                    (when (= (. rtype (getSort)) (. Type VOID))
                      (. gen (pop)))
                    (. gen (goTo end-label))
                    
                                        ;else call supplied alternative generator
                    (. gen (mark else-label))
                    (. gen (pop))
                    
                    (else-gen gen m)
                    
                    (. gen (mark end-label))
                    (. gen (returnValue))
                    (. gen (endMethod))))
         ]
                                        ;start class definition
     (. cv (visit (. Opcodes V1_5) (. Opcodes ACC_PUBLIC)
                  cname nil (iname super)
                  (when interfaces
                    (into-array (map iname interfaces)))))

                                        ;static fields for vars
     (doseq v var-fields
       (. cv (visitField (+ (Opcodes.ACC_PUBLIC) (Opcodes.ACC_FINAL) (Opcodes.ACC_STATIC))
                         (var-name v) 
                         (. var-type getDescriptor)
                         nil nil)))

                                        ;instance field for state
     (. cv (visitField (+ (Opcodes.ACC_PUBLIC) (Opcodes.ACC_FINAL))
                       state-name 
                       (. obj-type getDescriptor)
                       nil nil))

                                        ;static init to set up var fields
     (let [gen (new GeneratorAdapter (+ (Opcodes.ACC_PUBLIC) (Opcodes.ACC_STATIC)) 
                    (Method.getMethod "void <clinit> ()")
                    nil nil cv)]
       (. gen (visitCode))
       (doseq v var-fields
         (. gen push name)
         (. gen push v)
         (. gen (invokeStatic rt-type (. Method (getMethod "clojure.lang.Var var(String,String)"))))
         (. gen putStatic ctype (var-name v) var-type))              
       (. gen (returnValue))
       (. gen (endMethod)))

                                        ;ctors
     (doseq [pclasses super-pclasses] ctor-sig-map
       (let [ptypes (to-types pclasses)
             super-ptypes (to-types super-pclasses)
             m (new Method "<init>" (. Type VOID_TYPE) ptypes)
             super-m (new Method "<init>" (. Type VOID_TYPE) super-ptypes)
             gen (new GeneratorAdapter (. Opcodes ACC_PUBLIC) m nil nil cv)
             no-init-label (. gen newLabel)
             end-label (. gen newLabel)
             nth-method (. Method (getMethod "Object nth(Object,int)"))
             local (. gen newLocal obj-type)]
         (. gen (visitCode))

         (emit-get-var gen init-name)
         (. gen dup)
         (. gen ifNull no-init-label)
                                        ;box init args
         (dotimes i (count pclasses)
           (. gen (loadArg i))
           (. clojure.lang.Compiler$HostExpr (emitBoxReturn nil gen (nth pclasses i))))
                                        ;call init fn
         (. gen (invokeInterface ifn-type (new Method "invoke" obj-type 
                                               (arg-types (count ptypes)))))
                                        ;expecting [[super-ctor-args] state] returned
         (. gen dup)
         (. gen push 0)
         (. gen (invokeStatic rt-type nth-method))
         (. gen storeLocal local)
         
         (. gen (loadThis))