source: trunk/abcl/src/org/armedbear/lisp/jvm-class-file.lisp @ 13511

Last change on this file since 13511 was 13511, checked in by ehuelsmann, 10 years ago

Re #116: while working to fix the issue, at least tell the user we're
unable to generate a conforming class file.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 52.1 KB
Line 
1;;; jvm-class-file.lisp
2;;;
3;;; Copyright (C) 2010 Erik Huelsmann
4;;; $Id: jvm-class-file.lisp 13511 2011-08-19 15:42:38Z 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 3 stream)
702  (write-u2 45 stream)
703
704   ;; constants pool
705  (write-constants (class-file-constants class) stream)
706  ;; flags
707  (write-u2  (class-file-access-flags class) stream)
708
709  ;; class name
710  (write-u2 (class-file-class class) stream)
711
712  ;; superclass
713  (write-u2 (class-file-superclass class) stream)
714
715  ;; interfaces
716  (if (class-file-interfaces class)
717      (progn 
718        (write-u2 (length (class-file-interfaces class)) stream)
719        (dolist (interface-ref (class-file-interfaces class))
720          (write-u2 interface-ref stream)))
721      (write-u2 0 stream))
722
723  ;; fields
724  (write-u2 (length (class-file-fields class)) stream)
725  (dolist (field (class-file-fields class))
726    (write-field field stream))
727
728  ;; methods
729  (write-u2 (length (class-file-methods class)) stream)
730  (dolist (method (class-file-methods class))
731    (write-method method stream))
732
733  ;; attributes
734  (write-attributes (class-file-attributes class) stream))
735
736
737(defvar *jvm-class-debug-pool* nil
738  "When bound to a non-NIL value, enables output to *standard-output*
739to allow debugging output of the constant section of the class file.")
740
741(defun write-constants (constants stream)
742  "Writes the constant section given in `constants' to the class file `stream'."
743  (let ((pool-index 0))
744    (write-u2 (1+ (pool-index constants)) stream)
745    (when *jvm-class-debug-pool*
746      (sys::%format t "pool count ~A~%" (pool-index constants)))
747    (dolist (entry (reverse (pool-entries-list constants)))
748      (incf pool-index)
749      (let ((tag (constant-tag entry)))
750        (when *jvm-class-debug-pool*
751          (print-constant entry t))
752        (write-u1 tag stream)
753        (case tag
754          (1                            ; UTF8
755           (write-utf8 (constant-utf8-value entry) stream))
756          ((3 4)                        ; float int
757           (write-u4 (constant-float/int-value entry) stream))
758          ((5 6)                        ; long double
759           (write-u4 (logand (ash (constant-double/long-value entry) -32)
760                             #xFFFFffff) stream)
761           (write-u4 (logand (constant-double/long-value entry) #xFFFFffff)
762                     stream))
763          ((9 10 11)           ; fieldref methodref InterfaceMethodref
764           (write-u2 (constant-member-ref-class-index entry) stream)
765           (write-u2 (constant-member-ref-name/type-index entry) stream))
766          (12                           ; nameAndType
767           (write-u2 (constant-name/type-name-index entry) stream)
768           (write-u2 (constant-name/type-descriptor-index entry) stream))
769          (7                            ; class
770           (write-u2 (constant-class-name-index entry) stream))
771          (8                            ; string
772           (write-u2 (constant-string-value-index entry) stream))
773          (t
774           (error "write-constant-pool-entry unhandled tag ~D~%" tag)))))))
775
776
777(defun print-constant (entry stream)
778  "Debugging helper to print the content of a constant-pool entry."
779  (let ((tag (constant-tag entry))
780        (index (constant-index entry)))
781    (sys::%format stream "pool element ~a, tag ~a, " index tag)
782    (case tag
783      (1     (sys::%format t "utf8: ~a~%" (constant-utf8-value entry)))
784      ((3 4) (sys::%format t "f/i: ~a~%" (constant-float/int-value entry)))
785      ((5 6) (sys::%format t "d/l: ~a~%" (constant-double/long-value entry)))
786      ((9 10 11) (sys::%format t "ref: ~a,~a~%"
787                               (constant-member-ref-class-index entry)
788                               (constant-member-ref-name/type-index entry)))
789      (12 (sys::%format t "n/t: ~a,~a~%"
790                        (constant-name/type-name-index entry)
791                        (constant-name/type-descriptor-index entry)))
792      (7 (sys::%format t "cls: ~a~%" (constant-class-name-index entry)))
793      (8 (sys::%format t "str: ~a~%" (constant-string-value-index entry))))))
794
795
796#|
797
798ABCL doesn't use interfaces, so don't implement it here at this time
799
800(defstruct interface)
801
802|#
803
804
805(defparameter +access-flags-map+
806  '((:public       #x0001)
807    (:private      #x0002)
808    (:protected    #x0004)
809    (:static       #x0008)
810    (:final        #x0010)
811    (:volatile     #x0040)
812    (:synchronized #x0020)
813    (:transient    #x0080)
814    (:native       #x0100)
815    (:interface    #x0200)
816    (:abstract     #x0400)
817    (:strict       #x0800))
818  "List of keyword symbols used for human readable representation of (access)
819flags and their binary values.")
820
821(defun map-flags (flags)
822  "Calculates the bitmap of the flags from a list of symbols."
823  (reduce #'(lambda (y x)
824              (logior (or (when (member (car x) flags)
825                            (second x))
826                          0) y))
827          +access-flags-map+
828          :initial-value 0))
829
830(defstruct (field (:constructor %make-field))
831  "Holds information on the properties of fields in the class(-file)."
832  access-flags
833  name
834  descriptor
835  attributes)
836
837(defun make-field (name type &key (flags '(:public)))
838  "Creates a field for addition to a class file."
839  (%make-field :access-flags flags
840               :name name
841               :descriptor type))
842
843(defun field-add-attribute (field attribute)
844  "Adds an attribute to a field."
845  (push attribute (field-attributes field)))
846
847(defun field-attribute (field name)
848  "Retrieves an attribute named `name' of `field'.
849
850Returns NIL if the attribute isn't found."
851  (find name (field-attributes field)
852        :test #'string= :key #'attribute-name))
853
854(defun finalize-field (field class)
855  "Prepares `field' for serialization."
856  (let ((pool (class-file-constants class)))
857    (setf (field-access-flags field)
858          (map-flags (field-access-flags field))
859          (field-descriptor field)
860          (pool-add-utf8 pool (internal-field-ref (field-descriptor field)))
861          (field-name field)
862          (pool-add-utf8 pool (field-name field))))
863  (finalize-attributes (field-attributes field) nil class))
864
865(defun write-field (field stream)
866  "Writes classfile representation of `field' to `stream'."
867  (write-u2 (field-access-flags field) stream)
868  (write-u2 (field-name field) stream)
869  (write-u2 (field-descriptor field) stream)
870  (write-attributes (field-attributes field) stream))
871
872
873(defstruct (jvm-method (:constructor %make-jvm-method)
874           (:conc-name method-))
875  "Holds information on the properties of methods in the class(-file)."
876  access-flags
877  name
878  descriptor
879  attributes)
880
881
882(defun map-method-name (name)
883  "Methods should be identified by strings containing their names, or,
884be one of two keyword identifiers to identify special methods:
885
886 * :static-initializer
887 * :constructor
888"
889  (cond
890    ((eq name :static-initializer)
891     "<clinit>")
892    ((eq name :constructor)
893     "<init>")
894    (t name)))
895
896(defun make-jvm-method (name return args &key (flags '(:public)))
897  "Creates a method for addition to a class file."
898  (%make-jvm-method :descriptor (cons return args)
899        :access-flags flags
900        :name (map-method-name name)))
901
902(defun method-add-attribute (method attribute)
903  "Add `attribute' to the list of attributes of `method',
904returning `attribute'."
905  (push attribute (method-attributes method))
906  attribute)
907
908(defun method-add-code (method &optional (optimize t))
909  "Creates an (empty) 'Code' attribute for the method,
910returning the created attribute."
911  (method-add-attribute
912   method
913   (make-code-attribute (+ (length (cdr (method-descriptor method)))
914                           (if (member :static (method-access-flags method))
915                               0 1)) ;; 1 == implicit 'this'
916      optimize)))
917
918(defun method-ensure-code (method &optional (optimize t))
919  "Ensures the existence of a 'Code' attribute for the method,
920returning the attribute."
921  (let ((code (method-attribute method "Code")))
922    (if (null code)
923        (method-add-code method optimize)
924        code)))
925
926(defun method-attribute (method name)
927  "Returns the first attribute of `method' with `name'."
928  (find name (method-attributes method)
929        :test #'string= :key #'attribute-name))
930
931
932(defun finalize-method (method class)
933  "Prepares `method' for serialization."
934  (let ((pool (class-file-constants class)))
935    (setf (method-access-flags method)
936          (map-flags (method-access-flags method))
937          (method-descriptor method)
938          (pool-add-utf8 pool (apply #'descriptor (method-descriptor method)))
939          (method-name method)
940          (pool-add-utf8 pool (method-name method))))
941  (finalize-attributes (method-attributes method) nil class))
942
943
944(defun write-method (method stream)
945  "Write class file representation of `method' to `stream'."
946  (write-u2 (method-access-flags method) stream)
947  (write-u2 (method-name method) stream)
948  ;;(sys::%format t "method-name: ~a~%" (method-name method))
949  (write-u2 (method-descriptor method) stream)
950  (write-attributes (method-attributes method) stream))
951
952(defstruct attribute
953  "Parent attribute structure to be included into other attributes, mainly
954to define common fields.
955
956Having common fields allows common driver code for
957finalizing and serializing attributes."
958  name
959
960  ;; not in the class file:
961  finalizer  ;; function of 3 arguments: the attribute, parent and class-file
962  writer     ;; function of 2 arguments: the attribute and the output stream
963  )
964
965(defun finalize-attributes (attributes att class)
966  "Prepare `attributes' (a list) of attribute `att' list for serialization."
967  (dolist (attribute attributes)
968    ;; assure header: make sure 'name' is in the pool
969    (setf (attribute-name attribute)
970          (pool-add-utf8 (class-file-constants class)
971                         (attribute-name attribute)))
972    ;; we're saving "root" attributes: attributes which have no parent
973    (funcall (attribute-finalizer attribute) attribute att class)))
974
975(defun write-attributes (attributes stream)
976  "Writes the `attributes' to `stream'."
977  (write-u2 (length attributes) stream)
978  (dolist (attribute attributes)
979    (write-u2 (attribute-name attribute) stream)
980    ;; set up a bulk catcher for (UNSIGNED-BYTE 8)
981    ;; since we need to know the attribute length (excluding the header)
982    (let ((local-stream (sys::%make-byte-array-output-stream)))
983      (funcall (attribute-writer attribute) attribute local-stream)
984      (let ((array (sys::%get-output-stream-array local-stream)))
985        (write-u4 (length array) stream)
986        (write-sequence array stream)))))
987
988
989
990(defstruct (code-attribute (:conc-name code-)
991                           (:include attribute
992                                     (name "Code")
993                                     (finalizer #'finalize-code-attribute)
994                                     (writer #'write-code-attribute))
995                           (:constructor %make-code-attribute))
996  "The attribute containing the actual JVM byte code;
997an attribute of a method."
998  max-stack
999  max-locals
1000  code
1001  exception-handlers
1002  attributes
1003
1004  ;; fields not in the class file start here
1005
1006  ;; labels contains offsets into the code array after it's finalized
1007  labels ;; an alist
1008  optimize
1009  (current-local 0)) ;; used for handling nested WITH-CODE-TO-METHOD blocks
1010
1011
1012
1013(defun code-label-offset (code label)
1014  "Retrieves the `label' offset within a `code' attribute after the
1015attribute has been finalized."
1016  (cdr (assoc label (code-labels code))))
1017
1018(defun (setf code-label-offset) (offset code label)
1019  "Sets the `label' offset within a `code' attribute after the attribute
1020has been finalized."
1021  (setf (code-labels code)
1022        (acons label offset (code-labels code))))
1023
1024(defun finalize-code-attribute (code parent class)
1025  "Prepares the `code' attribute for serialization, within method `parent'."
1026  (let* ((handlers (code-exception-handlers code))
1027         (c (finalize-code
1028                     (code-code code)
1029                     (nconc (mapcar #'exception-start-pc handlers)
1030                            (mapcar #'exception-end-pc handlers)
1031                            (mapcar #'exception-handler-pc handlers))
1032                     (code-optimize code))))
1033    (invoke-callbacks :code-finalized class parent
1034                      (coerce c 'list) handlers)
1035    (unless (code-max-stack code)
1036      (setf (code-max-stack code)
1037            (analyze-stack c (mapcar #'exception-handler-pc handlers))))
1038    (unless (code-max-locals code)
1039      (setf (code-max-locals code)
1040            (analyze-locals code)))
1041    (multiple-value-bind
1042          (c labels)
1043        (code-bytes c)
1044      (setf (code-code code) c
1045            (code-labels code) labels)))
1046
1047  (setf (code-exception-handlers code)
1048        (remove-if #'(lambda (h)
1049                       (eql (code-label-offset code (exception-start-pc h))
1050                            (code-label-offset code (exception-end-pc h))))
1051                   (code-exception-handlers code)))
1052
1053  (dolist (exception (code-exception-handlers code))
1054    (setf (exception-start-pc exception)
1055          (code-label-offset code (exception-start-pc exception))
1056          (exception-end-pc exception)
1057          (code-label-offset code (exception-end-pc exception))
1058          (exception-handler-pc exception)
1059          (code-label-offset code (exception-handler-pc exception))
1060          (exception-catch-type exception)
1061          (if (null (exception-catch-type exception))
1062              0  ;; generic 'catch all' class index number
1063              (pool-add-class (class-file-constants class)
1064                              (exception-catch-type exception)))))
1065
1066  (finalize-attributes (code-attributes code) code class))
1067
1068(defun write-code-attribute (code stream)
1069  "Writes the attribute `code' to `stream'."
1070  ;;(sys::%format t "max-stack: ~a~%" (code-max-stack code))
1071  (write-u2 (code-max-stack code) stream)
1072  ;;(sys::%format t "max-locals: ~a~%" (code-max-locals code))
1073  (write-u2 (code-max-locals code) stream)
1074  (let ((code-array (code-code code)))
1075    ;;(sys::%format t "length: ~a~%" (length code-array))
1076    (write-u4 (length code-array) stream)
1077    (dotimes (i (length code-array))
1078      (write-u1 (svref code-array i) stream)))
1079
1080  (write-u2 (length (code-exception-handlers code)) stream)
1081  (dolist (exception (reverse (code-exception-handlers code)))
1082    ;;(sys::%format t "start-pc: ~a~%" (exception-start-pc exception))
1083    (write-u2 (exception-start-pc exception) stream)
1084    ;;(sys::%format t "end-pc: ~a~%" (exception-end-pc exception))
1085    (write-u2 (exception-end-pc exception) stream)
1086    ;;(sys::%format t "handler-pc: ~a~%" (exception-handler-pc exception))
1087    (write-u2 (exception-handler-pc exception) stream)
1088    (write-u2 (exception-catch-type exception) stream))
1089
1090  (write-attributes (code-attributes code) stream))
1091
1092(defun make-code-attribute (arg-count &optional optimize)
1093  "Creates an empty 'Code' attribute for a method which takes
1094`arg-count` parameters, including the implicit `this` parameter."
1095  (%make-code-attribute :max-locals arg-count :optimize optimize))
1096
1097(defun code-add-attribute (code attribute)
1098  "Adds `attribute' to `code', returning `attribute'."
1099  (push attribute (code-attributes code))
1100  attribute)
1101
1102(defun code-attribute (code name)
1103  "Returns an attribute of `code' identified by `name'."
1104  (find name (code-attributes code)
1105        :test #'string= :key #'attribute-name))
1106
1107
1108(defun code-add-exception-handler (code start end handler type)
1109  "Adds an exception handler to `code' protecting the region from
1110labels `start' to `end' (inclusive) from exception `type' - where
1111a value of NIL indicates all types. Upon an exception of the given
1112type, control is transferred to label `handler'."
1113  (push (make-exception :start-pc start
1114                        :end-pc end
1115                        :handler-pc handler
1116                        :catch-type type)
1117        (code-exception-handlers code)))
1118
1119(defstruct exception
1120  "Exception handler information.
1121
1122After finalization, the fields contain offsets instead of labels."
1123  start-pc    ;; label target
1124  end-pc      ;; label target
1125  handler-pc  ;; label target
1126  catch-type  ;; a string for a specific type, or NIL for all
1127  )
1128
1129
1130(defstruct (constant-value-attribute (:conc-name constant-value-)
1131                                     (:include attribute
1132                                               (name "ConstantValue")
1133                                               ;; finalizer
1134                                               ;; writer
1135                                               ))
1136  "An attribute of a field of primitive type.
1137
1138"
1139  ;;; ### TODO
1140  )
1141
1142
1143(defstruct (checked-exceptions-attribute
1144             (:conc-name checked-)
1145             (:include attribute
1146                       (name "Exceptions")
1147                       (finalizer #'finalize-checked-exceptions)
1148                       (writer #'write-checked-exceptions)))
1149  "An attribute of `code-attribute', "
1150  table ;; a list of checked classes corresponding to Java's 'throws'
1151)
1152
1153(defun finalize-checked-exceptions (checked-exceptions code class)
1154  (declare (ignorable code class))
1155
1156  "Prepare `checked-exceptions' for serialization."
1157  (setf (checked-table checked-exceptions)
1158        (mapcar #'(lambda (exception)
1159                    (pool-add-class (class-file-constants class)
1160                                    exception))
1161                (checked-table checked-exceptions))))
1162
1163(defun write-checked-exceptions (checked-exceptions stream)
1164  "Write `checked-exceptions' to `stream' in class file representation."
1165  (write-u2 (length (checked-table checked-exceptions)) stream)
1166  (dolist (exception (reverse (checked-table checked-exceptions)))
1167    (write-u2 exception stream)))
1168
1169;; Can't be used yet: serialization missing
1170(defstruct (deprecated-attribute (:include attribute
1171                                           (name "Deprecated")
1172                                           (finalizer (constantly nil))
1173                                           (writer (constantly nil))))
1174  ;; finalizer and writer need to do nothing: Deprecated attributes are empty
1175  "An attribute of a class file, field or method, indicating the element
1176to which it has been attached has been superseded.")
1177
1178(defvar *current-code-attribute* nil)
1179(defvar *method*)
1180
1181(defun save-code-specials (code)
1182  (setf (code-code code) *code*
1183        (code-max-locals code) *registers-allocated*
1184        (code-current-local code) *register*))
1185
1186(defun restore-code-specials (code)
1187  (setf *code* (code-code code)
1188        *registers-allocated* (code-max-locals code)
1189        *register* (code-current-local code)))
1190
1191(defmacro with-code-to-method ((class-file method)
1192                               &body body)
1193  (let ((m (gensym))
1194        (c (gensym)))
1195    `(progn
1196       (when *current-code-attribute*
1197         (save-code-specials *current-code-attribute*))
1198       (unwind-protect
1199           (let* ((,m ,method)
1200                  (*method* ,m)
1201                  (,c (method-ensure-code ,method))
1202                  (*pool* (class-file-constants ,class-file))
1203                  (*code* (code-code ,c))
1204                  (*registers-allocated* (code-max-locals ,c))
1205                  (*register* (code-current-local ,c))
1206                  (*current-code-attribute* ,c))
1207             (unwind-protect
1208                 ,@body
1209               ;; in case of a RETURN-FROM or GO, save the current state
1210               (setf (code-code ,c) *code*
1211                     (code-current-local ,c) *register*
1212                     (code-max-locals ,c) *registers-allocated*)))
1213         ;; using the same line of reasoning, restore the outer-scope state
1214         (when *current-code-attribute*
1215           (restore-code-specials *current-code-attribute*))))))
1216
1217
1218(defstruct (source-file-attribute (:conc-name source-)
1219                                  (:include attribute
1220                                            (name "SourceFile")
1221                                            (finalizer #'finalize-source-file)
1222                                            (writer #'write-source-file)))
1223  "An attribute of the class file indicating which source file
1224it was compiled from."
1225  filename)
1226
1227(defun finalize-source-file (source-file code class)
1228  (declare (ignorable code class))
1229  (setf (source-filename source-file)
1230        (pool-add-utf8 (class-file-constants class)
1231                       (source-filename source-file))))
1232
1233(defun write-source-file (source-file stream)
1234  (write-u2 (source-filename source-file) stream))
1235
1236
1237(defstruct (synthetic-attribute (:include attribute
1238                                          (name "Synthetic")
1239                                          (finalizer (constantly nil))
1240                                          (writer (constantly nil))))
1241  ;; finalizer and writer need to do nothing: Synthetic attributes are empty
1242  "An attribute of a class file, field or method to mark that it wasn't
1243included in the sources - but was generated artificially.")
1244
1245
1246(defstruct (line-numbers-attribute
1247             (:conc-name line-numbers-)
1248             (:include attribute
1249                       (name "LineNumberTable")
1250                       (finalizer #'finalize-line-numbers)
1251                       (writer #'write-line-numbers)))
1252  "An attribute of `code-attribute', containing a mapping of offsets
1253within the code section to the line numbers in the source file."
1254  table ;; a list of line-number structures, in reverse order
1255  )
1256
1257(defstruct line-number
1258  start-pc  ;; a label, before finalization, or 0 for "start of function"
1259  line)
1260
1261(defun finalize-line-numbers (line-numbers code class)
1262  (declare (ignorable code class))
1263  (dolist (line-number (line-numbers-table line-numbers))
1264    (unless (zerop (line-number-start-pc line-number))
1265      (setf (line-number-start-pc line-number)
1266            (code-label-offset code (line-number-start-pc line-number))))))
1267
1268(defun write-line-numbers (line-numbers stream)
1269  (write-u2 (length (line-numbers-table line-numbers)) stream)
1270  (dolist (line-number (reverse (line-numbers-table line-numbers)))
1271    (write-u2 (line-number-start-pc line-number) stream)
1272    (write-u2 (line-number-line line-number) stream)))
1273
1274(defun line-numbers-add-line (line-numbers start-pc line)
1275  (push (make-line-number :start-pc start-pc :line line)
1276        (line-numbers-table line-numbers)))
1277
1278(defstruct (local-variables-attribute
1279             (:conc-name local-var-)
1280             (:include attribute
1281                       (name "LocalVariableTable")
1282                       (finalizer #'finalize-local-variables)
1283                       (writer #'write-local-variables)))
1284  "An attribute of the `code-attribute', containing a table of local variable
1285names, their type and their scope of validity."
1286  table ;; a list of local-variable structures, in reverse order
1287  )
1288
1289(defstruct (local-variable (:conc-name local-))
1290  start-pc  ;; a label, before finalization
1291  length    ;; a label (at the ending position) before finalization
1292  name
1293  descriptor
1294  index ;; The index of the variable inside the block of locals
1295  )
1296
1297(defun finalize-local-variables (local-variables code class)
1298  (dolist (local-variable (local-var-table local-variables))
1299    (setf (local-start-pc local-variable)
1300          (code-label-offset code (local-start-pc local-variable))
1301          (local-length local-variable)
1302          ;; calculate 'length' from the distance between 2 labels
1303          (- (code-label-offset code (local-length local-variable))
1304             (local-start-pc local-variable))
1305          (local-name local-variable)
1306          (pool-add-utf8 (class-file-constants class)
1307                         (local-name local-variable))
1308          (local-descriptor local-variable)
1309          (pool-add-utf8 (class-file-constants class)
1310                         (local-descriptor local-variable)))))
1311
1312(defun write-local-variables (local-variables stream)
1313  (write-u2 (length (local-var-table local-variables)) stream)
1314  (dolist (local-variable (reverse (local-var-table local-variables)))
1315    (write-u2 (local-start-pc local-variable) stream)
1316    (write-u2 (local-length local-variable) stream)
1317    (write-u2 (local-name local-variable) stream)
1318    (write-u2 (local-descriptor local-variable) stream)
1319    (write-u2 (local-index local-variable) stream)))
1320
1321#|
1322
1323;; this is the minimal sequence we need to support:
1324
1325;;  create a class file structure
1326;;  add methods
1327;;  add code to the methods, switching from one method to the other
1328;;  finalize the methods, one by one
1329;;  write the class file
1330
1331to support the sequence above, we probably need to
1332be able to
1333
1334- find methods by signature
1335- find the method's code attribute
1336- add code to the code attribute
1337- finalize the code attribute contents (blocking it for further addition)
1338-
1339
1340
1341|#
1342
Note: See TracBrowser for help on using the repository browser.