source: branches/1.0.x/abcl/src/org/armedbear/lisp/jvm-class-file.lisp

Last change on this file was 13535, checked in by ehuelsmann, 14 years ago

Moving huge object serialization from <init>() to <clinit>()
broke the code generation for that special case -- there's no longer
a 'this' variable to be loaded. Replace with <this class>.class.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 52.3 KB
Line 
1;;; jvm-class-file.lisp
2;;;
3;;; Copyright (C) 2010 Erik Huelsmann
4;;; $Id: jvm-class-file.lisp 13535 2011-08-23 20:35:32Z ehuelsmann $
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 "JVM")
33
34#|
35
36The general design of the class-file writer is to have generic
37- human readable - representations of the class being generated
38during the construction and manipulation phases.
39
40After completing the creation/manipulation of the class, all its
41components will be finalized. This process translates readable
42(e.g. string) representations to indices to be stored on disc.
43
44The only thing to be done after finalization is sending the
45output to a stream ("writing").
46
47
48Finalization happens highest-level first. As an example, take a
49method with exception handlers. The exception handlers are stored
50as attributes in the class file structure. They are children of the
51method's Code attribute. In this example, the body of the Code
52attribute (the higher level) gets finalized before the attributes.
53The reason to do so is that the exceptions need to refer to labels
54(offsets) in the Code segment.
55
56
57|#
58
59
60(defun map-primitive-type (type)
61  "Maps a symbolic primitive type name to its Java string representation."
62  (case type
63    (:int        "I")
64    (:long       "J")
65    (:float      "F")
66    (:double     "D")
67    (:boolean    "Z")
68    (:char       "C")
69    (:byte       "B")
70    (:short      "S")
71    ((nil :void) "V")))
72
73
74#|
75
76The `class-name' facility helps to abstract from "this instruction takes
77a reference" and "this instruction takes a class name". We simply pass
78the class name around and the instructions themselves know which
79representation to use.
80
81|#
82
83(defstruct (jvm-class-name (:conc-name class-)
84         (:constructor %make-jvm-class-name))
85  "Used for class identification.
86
87The caller should instantiate only one `class-name' per class, as they are
88used as class identifiers and compared using EQ.
89
90Some instructions need a class argument, others need a reference identifier.
91This class is used to abstract from the difference."
92  name-internal
93  ref
94  array-class ;; cached array class reference
95  ;; keeping a reference to the associated array class allows class
96  ;; name comparisons to be EQ: all classes should exist only once,
97  )
98
99(defun make-jvm-class-name (name)
100  "Creates a `class-name' structure for the class or interface `name'.
101
102`name' should be specified using Java representation, which is converted
103to 'internal' (JVM) representation by this function."
104  (setf name (substitute #\/ #\. name))
105  (%make-jvm-class-name :name-internal name
106      :ref (concatenate 'string "L" name ";")))
107
108(defun class-array (class-name)
109  "Returns a class-name representing an array of `class-name'.
110For multi-dimensional arrays, call this function multiple times, using
111its own result.
112
113This function can be called multiple times on the same `class-name' without
114violating the 'only one instance' requirement: the returned value is cached
115and used on successive calls."
116  (unless (class-array-class class-name)
117    ;; Alessio Stalla found by dumping a class file that the JVM uses
118    ;; the same representation (ie '[L<class-name>;') in CHECKCAST as
119    ;; it does in field references, meaning the class name and class ref
120    ;; are identified by the same string
121    (let ((name-and-ref (concatenate 'string "[" (class-ref class-name))))
122      (setf (class-array-class class-name)
123            (%make-jvm-class-name :name-internal name-and-ref
124          :ref name-and-ref))))
125  (class-array-class class-name))
126
127(defmacro define-class-name (symbol java-dotted-name &optional documentation)
128  "Convenience macro to define constants for `class-name' structures,
129initialized from the `java-dotted-name'."
130  `(defconstant ,symbol (make-jvm-class-name ,java-dotted-name)
131     ,documentation))
132
133(define-class-name +java-class+ "java.lang.Class")
134(define-class-name +java-object+ "java.lang.Object")
135(define-class-name +java-string+ "java.lang.String")
136(define-class-name +java-system+ "java.lang.System")
137(define-class-name +java-io-input-stream+ "java.io.InputStream")
138(define-class-name +lisp-object+ "org.armedbear.lisp.LispObject")
139(defconstant +lisp-object-array+ (class-array +lisp-object+))
140(define-class-name +lisp-simple-string+ "org.armedbear.lisp.SimpleString")
141(define-class-name +lisp+ "org.armedbear.lisp.Lisp")
142(define-class-name +lisp-nil+ "org.armedbear.lisp.Nil")
143(define-class-name +lisp-class+ "org.armedbear.lisp.LispClass")
144(define-class-name +lisp-symbol+ "org.armedbear.lisp.Symbol")
145(define-class-name +lisp-thread+ "org.armedbear.lisp.LispThread")
146(define-class-name +lisp-closure-binding+ "org.armedbear.lisp.ClosureBinding")
147(defconstant +closure-binding-array+ (class-array +lisp-closure-binding+))
148(define-class-name +lisp-integer+ "org.armedbear.lisp.LispInteger")
149(define-class-name +lisp-fixnum+ "org.armedbear.lisp.Fixnum")
150(defconstant +lisp-fixnum-array+ (class-array +lisp-fixnum+))
151(define-class-name +lisp-bignum+ "org.armedbear.lisp.Bignum")
152(define-class-name +lisp-single-float+ "org.armedbear.lisp.SingleFloat")
153(define-class-name +lisp-double-float+ "org.armedbear.lisp.DoubleFloat")
154(define-class-name +lisp-cons+ "org.armedbear.lisp.Cons")
155(define-class-name +lisp-load+ "org.armedbear.lisp.Load")
156(define-class-name +lisp-character+ "org.armedbear.lisp.LispCharacter")
157(defconstant +lisp-character-array+ (class-array +lisp-character+))
158(define-class-name +lisp-structure-object+ "org.armedbear.lisp.StructureObject")
159(define-class-name +lisp-simple-vector+ "org.armedbear.lisp.SimpleVector")
160(define-class-name +lisp-abstract-string+ "org.armedbear.lisp.AbstractString")
161(define-class-name +lisp-abstract-vector+ "org.armedbear.lisp.AbstractVector")
162(define-class-name +lisp-abstract-bit-vector+
163    "org.armedbear.lisp.AbstractBitVector")
164(define-class-name +lisp-environment+ "org.armedbear.lisp.Environment")
165(define-class-name +lisp-special-binding+ "org.armedbear.lisp.SpecialBinding")
166(define-class-name +lisp-special-bindings-mark+
167    "org.armedbear.lisp.SpecialBindingsMark")
168(define-class-name +lisp-throw+ "org.armedbear.lisp.Throw")
169(define-class-name +lisp-return+ "org.armedbear.lisp.Return")
170(define-class-name +lisp-go+ "org.armedbear.lisp.Go")
171(define-class-name +lisp-primitive+ "org.armedbear.lisp.Primitive")
172(define-class-name +lisp-compiled-primitive+
173    "org.armedbear.lisp.CompiledPrimitive")
174(define-class-name +lisp-eql-hash-table+ "org.armedbear.lisp.EqlHashTable")
175(define-class-name +lisp-hash-table+ "org.armedbear.lisp.HashTable")
176(define-class-name +lisp-package+ "org.armedbear.lisp.Package")
177(define-class-name +lisp-readtable+ "org.armedbear.lisp.Readtable")
178(define-class-name +lisp-stream+ "org.armedbear.lisp.Stream")
179(define-class-name +lisp-closure+ "org.armedbear.lisp.Closure")
180(define-class-name +lisp-compiled-closure+ "org.armedbear.lisp.CompiledClosure")
181(define-class-name +lisp-closure-parameter+
182    "org.armedbear.lisp.Closure$Parameter")
183(defconstant +lisp-closure-parameter-array+
184  (class-array +lisp-closure-parameter+))
185
186#|
187
188Lisp-side descriptor representation:
189
190 - list: a list starting with a method return value, followed by
191     the argument types
192 - keyword: the primitive type associated with that keyword
193 - class-name structure instance: the class-ref value
194
195The latter two can be converted to a Java representation using
196the `internal-field-ref' function, the former is to be fed to
197`descriptor'.
198
199|#
200
201(defun internal-field-type (field-type)
202  "Returns a string containing the JVM-internal representation
203of `field-type', which should either be a symbol identifying a primitive
204type, or a `class-name' structure identifying a class or interface."
205  (if (symbolp field-type)
206      (map-primitive-type field-type)
207      (class-name-internal field-type)))
208
209(defun internal-field-ref (field-type)
210  "Returns a string containing the JVM-internal representation of a reference
211to `field-type', which should either be a symbol identifying a primitive
212type, or a `class-name' structure identifying a class or interface."
213  (if (symbolp field-type)
214      (map-primitive-type field-type)
215      (class-ref field-type)))
216
217(defun descriptor (return-type &rest argument-types)
218  "Returns a string describing the `return-type' and `argument-types'
219in JVM-internal representation."
220  (let* ((arg-strings (mapcar #'internal-field-ref argument-types))
221         (ret-string (internal-field-ref return-type))
222         (size (+ 2 (reduce #'+ arg-strings
223                            :key #'length
224                            :initial-value (length ret-string))))
225         (str (make-array size :fill-pointer 0 :element-type 'character)))
226    (with-output-to-string (s str)
227      (princ #\( s)
228      (dolist (arg-string arg-strings)
229        (princ arg-string s))
230      (princ #\) s)
231      (princ ret-string s))
232    str)
233;;  (format nil "(~{~A~})~A"
234;;          (internal-field-ref return-type))
235  )
236
237(defun descriptor-stack-effect (return-type &rest argument-types)
238  "Returns the effect on the stack position of the `argument-types' and
239`return-type' of a method call.
240
241If the method consumes an implicit `this' argument, this function does not
242take that effect into account."
243  (flet ((type-stack-effect (arg)
244           (case arg
245             ((:long :double) 2)
246             ((nil :void) 0)
247             (otherwise 1))))
248    (+ (reduce #'- argument-types
249               :key #'type-stack-effect
250               :initial-value 0)
251       (type-stack-effect return-type))))
252
253
254(defstruct pool
255  ;; `index' contains the index of the last allocated slot (0 == empty)
256  ;; "A constant pool entry is considered valid if it has
257  ;; an index greater than 0 (zero) and less than pool-count"
258  (index 0)
259  entries-list
260  ;; the entries hash stores raw values, except in case of string and
261  ;; utf8, because both are string values
262  (entries (make-hash-table :test #'equal :size 2048 :rehash-size 2.0)))
263
264
265(defstruct constant
266  "Structure to be included in all constant sub-types."
267  tag
268  index)
269
270(defparameter +constant-type-map+
271  '((:class          7 1)
272    (:field-ref      9 1)
273    (:method-ref    10 1)
274    ;; (:interface-method-ref 11)
275    (:string         8 1)
276    (:integer        3 1)
277    (:float          4 1)
278    (:long           5 2)
279    (:double         6 2)
280    (:name-and-type 12 1)
281    (:utf8           1 1)))
282
283(defstruct (constant-class (:constructor make-constant-class (index name-index))
284                           (:include constant
285                                     (tag 7)))
286  "Structure holding information on a 'class' type item in the constant pool."
287  name-index)
288
289(defstruct (constant-member-ref (:constructor
290                                 %make-constant-member-ref
291                                     (tag index class-index name/type-index))
292                                (:include constant))
293  "Structure holding information on a member reference type item
294(a field, method or interface method reference) in the constant pool."
295  class-index
296  name/type-index)
297
298(declaim (inline make-constant-field-ref make-constant-method-ref
299                 make-constant-interface-method-ref))
300(defun make-constant-field-ref (index class-index name/type-index)
301  "Creates a `constant-member-ref' instance containing a field reference."
302  (%make-constant-member-ref 9 index class-index name/type-index))
303
304(defun make-constant-method-ref (index class-index name/type-index)
305  "Creates a `constant-member-ref' instance containing a method reference."
306  (%make-constant-member-ref 10 index class-index name/type-index))
307
308(defun make-constant-interface-method-ref (index class-index name/type-index)
309  "Creates a `constant-member-ref' instance containing an
310interface-method reference."
311  (%make-constant-member-ref 11 index class-index name/type-index))
312
313(defstruct (constant-string (:constructor
314                             make-constant-string (index value-index))
315                            (:include constant
316                                      (tag 8)))
317  "Structure holding information on a 'string' type item in the constant pool."
318  value-index)
319
320(defstruct (constant-float/int (:constructor
321                                %make-constant-float/int (tag index value))
322                               (:include constant))
323  "Structure holding information on a 'float' or 'integer' type item
324in the constant pool."
325  value)
326
327(declaim (inline make-constant-float make-constant-int))
328(defun make-constant-float (index value)
329  "Creates a `constant-float/int' structure instance containing a float."
330  (%make-constant-float/int 4 index value))
331
332(defun make-constant-int (index value)
333  "Creates a `constant-float/int' structure instance containing an int."
334  (%make-constant-float/int 3 index value))
335
336(defstruct (constant-double/long (:constructor
337                                  %make-constant-double/long (tag index value))
338                                 (:include constant))
339  "Structure holding information on a 'double' or 'long' type item
340in the constant pool."
341  value)
342
343(declaim (inline make-constant-double make-constant-float))
344(defun make-constant-double (index value)
345  "Creates a `constant-double/long' structure instance containing a double."
346  (%make-constant-double/long 6 index value))
347
348(defun make-constant-long (index value)
349  "Creates a `constant-double/long' structure instance containing a long."
350  (%make-constant-double/long 5 index value))
351
352(defstruct (constant-name/type (:constructor
353                                make-constant-name/type (index
354                                                         name-index
355                                                         descriptor-index))
356                               (:include constant
357                                         (tag 12)))
358  "Structure holding information on a 'name-and-type' type item in the
359constant pool; this type of element is used by 'member-ref' type items."
360  name-index
361  descriptor-index)
362
363(defstruct (constant-utf8 (:constructor make-constant-utf8 (index value))
364                          (:include constant
365                                    (tag 1)))
366  "Structure holding information on a 'utf8' type item in the constant pool;
367
368This type of item is used for text representation of identifiers
369and string contents."
370  value)
371
372
373(defun pool-add-class (pool class)
374  "Returns the index of the constant-pool class item for `class'.
375
376`class' must be an instance of `class-name'."
377  (let ((entry (gethash class (pool-entries pool))))
378    (unless entry
379      (let ((utf8 (pool-add-utf8 pool (class-name-internal class))))
380        (setf entry
381              (make-constant-class (incf (pool-index pool)) utf8)
382              (gethash class (pool-entries pool)) entry))
383      (push entry (pool-entries-list pool)))
384    (constant-index entry)))
385
386(defun pool-add-field-ref (pool class name type)
387  "Returns the index of the constant-pool item which denotes a reference
388to the `name' field of the `class', being of `type'.
389
390`class' should be an instance of `class-name'.
391`name' is a string.
392`type' is a field-type (see `internal-field-type')"
393  (let ((entry (gethash (acons name type class) (pool-entries pool))))
394    (unless entry
395      (let ((c (pool-add-class pool class))
396            (n/t (pool-add-name/type pool name type)))
397        (setf entry (make-constant-field-ref (incf (pool-index pool)) c n/t)
398            (gethash (acons name type class) (pool-entries pool)) entry))
399      (push entry (pool-entries-list pool)))
400    (constant-index entry)))
401
402(defun pool-add-method-ref (pool class name type)
403  "Returns the index of the constant-pool item which denotes a reference
404to the method with `name' in `class', which is of `type'.
405
406Here, `type' is a method descriptor, which defines the argument types
407and return type. `class' is an instance of `class-name'."
408  (let ((entry (gethash (acons name type class) (pool-entries pool))))
409    (unless entry
410      (let ((c (pool-add-class pool class))
411            (n/t (pool-add-name/type pool name type)))
412        (setf entry (make-constant-method-ref (incf (pool-index pool)) c n/t)
413              (gethash (acons name type class) (pool-entries pool)) entry))
414      (push entry (pool-entries-list pool)))
415    (constant-index entry)))
416
417(defun pool-add-interface-method-ref (pool class name type)
418  "Returns the index of the constant-pool item which denotes a reference to
419the method `name' in the interface `class', which is of `type'.
420
421See `pool-add-method-ref' for remarks."
422  (let ((entry (gethash (acons name type class) (pool-entries pool))))
423    (unless entry
424      (let ((c (pool-add-class pool class))
425            (n/t (pool-add-name/type pool name type)))
426        (setf entry
427            (make-constant-interface-method-ref (incf (pool-index pool)) c n/t)
428            (gethash (acons name type class) (pool-entries pool)) entry))
429      (push entry (pool-entries-list pool)))
430    (constant-index entry)))
431
432(defun pool-add-string (pool string)
433  "Returns the index of the constant-pool item denoting the string."
434  (let ((entry (gethash (cons 8 string) ;; 8 == string-tag
435                        (pool-entries pool))))
436    (unless entry
437      (let ((utf8 (pool-add-utf8 pool string)))
438        (setf entry (make-constant-string (incf (pool-index pool)) utf8)
439              (gethash (cons 8 string) (pool-entries pool)) entry))
440      (push entry (pool-entries-list pool)))
441    (constant-index entry)))
442
443(defun pool-add-int (pool int)
444  "Returns the index of the constant-pool item denoting the int."
445  (let ((entry (gethash (cons 3 int) (pool-entries pool))))
446    (unless entry
447      (setf entry (make-constant-int (incf (pool-index pool)) int)
448            (gethash (cons 3 int) (pool-entries pool)) entry)
449      (push entry (pool-entries-list pool)))
450    (constant-index entry)))
451
452(defun pool-add-float (pool float)
453  "Returns the index of the constant-pool item denoting the float."
454  (let ((entry (gethash (cons 4 float) (pool-entries pool))))
455    (unless entry
456      (setf entry (make-constant-float (incf (pool-index pool))
457                                       (sys::%float-bits float))
458            (gethash (cons 4 float) (pool-entries pool)) entry)
459      (push entry (pool-entries-list pool)))
460    (constant-index entry)))
461
462(defun pool-add-long (pool long)
463  "Returns the index of the constant-pool item denoting the long."
464  (let ((entry (gethash (cons 5 long) (pool-entries pool))))
465    (unless entry
466      (setf entry (make-constant-long (incf (pool-index pool)) long)
467            (gethash (cons 5 long) (pool-entries pool)) entry)
468      (push entry (pool-entries-list pool))
469      (incf (pool-index pool))) ;; double index increase; long takes 2 slots
470    (constant-index entry)))
471
472(defun pool-add-double (pool double)
473  "Returns the index of the constant-pool item denoting the double."
474  (let ((entry (gethash (cons 6 double) (pool-entries pool))))
475    (unless entry
476      (setf entry (make-constant-double (incf (pool-index pool))
477                                        (sys::%float-bits double))
478            (gethash (cons 6 double) (pool-entries pool)) entry)
479      (push entry (pool-entries-list pool))
480      (incf (pool-index pool))) ;; double index increase; 'double' takes 2 slots
481    (constant-index entry)))
482
483(defun pool-add-name/type (pool name type)
484  "Returns the index of the constant-pool item denoting
485the name/type identifier."
486  (let ((entry (gethash (cons name type) (pool-entries pool)))
487        (internal-type (if (listp type)
488                           (apply #'descriptor type)
489                           (internal-field-ref type))))
490    (unless entry
491      (let ((n (pool-add-utf8 pool name))
492            (i-t (pool-add-utf8 pool internal-type)))
493        (setf entry (make-constant-name/type (incf (pool-index pool)) n i-t)
494              (gethash (cons name type) (pool-entries pool)) entry))
495      (push entry (pool-entries-list pool)))
496    (constant-index entry)))
497
498(defun pool-add-utf8 (pool utf8-as-string)
499  "Returns the index of the textual value that will be stored in the
500class file as UTF-8 encoded data."
501  (let ((entry (gethash (cons 11 utf8-as-string) ;; 11 == utf8
502                        (pool-entries pool))))
503    (unless entry
504      (setf entry (make-constant-utf8 (incf (pool-index pool)) utf8-as-string)
505            (gethash (cons 11 utf8-as-string) (pool-entries pool)) entry)
506      (push entry (pool-entries-list pool)))
507    (constant-index entry)))
508
509(defstruct (class-file (:constructor
510                        make-class-file (class superclass access-flags)))
511  "Holds the components of a class file."
512  (constants (make-pool))
513  access-flags
514  class
515  superclass
516  interfaces
517  fields
518  methods
519  attributes)
520
521(defun make-class-interface-file (class)
522  "Create the components of a class file representing a public Java
523interface."
524  (make-class-file class +java-object+ '(:public :abstract :interface)))
525
526(defun class-add-field (class field)
527  "Adds a `field' created by `make-field'."
528  (push field (class-file-fields class)))
529
530(defun class-field (class name)
531  "Finds a field by name." ;; ### strictly speaking, a field is uniquely
532  ;; identified by its name and type, not by the name alone.
533  (find name (class-file-fields class)
534        :test #'string= :key #'field-name))
535
536(defun class-add-method (class method)
537  "Adds a `method' to `class'; the method must have been created using
538`make-jvm-method'."
539  (push method (class-file-methods class)))
540
541(defun class-methods-by-name (class name)
542  "Returns all methods which have `name'."
543  (remove (map-method-name name) (class-file-methods class)
544          :test-not #'string= :key #'method-name))
545
546(defun class-method (class name return &rest args)
547  "Return the method which is (uniquely) identified by its name AND descriptor."
548  (let ((return-and-args (cons return args))
549        (name (map-method-name name)))
550    (find-if #'(lambda (c)
551                 (and (string= (method-name c) name)
552                      (equal (method-descriptor c) return-and-args)))
553             (class-file-methods class))))
554
555(defun class-add-attribute (class attribute)
556  "Adds `attribute' to the class; attributes must be instances of
557structure classes which include the `attribute' structure class."
558  (push attribute (class-file-attributes class)))
559
560(defun class-add-superinterface (class interface)
561  "Adds the java-class-name contained in `interface' as a superinterface of the `class'.
562
563For a class that represents an object, the requirements in `interface'
564must then be implemented in the class.  For a class that represents an
565interface, the `interface' imposes additional requirements to the
566classes which implement this class."
567  (push interface (class-file-interfaces class)))
568
569(defun class-attribute (class name)
570  "Returns the attribute which is named `name'."
571  (find name (class-file-attributes class)
572        :test #'string= :key #'attribute-name))
573
574(defun finalize-interfaces (class)
575  "Finalize the interfaces for `class'.
576
577Interface finalization first ensures that all the classes referenced
578by the interfaces members exist in the pool.  Then, it destructively
579modfies the interfaces members with a list of the references to the
580corresponding pool indices."
581  (let ((interface-refs nil))
582    (dolist (interface (class-file-interfaces class))
583      (push 
584       (pool-add-class (class-file-constants class)
585                       interface)
586       interface-refs))
587    (setf (class-file-interfaces class) interface-refs)))
588
589(defun finalize-class-file (class)
590  "Transforms the representation of the class-file from one
591which allows easy modification to one which works best for serialization.
592
593The class can't be modified after finalization."
594
595  ;; constant pool contains constants finalized on addition;
596  ;; no need for additional finalization
597
598  (setf (class-file-access-flags class)
599        (map-flags (class-file-access-flags class)))
600  (setf (class-file-superclass class)
601        (pool-add-class (class-file-constants class)
602                        (class-file-superclass class))
603        (class-file-class class)
604        (pool-add-class (class-file-constants class)
605                        (class-file-class class)))
606  (finalize-interfaces class)
607  (dolist (field (class-file-fields class))
608    (finalize-field field class))
609  (dolist (method (class-file-methods class))
610    (finalize-method method class))
611  ;; top-level attributes (no parent attributes to refer to)
612  (finalize-attributes (class-file-attributes class) nil class))
613
614
615(declaim (inline write-u1 write-u2 write-u4 write-s4))
616(defun write-u1 (n stream)
617  (declare (optimize speed))
618  (declare (type (unsigned-byte 8) n))
619  (declare (type stream stream))
620  (write-8-bits n stream))
621
622(defknown write-u2 (t t) t)
623(defun write-u2 (n stream)
624  (declare (optimize speed))
625  (declare (type (unsigned-byte 16) n))
626  (declare (type stream stream))
627  (write-8-bits (logand (ash n -8) #xFF) stream)
628  (write-8-bits (logand n #xFF) stream))
629
630(defknown write-u4 (integer stream) t)
631(defun write-u4 (n stream)
632  (declare (optimize speed))
633  (declare (type (unsigned-byte 32) n))
634  (write-u2 (logand (ash n -16) #xFFFF) stream)
635  (write-u2 (logand n #xFFFF) stream))
636
637(declaim (ftype (function (t t) t) write-s4))
638(defun write-s4 (n stream)
639  (declare (optimize speed))
640  (cond ((minusp n)
641         (write-u4 (1+ (logxor (- n) #xFFFFFFFF)) stream))
642        (t
643         (write-u4 n stream))))
644
645(declaim (ftype (function (t t t) t) write-ascii))
646(defun write-ascii (string length stream)
647  (declare (type string string))
648  (declare (type (unsigned-byte 16) length))
649  (declare (type stream stream))
650  (write-u2 length stream)
651  (dotimes (i length)
652    (declare (type (unsigned-byte 16) i))
653    (write-8-bits (char-code (char string i)) stream)))
654
655
656(declaim (ftype (function (t t) t) write-utf8))
657(defun write-utf8 (string stream)
658  (declare (optimize speed))
659  (declare (type string string))
660  (declare (type stream stream))
661  (let ((length (length string))
662        (must-convert nil))
663    (declare (type fixnum length))
664    (dotimes (i length)
665      (declare (type fixnum i))
666      (unless (< 0 (char-code (char string i)) #x80)
667        (setf must-convert t)
668        (return)))
669    (if must-convert
670        (let ((octets (make-array (* length 2)
671                                  :element-type '(unsigned-byte 8)
672                                  :adjustable t
673                                  :fill-pointer 0)))
674          (declare (type (vector (unsigned-byte 8)) octets))
675          (dotimes (i length)
676            (declare (type fixnum i))
677            (let* ((c (char string i))
678                   (n (char-code c)))
679              (cond ((zerop n)
680                     (vector-push-extend #xC0 octets)
681                     (vector-push-extend #x80 octets))
682                    ((< 0 n #x80)
683                     (vector-push-extend n octets))
684                    (t
685                     (let ((char-octets (char-to-utf8 c)))
686                       (dotimes (j (length char-octets))
687                         (declare (type fixnum j))
688                         (vector-push-extend (svref char-octets j) octets)))))))
689          (write-u2 (length octets) stream)
690          (dotimes (i (length octets))
691            (declare (type fixnum i))
692            (write-8-bits (aref octets i) stream)))
693        (write-ascii string length stream))))
694
695
696(defun write-class-file (class stream)
697  "Serializes `class' to `stream', after it has been finalized."
698
699  ;; header
700  (write-u4 #xCAFEBABE stream)
701  (write-u2 0 stream)
702  (write-u2 49 stream)  ;; our <clinit> methods use class literals
703  ;; which require a high enough class file format
704  ;; we used to have 45, but the LDC instruction doesn't support
705  ;; class literals in that version... (49 == Java 1.5)
706
707   ;; constants pool
708  (write-constants (class-file-constants class) stream)
709  ;; flags
710  (write-u2  (class-file-access-flags class) stream)
711
712  ;; class name
713  (write-u2 (class-file-class class) stream)
714
715  ;; superclass
716  (write-u2 (class-file-superclass class) stream)
717
718  ;; interfaces
719  (if (class-file-interfaces class)
720      (progn
721        (write-u2 (length (class-file-interfaces class)) stream)
722        (dolist (interface-ref (class-file-interfaces class))
723          (write-u2 interface-ref stream)))
724      (write-u2 0 stream))
725
726  ;; fields
727  (write-u2 (length (class-file-fields class)) stream)
728  (dolist (field (class-file-fields class))
729    (write-field field stream))
730
731  ;; methods
732  (write-u2 (length (class-file-methods class)) stream)
733  (dolist (method (class-file-methods class))
734    (write-method method stream))
735
736  ;; attributes
737  (write-attributes (class-file-attributes class) stream))
738
739
740(defvar *jvm-class-debug-pool* nil
741  "When bound to a non-NIL value, enables output to *standard-output*
742to allow debugging output of the constant section of the class file.")
743
744(defun write-constants (constants stream)
745  "Writes the constant section given in `constants' to the class file `stream'."
746  (let ((pool-index 0))
747    (write-u2 (1+ (pool-index constants)) stream)
748    (when *jvm-class-debug-pool*
749      (sys::%format t "pool count ~A~%" (pool-index constants)))
750    (dolist (entry (reverse (pool-entries-list constants)))
751      (incf pool-index)
752      (let ((tag (constant-tag entry)))
753        (when *jvm-class-debug-pool*
754          (print-constant entry t))
755        (write-u1 tag stream)
756        (case tag
757          (1                            ; UTF8
758           (write-utf8 (constant-utf8-value entry) stream))
759          ((3 4)                        ; float int
760           (write-u4 (constant-float/int-value entry) stream))
761          ((5 6)                        ; long double
762           (write-u4 (logand (ash (constant-double/long-value entry) -32)
763                             #xFFFFffff) stream)
764           (write-u4 (logand (constant-double/long-value entry) #xFFFFffff)
765                     stream))
766          ((9 10 11)           ; fieldref methodref InterfaceMethodref
767           (write-u2 (constant-member-ref-class-index entry) stream)
768           (write-u2 (constant-member-ref-name/type-index entry) stream))
769          (12                           ; nameAndType
770           (write-u2 (constant-name/type-name-index entry) stream)
771           (write-u2 (constant-name/type-descriptor-index entry) stream))
772          (7                            ; class
773           (write-u2 (constant-class-name-index entry) stream))
774          (8                            ; string
775           (write-u2 (constant-string-value-index entry) stream))
776          (t
777           (error "write-constant-pool-entry unhandled tag ~D~%" tag)))))))
778
779
780(defun print-constant (entry stream)
781  "Debugging helper to print the content of a constant-pool entry."
782  (let ((tag (constant-tag entry))
783        (index (constant-index entry)))
784    (sys::%format stream "pool element ~a, tag ~a, " index tag)
785    (case tag
786      (1     (sys::%format t "utf8: ~a~%" (constant-utf8-value entry)))
787      ((3 4) (sys::%format t "f/i: ~a~%" (constant-float/int-value entry)))
788      ((5 6) (sys::%format t "d/l: ~a~%" (constant-double/long-value entry)))
789      ((9 10 11) (sys::%format t "ref: ~a,~a~%"
790                               (constant-member-ref-class-index entry)
791                               (constant-member-ref-name/type-index entry)))
792      (12 (sys::%format t "n/t: ~a,~a~%"
793                        (constant-name/type-name-index entry)
794                        (constant-name/type-descriptor-index entry)))
795      (7 (sys::%format t "cls: ~a~%" (constant-class-name-index entry)))
796      (8 (sys::%format t "str: ~a~%" (constant-string-value-index entry))))))
797
798
799#|
800
801ABCL doesn't use interfaces, so don't implement it here at this time
802
803(defstruct interface)
804
805|#
806
807
808(defparameter +access-flags-map+
809  '((:public       #x0001)
810    (:private      #x0002)
811    (:protected    #x0004)
812    (:static       #x0008)
813    (:final        #x0010)
814    (:volatile     #x0040)
815    (:synchronized #x0020)
816    (:transient    #x0080)
817    (:native       #x0100)
818    (:interface    #x0200)
819    (:abstract     #x0400)
820    (:strict       #x0800))
821  "List of keyword symbols used for human readable representation of (access)
822flags and their binary values.")
823
824(defun map-flags (flags)
825  "Calculates the bitmap of the flags from a list of symbols."
826  (reduce #'(lambda (y x)
827              (logior (or (when (member (car x) flags)
828                            (second x))
829                          0) y))
830          +access-flags-map+
831          :initial-value 0))
832
833(defstruct (field (:constructor %make-field))
834  "Holds information on the properties of fields in the class(-file)."
835  access-flags
836  name
837  descriptor
838  attributes)
839
840(defun make-field (name type &key (flags '(:public)))
841  "Creates a field for addition to a class file."
842  (%make-field :access-flags flags
843               :name name
844               :descriptor type))
845
846(defun field-add-attribute (field attribute)
847  "Adds an attribute to a field."
848  (push attribute (field-attributes field)))
849
850(defun field-attribute (field name)
851  "Retrieves an attribute named `name' of `field'.
852
853Returns NIL if the attribute isn't found."
854  (find name (field-attributes field)
855        :test #'string= :key #'attribute-name))
856
857(defun finalize-field (field class)
858  "Prepares `field' for serialization."
859  (let ((pool (class-file-constants class)))
860    (setf (field-access-flags field)
861          (map-flags (field-access-flags field))
862          (field-descriptor field)
863          (pool-add-utf8 pool (internal-field-ref (field-descriptor field)))
864          (field-name field)
865          (pool-add-utf8 pool (field-name field))))
866  (finalize-attributes (field-attributes field) nil class))
867
868(defun write-field (field stream)
869  "Writes classfile representation of `field' to `stream'."
870  (write-u2 (field-access-flags field) stream)
871  (write-u2 (field-name field) stream)
872  (write-u2 (field-descriptor field) stream)
873  (write-attributes (field-attributes field) stream))
874
875
876(defstruct (jvm-method (:constructor %make-jvm-method)
877           (:conc-name method-))
878  "Holds information on the properties of methods in the class(-file)."
879  access-flags
880  name
881  descriptor
882  attributes)
883
884
885(defun map-method-name (name)
886  "Methods should be identified by strings containing their names, or,
887be one of two keyword identifiers to identify special methods:
888
889 * :static-initializer
890 * :constructor
891"
892  (cond
893    ((eq name :static-initializer)
894     "<clinit>")
895    ((eq name :constructor)
896     "<init>")
897    (t name)))
898
899(defun make-jvm-method (name return args &key (flags '(:public)))
900  "Creates a method for addition to a class file."
901  (%make-jvm-method :descriptor (cons return args)
902        :access-flags flags
903        :name (map-method-name name)))
904
905(defun method-add-attribute (method attribute)
906  "Add `attribute' to the list of attributes of `method',
907returning `attribute'."
908  (push attribute (method-attributes method))
909  attribute)
910
911(defun method-add-code (method &optional (optimize t))
912  "Creates an (empty) 'Code' attribute for the method,
913returning the created attribute."
914  (method-add-attribute
915   method
916   (make-code-attribute (+ (length (cdr (method-descriptor method)))
917                           (if (member :static (method-access-flags method))
918                               0 1)) ;; 1 == implicit 'this'
919      optimize)))
920
921(defun method-ensure-code (method &optional (optimize t))
922  "Ensures the existence of a 'Code' attribute for the method,
923returning the attribute."
924  (let ((code (method-attribute method "Code")))
925    (if (null code)
926        (method-add-code method optimize)
927        code)))
928
929(defun method-attribute (method name)
930  "Returns the first attribute of `method' with `name'."
931  (find name (method-attributes method)
932        :test #'string= :key #'attribute-name))
933
934
935(defun finalize-method (method class)
936  "Prepares `method' for serialization."
937  (let ((pool (class-file-constants class)))
938    (setf (method-access-flags method)
939          (map-flags (method-access-flags method))
940          (method-descriptor method)
941          (pool-add-utf8 pool (apply #'descriptor (method-descriptor method)))
942          (method-name method)
943          (pool-add-utf8 pool (method-name method))))
944  (finalize-attributes (method-attributes method) nil class))
945
946
947(defun write-method (method stream)
948  "Write class file representation of `method' to `stream'."
949  (write-u2 (method-access-flags method) stream)
950  (write-u2 (method-name method) stream)
951  ;;(sys::%format t "method-name: ~a~%" (method-name method))
952  (write-u2 (method-descriptor method) stream)
953  (write-attributes (method-attributes method) stream))
954
955(defstruct attribute
956  "Parent attribute structure to be included into other attributes, mainly
957to define common fields.
958
959Having common fields allows common driver code for
960finalizing and serializing attributes."
961  name
962
963  ;; not in the class file:
964  finalizer  ;; function of 3 arguments: the attribute, parent and class-file
965  writer     ;; function of 2 arguments: the attribute and the output stream
966  )
967
968(defun finalize-attributes (attributes att class)
969  "Prepare `attributes' (a list) of attribute `att' list for serialization."
970  (dolist (attribute attributes)
971    ;; assure header: make sure 'name' is in the pool
972    (setf (attribute-name attribute)
973          (pool-add-utf8 (class-file-constants class)
974                         (attribute-name attribute)))
975    ;; we're saving "root" attributes: attributes which have no parent
976    (funcall (attribute-finalizer attribute) attribute att class)))
977
978(defun write-attributes (attributes stream)
979  "Writes the `attributes' to `stream'."
980  (write-u2 (length attributes) stream)
981  (dolist (attribute attributes)
982    (write-u2 (attribute-name attribute) stream)
983    ;; set up a bulk catcher for (UNSIGNED-BYTE 8)
984    ;; since we need to know the attribute length (excluding the header)
985    (let ((local-stream (sys::%make-byte-array-output-stream)))
986      (funcall (attribute-writer attribute) attribute local-stream)
987      (let ((array (sys::%get-output-stream-array local-stream)))
988        (write-u4 (length array) stream)
989        (write-sequence array stream)))))
990
991
992
993(defstruct (code-attribute (:conc-name code-)
994                           (:include attribute
995                                     (name "Code")
996                                     (finalizer #'finalize-code-attribute)
997                                     (writer #'write-code-attribute))
998                           (:constructor %make-code-attribute))
999  "The attribute containing the actual JVM byte code;
1000an attribute of a method."
1001  max-stack
1002  max-locals
1003  code
1004  exception-handlers
1005  attributes
1006
1007  ;; fields not in the class file start here
1008
1009  ;; labels contains offsets into the code array after it's finalized
1010  labels ;; an alist
1011  optimize
1012  (current-local 0)) ;; used for handling nested WITH-CODE-TO-METHOD blocks
1013
1014
1015
1016(defun code-label-offset (code label)
1017  "Retrieves the `label' offset within a `code' attribute after the
1018attribute has been finalized."
1019  (cdr (assoc label (code-labels code))))
1020
1021(defun (setf code-label-offset) (offset code label)
1022  "Sets the `label' offset within a `code' attribute after the attribute
1023has been finalized."
1024  (setf (code-labels code)
1025        (acons label offset (code-labels code))))
1026
1027(defun finalize-code-attribute (code parent class)
1028  "Prepares the `code' attribute for serialization, within method `parent'."
1029  (let* ((handlers (code-exception-handlers code))
1030         (c (finalize-code
1031                     (code-code code)
1032                     (nconc (mapcar #'exception-start-pc handlers)
1033                            (mapcar #'exception-end-pc handlers)
1034                            (mapcar #'exception-handler-pc handlers))
1035                     (code-optimize code))))
1036    (invoke-callbacks :code-finalized class parent
1037                      (coerce c 'list) handlers)
1038    (unless (code-max-stack code)
1039      (setf (code-max-stack code)
1040            (analyze-stack c (mapcar #'exception-handler-pc handlers))))
1041    (unless (code-max-locals code)
1042      (setf (code-max-locals code)
1043            (analyze-locals code)))
1044    (multiple-value-bind
1045          (c labels)
1046        (code-bytes c)
1047      (setf (code-code code) c
1048            (code-labels code) labels)))
1049
1050  (setf (code-exception-handlers code)
1051        (remove-if #'(lambda (h)
1052                       (eql (code-label-offset code (exception-start-pc h))
1053                            (code-label-offset code (exception-end-pc h))))
1054                   (code-exception-handlers code)))
1055
1056  (dolist (exception (code-exception-handlers code))
1057    (setf (exception-start-pc exception)
1058          (code-label-offset code (exception-start-pc exception))
1059          (exception-end-pc exception)
1060          (code-label-offset code (exception-end-pc exception))
1061          (exception-handler-pc exception)
1062          (code-label-offset code (exception-handler-pc exception))
1063          (exception-catch-type exception)
1064          (if (null (exception-catch-type exception))
1065              0  ;; generic 'catch all' class index number
1066              (pool-add-class (class-file-constants class)
1067                              (exception-catch-type exception)))))
1068
1069  (finalize-attributes (code-attributes code) code class))
1070
1071(defun write-code-attribute (code stream)
1072  "Writes the attribute `code' to `stream'."
1073  ;;(sys::%format t "max-stack: ~a~%" (code-max-stack code))
1074  (write-u2 (code-max-stack code) stream)
1075  ;;(sys::%format t "max-locals: ~a~%" (code-max-locals code))
1076  (write-u2 (code-max-locals code) stream)
1077  (let ((code-array (code-code code)))
1078    ;;(sys::%format t "length: ~a~%" (length code-array))
1079    (write-u4 (length code-array) stream)
1080    (dotimes (i (length code-array))
1081      (write-u1 (svref code-array i) stream)))
1082
1083  (write-u2 (length (code-exception-handlers code)) stream)
1084  (dolist (exception (reverse (code-exception-handlers code)))
1085    ;;(sys::%format t "start-pc: ~a~%" (exception-start-pc exception))
1086    (write-u2 (exception-start-pc exception) stream)
1087    ;;(sys::%format t "end-pc: ~a~%" (exception-end-pc exception))
1088    (write-u2 (exception-end-pc exception) stream)
1089    ;;(sys::%format t "handler-pc: ~a~%" (exception-handler-pc exception))
1090    (write-u2 (exception-handler-pc exception) stream)
1091    (write-u2 (exception-catch-type exception) stream))
1092
1093  (write-attributes (code-attributes code) stream))
1094
1095(defun make-code-attribute (arg-count &optional optimize)
1096  "Creates an empty 'Code' attribute for a method which takes
1097`arg-count` parameters, including the implicit `this` parameter."
1098  (%make-code-attribute :max-locals arg-count :optimize optimize))
1099
1100(defun code-add-attribute (code attribute)
1101  "Adds `attribute' to `code', returning `attribute'."
1102  (push attribute (code-attributes code))
1103  attribute)
1104
1105(defun code-attribute (code name)
1106  "Returns an attribute of `code' identified by `name'."
1107  (find name (code-attributes code)
1108        :test #'string= :key #'attribute-name))
1109
1110
1111(defun code-add-exception-handler (code start end handler type)
1112  "Adds an exception handler to `code' protecting the region from
1113labels `start' to `end' (inclusive) from exception `type' - where
1114a value of NIL indicates all types. Upon an exception of the given
1115type, control is transferred to label `handler'."
1116  (push (make-exception :start-pc start
1117                        :end-pc end
1118                        :handler-pc handler
1119                        :catch-type type)
1120        (code-exception-handlers code)))
1121
1122(defstruct exception
1123  "Exception handler information.
1124
1125After finalization, the fields contain offsets instead of labels."
1126  start-pc    ;; label target
1127  end-pc      ;; label target
1128  handler-pc  ;; label target
1129  catch-type  ;; a string for a specific type, or NIL for all
1130  )
1131
1132
1133(defstruct (constant-value-attribute (:conc-name constant-value-)
1134                                     (:include attribute
1135                                               (name "ConstantValue")
1136                                               ;; finalizer
1137                                               ;; writer
1138                                               ))
1139  "An attribute of a field of primitive type.
1140
1141"
1142  ;;; ### TODO
1143  )
1144
1145
1146(defstruct (checked-exceptions-attribute
1147             (:conc-name checked-)
1148             (:include attribute
1149                       (name "Exceptions")
1150                       (finalizer #'finalize-checked-exceptions)
1151                       (writer #'write-checked-exceptions)))
1152  "An attribute of `code-attribute', "
1153  table ;; a list of checked classes corresponding to Java's 'throws'
1154)
1155
1156(defun finalize-checked-exceptions (checked-exceptions code class)
1157  (declare (ignorable code class))
1158
1159  "Prepare `checked-exceptions' for serialization."
1160  (setf (checked-table checked-exceptions)
1161        (mapcar #'(lambda (exception)
1162                    (pool-add-class (class-file-constants class)
1163                                    exception))
1164                (checked-table checked-exceptions))))
1165
1166(defun write-checked-exceptions (checked-exceptions stream)
1167  "Write `checked-exceptions' to `stream' in class file representation."
1168  (write-u2 (length (checked-table checked-exceptions)) stream)
1169  (dolist (exception (reverse (checked-table checked-exceptions)))
1170    (write-u2 exception stream)))
1171
1172;; Can't be used yet: serialization missing
1173(defstruct (deprecated-attribute (:include attribute
1174                                           (name "Deprecated")
1175                                           (finalizer (constantly nil))
1176                                           (writer (constantly nil))))
1177  ;; finalizer and writer need to do nothing: Deprecated attributes are empty
1178  "An attribute of a class file, field or method, indicating the element
1179to which it has been attached has been superseded.")
1180
1181(defvar *current-code-attribute* nil)
1182(defvar *method*)
1183
1184(defun save-code-specials (code)
1185  (setf (code-code code) *code*
1186        (code-max-locals code) *registers-allocated*
1187        (code-current-local code) *register*))
1188
1189(defun restore-code-specials (code)
1190  (setf *code* (code-code code)
1191        *registers-allocated* (code-max-locals code)
1192        *register* (code-current-local code)))
1193
1194(defmacro with-code-to-method ((class-file method)
1195                               &body body)
1196  (let ((m (gensym))
1197        (c (gensym)))
1198    `(progn
1199       (when *current-code-attribute*
1200         (save-code-specials *current-code-attribute*))
1201       (unwind-protect
1202           (let* ((,m ,method)
1203                  (*method* ,m)
1204                  (,c (method-ensure-code ,method))
1205                  (*pool* (class-file-constants ,class-file))
1206                  (*code* (code-code ,c))
1207                  (*registers-allocated* (code-max-locals ,c))
1208                  (*register* (code-current-local ,c))
1209                  (*current-code-attribute* ,c))
1210             (unwind-protect
1211                 ,@body
1212               ;; in case of a RETURN-FROM or GO, save the current state
1213               (setf (code-code ,c) *code*
1214                     (code-current-local ,c) *register*
1215                     (code-max-locals ,c) *registers-allocated*)))
1216         ;; using the same line of reasoning, restore the outer-scope state
1217         (when *current-code-attribute*
1218           (restore-code-specials *current-code-attribute*))))))
1219
1220
1221(defstruct (source-file-attribute (:conc-name source-)
1222                                  (:include attribute
1223                                            (name "SourceFile")
1224                                            (finalizer #'finalize-source-file)
1225                                            (writer #'write-source-file)))
1226  "An attribute of the class file indicating which source file
1227it was compiled from."
1228  filename)
1229
1230(defun finalize-source-file (source-file code class)
1231  (declare (ignorable code class))
1232  (setf (source-filename source-file)
1233        (pool-add-utf8 (class-file-constants class)
1234                       (source-filename source-file))))
1235
1236(defun write-source-file (source-file stream)
1237  (write-u2 (source-filename source-file) stream))
1238
1239
1240(defstruct (synthetic-attribute (:include attribute
1241                                          (name "Synthetic")
1242                                          (finalizer (constantly nil))
1243                                          (writer (constantly nil))))
1244  ;; finalizer and writer need to do nothing: Synthetic attributes are empty
1245  "An attribute of a class file, field or method to mark that it wasn't
1246included in the sources - but was generated artificially.")
1247
1248
1249(defstruct (line-numbers-attribute
1250             (:conc-name line-numbers-)
1251             (:include attribute
1252                       (name "LineNumberTable")
1253                       (finalizer #'finalize-line-numbers)
1254                       (writer #'write-line-numbers)))
1255  "An attribute of `code-attribute', containing a mapping of offsets
1256within the code section to the line numbers in the source file."
1257  table ;; a list of line-number structures, in reverse order
1258  )
1259
1260(defstruct line-number
1261  start-pc  ;; a label, before finalization, or 0 for "start of function"
1262  line)
1263
1264(defun finalize-line-numbers (line-numbers code class)
1265  (declare (ignorable code class))
1266  (dolist (line-number (line-numbers-table line-numbers))
1267    (unless (zerop (line-number-start-pc line-number))
1268      (setf (line-number-start-pc line-number)
1269            (code-label-offset code (line-number-start-pc line-number))))))
1270
1271(defun write-line-numbers (line-numbers stream)
1272  (write-u2 (length (line-numbers-table line-numbers)) stream)
1273  (dolist (line-number (reverse (line-numbers-table line-numbers)))
1274    (write-u2 (line-number-start-pc line-number) stream)
1275    (write-u2 (line-number-line line-number) stream)))
1276
1277(defun line-numbers-add-line (line-numbers start-pc line)
1278  (push (make-line-number :start-pc start-pc :line line)
1279        (line-numbers-table line-numbers)))
1280
1281(defstruct (local-variables-attribute
1282             (:conc-name local-var-)
1283             (:include attribute
1284                       (name "LocalVariableTable")
1285                       (finalizer #'finalize-local-variables)
1286                       (writer #'write-local-variables)))
1287  "An attribute of the `code-attribute', containing a table of local variable
1288names, their type and their scope of validity."
1289  table ;; a list of local-variable structures, in reverse order
1290  )
1291
1292(defstruct (local-variable (:conc-name local-))
1293  start-pc  ;; a label, before finalization
1294  length    ;; a label (at the ending position) before finalization
1295  name
1296  descriptor
1297  index ;; The index of the variable inside the block of locals
1298  )
1299
1300(defun finalize-local-variables (local-variables code class)
1301  (dolist (local-variable (local-var-table local-variables))
1302    (setf (local-start-pc local-variable)
1303          (code-label-offset code (local-start-pc local-variable))
1304          (local-length local-variable)
1305          ;; calculate 'length' from the distance between 2 labels
1306          (- (code-label-offset code (local-length local-variable))
1307             (local-start-pc local-variable))
1308          (local-name local-variable)
1309          (pool-add-utf8 (class-file-constants class)
1310                         (local-name local-variable))
1311          (local-descriptor local-variable)
1312          (pool-add-utf8 (class-file-constants class)
1313                         (local-descriptor local-variable)))))
1314
1315(defun write-local-variables (local-variables stream)
1316  (write-u2 (length (local-var-table local-variables)) stream)
1317  (dolist (local-variable (reverse (local-var-table local-variables)))
1318    (write-u2 (local-start-pc local-variable) stream)
1319    (write-u2 (local-length local-variable) stream)
1320    (write-u2 (local-name local-variable) stream)
1321    (write-u2 (local-descriptor local-variable) stream)
1322    (write-u2 (local-index local-variable) stream)))
1323
1324#|
1325
1326;; this is the minimal sequence we need to support:
1327
1328;;  create a class file structure
1329;;  add methods
1330;;  add code to the methods, switching from one method to the other
1331;;  finalize the methods, one by one
1332;;  write the class file
1333
1334to support the sequence above, we probably need to
1335be able to
1336
1337- find methods by signature
1338- find the method's code attribute
1339- add code to the code attribute
1340- finalize the code attribute contents (blocking it for further addition)
1341-
1342
1343
1344|#
1345
Note: See TracBrowser for help on using the repository browser.