bdfddf078250c31c1a4c12081ec3f7ceb0004b94
[org.ibex.classgen.git] / src / org / ibex / classgen / ConstantPool.java
1 package org.ibex.classgen;
2
3 import java.util.*;
4 import java.io.*;
5
6 import org.ibex.classgen.util.*;
7
8 class ConstantPool implements CGConst {
9     private final Hashtable entries = new Hashtable();
10     private Ent[] entriesByIndex; // only valid when stable
11     
12     private int usedSlots = 1; // 0 is reserved
13     private int state = OPEN;
14     private static final int OPEN = 0;
15     private static final int STABLE = 1; // existing entries won't change
16     private static final int SEALED = 2; // no new entries
17     
18     ConstantPool() { }
19     
20     public abstract class Ent {
21         int n; // this is the refcount if state == OPEN, index if >= STABLE
22         int tag;
23         Object key;
24         Ent(int tag) { this.tag = tag; }
25         void dump(DataOutput o) throws IOException { o.writeByte(tag); }
26         abstract Object _key();
27         final Object key() { return key == null ? (key = _key()) : key; }
28         int slots() { return 1; } // number of slots this ent takes up
29         void ref() {
30             if(state != OPEN) throw new IllegalStateException("cp is not open");
31             n++;
32         }
33         void unref() {
34             if(state != OPEN) throw new IllegalStateException("cp is not open");
35             if(--n == 0) entries.remove(key());
36         }
37     }
38     
39     class Utf8Ent extends Ent {
40         String s;
41         Utf8Ent() { super(CONSTANT_UTF8); }
42         Utf8Ent(String s) { this();  this.s = s; }
43         public String toString() { return s; }
44         void dump(DataOutput o) throws IOException { super.dump(o); o.writeUTF(s); }
45         Object _key() { return new Utf8Key(s); }
46     }
47     
48     class IntLitEnt extends Ent {
49         final int i;
50         IntLitEnt(int i) { super(CONSTANT_INTEGER); this.i = i; }
51         void dump(DataOutput o) throws IOException { super.dump(o); o.writeInt(i);  }
52         Object _key() { return new Integer(i); }
53     }
54     class FloatLitEnt extends Ent {
55         final float f;
56         FloatLitEnt(float f) { super(CONSTANT_FLOAT); this.f = f; }
57         void dump(DataOutput o) throws IOException { super.dump(o); o.writeFloat(f);  }
58         Object _key() { return new Float(f); }
59     }
60     class LongLitEnt extends Ent {
61         final long l;
62         LongLitEnt(long l) { super(CONSTANT_LONG); this.l = l; }
63         void dump(DataOutput o) throws IOException { super.dump(o); o.writeLong(l); }
64         Object _key() { return new Long(l); }
65         int slots() { return 2; }
66     }
67     class DoubleLitEnt extends Ent {
68         final double d;
69         DoubleLitEnt(double d) { super(CONSTANT_DOUBLE); this.d = d; }
70         void dump(DataOutput o) throws IOException { super.dump(o); o.writeDouble(d); }
71         Object _key() { return new Double(d); }
72         int slots() { return 2; }
73     }
74     class StringLitEnt extends Ent {
75         Utf8Ent utf8;
76         StringLitEnt() { super(CONSTANT_STRING); }
77         StringLitEnt(String s) { this(); this.utf8 = (Utf8Ent)addUtf8(s); }
78         void dump(DataOutput o) throws IOException { super.dump(o); o.writeShort(utf8.n); }
79         Object _key() { return utf8.s; }
80         void unref() { utf8.unref(); super.unref(); }
81     }
82     class ClassEnt extends Ent {
83         Utf8Ent utf8;
84         ClassEnt() { super(CONSTANT_CLASS); }
85         ClassEnt(String s) { this(); this.utf8 = (Utf8Ent) addUtf8(s); }
86         void dump(DataOutput o) throws IOException { super.dump(o); o.writeShort(utf8.n); }
87         Type.Class getTypeClass() { return  (Type.Class) key(); }
88         Object _key() { return Type.Class.instance(utf8.s); }
89         void unref() { utf8.unref(); super.unref(); }
90         public String toString() { return "[Class: " + utf8.s + "]"; }
91     }
92     
93     class NameAndTypeEnt extends Ent {
94         Utf8Ent name;
95         Utf8Ent type;
96         
97         NameAndTypeEnt() { super(CONSTANT_NAMEANDTYPE); }
98         NameAndTypeEnt(String name, String type) {
99             this();
100             this.name = (Utf8Ent) addUtf8(name);
101             this.type = (Utf8Ent) addUtf8(type);
102         }
103         void dump(DataOutput o) throws IOException { super.dump(o); o.writeShort(name.n); o.writeShort(type.n); }
104         Object _key() { return new NameAndTypeKey(name.s, type.s); }
105         void unref() { name.unref(); type.unref(); super.unref(); }
106     }
107     
108     class MemberEnt extends Ent {
109         ClassEnt klass;
110         NameAndTypeEnt member;
111         
112         MemberEnt(int tag) { super(tag); }
113         MemberEnt(int tag, Type.Class klass, String name, String type) {
114             this(tag);
115             this.klass = (ClassEnt) add(klass); 
116             this.member = addNameAndType(name,type);
117         }
118         
119         void dump(DataOutput o) throws IOException { super.dump(o); o.writeShort(klass.n); o.writeShort(member.n); }
120         
121         Object _key() {
122             if(member.name == null) throw new Error("should never happen");
123             switch(tag) {
124                 case CONSTANT_FIELDREF:
125                     return klass.getTypeClass().field(member.name.s, member.type.s);
126                 case CONSTANT_METHODREF:
127                 case CONSTANT_INTERFACEMETHODREF:
128                     Type.Class.Method m = klass.getTypeClass().method(member.name.s,member.type.s);
129                     return tag == CONSTANT_INTERFACEMETHODREF ? (Object) new InterfaceMethodKey(m) : (Object) m;
130                 default:
131                     throw new Error("should never happen");
132             }
133         }
134         void unref() { klass.unref(); member.unref(); super.unref(); }
135     }
136     
137     /*
138      * Cache Keys
139      */
140     static class Utf8Key {
141         String s;
142         public Utf8Key(String s) { this.s = s; }
143         public boolean equals(Object o) { return o instanceof Utf8Key && ((Utf8Key)o).s.equals(s); }
144         public int hashCode() { return ~s.hashCode(); }
145     }
146         
147     static class NameAndTypeKey {
148         String name;
149         String type;
150         NameAndTypeKey(String name, String type) { this.name = name; this.type = type; }
151         public boolean equals(Object o_) {
152             if (!(o_ instanceof NameAndTypeKey)) return false;
153             NameAndTypeKey o = (NameAndTypeKey) o_;
154             return o.name.equals(name) && o.type.equals(type);
155         }
156         public int hashCode() { return name.hashCode() ^ type.hashCode(); }
157     }
158     
159     static class InterfaceMethodKey {
160         Type.Class.Method method;
161         InterfaceMethodKey(Type.Class.Method method) { this.method = method; }
162         public int hashCode() { return ~method.hashCode(); }
163         public boolean equals(Object o) { return o instanceof InterfaceMethodKey && ((InterfaceMethodKey)o).method.equals(method); }
164     }
165     
166     /*
167      * Methods
168      */
169     
170     Ent get(Object o) { return (Ent) entries.get(o); }
171     Utf8Ent getUtf8(String s) { return (Utf8Ent) get(new Utf8Key(s)); }
172     
173     int getIndex(Object o) {
174         Ent e = get(o);
175         if (e == null) throw new IllegalStateException("entry not found");
176         return getIndex(e);
177     }
178     int getUtf8Index(String s) {
179         Ent e = getUtf8(s);
180         if (e == null) throw new IllegalStateException("entry not found");
181         return getIndex(e);
182     }
183     int getIndex(Ent ent) {
184         if (state < STABLE) throw new IllegalStateException("constant pool is not stable");
185         return ent.n;
186     }
187     
188     Ent getByIndex(int index) {
189         if (state < STABLE) throw new IllegalStateException("constant pool is not stable");
190         Ent e;
191         if (index >= 65536 || index >= entriesByIndex.length || (e = entriesByIndex[index]) == null) 
192             throw new IllegalArgumentException("invalid cp index: " + index + "/" + entriesByIndex.length);
193         return e;
194     }
195     
196     String getUtf8KeyByIndex(int index) {
197         Ent e = getByIndex(index);
198         if(!(e instanceof Utf8Ent)) throw new IllegalArgumentException("that isn't a utf8 (" + e.toString() + ")");
199         return ((Utf8Ent)e).s;
200     }
201     
202     Object getKeyByIndex(int index) {
203         Ent e = getByIndex(index);
204         return e == null ? null : e.key();
205     }
206     
207     NameAndTypeEnt addNameAndType(String name, String descriptor) { return (NameAndTypeEnt) add(new NameAndTypeKey(name, descriptor)); }
208     Utf8Ent addUtf8(String s) { return (Utf8Ent) add(new Utf8Key(s)); }
209     
210     Ent add(Object o) {
211         boolean isInterfaceMethod;
212         if (state == SEALED) throw new IllegalStateException("constant pool is sealed");
213         
214         Ent ent = get(o);
215         if (ent != null) {
216             if (state == OPEN) ent.n++;
217             return ent;
218         }
219         
220         if (o instanceof Type.Class) { ent = new ClassEnt(((Type.Class)o).internalForm()); }
221         else if (o instanceof String) { ent = new StringLitEnt((String)o); }
222         else if (o instanceof Integer) { ent = new IntLitEnt(((Integer)o).intValue()); }
223         else if (o instanceof Float) { ent = new FloatLitEnt(((Float)o).floatValue()); }
224         else if (o instanceof Long) { ent = new LongLitEnt(((Long)o).longValue()); }
225         else if (o instanceof Double) { ent = new DoubleLitEnt(((Double)o).doubleValue()); }
226         else if (o instanceof Utf8Key) { ent = new Utf8Ent(((Utf8Key)o).s); }
227         else if (o instanceof NameAndTypeKey) {
228             NameAndTypeKey key = (NameAndTypeKey) o;
229             ent = new NameAndTypeEnt(key.name,key.type);
230         }
231         else if ((isInterfaceMethod = o instanceof InterfaceMethodKey) || o instanceof Type.Class.Member) {
232             Type.Class.Member m = isInterfaceMethod ? ((InterfaceMethodKey)o).method : (Type.Class.Member) o;
233             int tag = isInterfaceMethod              ? CONSTANT_INTERFACEMETHODREF
234                     : m instanceof Type.Class.Field  ? CONSTANT_FIELDREF 
235                     : m instanceof Type.Class.Method ? CONSTANT_METHODREF
236                     : 0;
237             if (tag == 0) throw new Error("should never happen");
238             ent = new MemberEnt(tag, m.getDeclaringClass(), m.name, m.getTypeDescriptor());
239         } 
240         else {
241             throw new IllegalArgumentException("Unknown type passed to add");
242         }
243         
244         int spaces = ent.slots();        
245         if (usedSlots + spaces > 65536) throw new ClassFile.Exn("constant pool full");
246         
247         ent.n = state == OPEN ? 1 : usedSlots; // refcount or index
248
249         usedSlots += spaces;        
250
251         entries.put(o, ent);
252         return ent;
253     }
254     
255     int slots() { return usedSlots; }
256
257     void seal() { state = SEALED; }
258     
259     private Ent[] asArray() {
260         int count = entries.size();
261         Ent[] ents = new Ent[count];
262         int i=0;
263         Enumeration e = entries.keys();
264         while(e.hasMoreElements()) ents[i++] = (Ent) entries.get(e.nextElement());
265         if (i != count) throw new Error("should never happen");
266         return ents;
267     }
268     
269     private void assignIndex(Ent[] ents) {
270         int index = 1;
271         entriesByIndex = new Ent[ents.length*2];
272         for(int i=0;i<ents.length;i++) {
273             Ent ent = ents[i];
274             ent.n = index;
275             entriesByIndex[index] = ent;
276             index += ent.slots();
277         }
278     }
279         
280     void stable() {
281         if (state != OPEN) return;
282         state = STABLE;
283         assignIndex(asArray());
284     } 
285
286     private static final Sort.CompareFunc compareFunc = new Sort.CompareFunc() {
287         public int compare(Object a_, Object b_) {
288             return ((Ent)a_).n - ((Ent)b_).n;
289         }
290     };
291     
292     private static final Sort.CompareFunc reverseCompareFunc = new Sort.CompareFunc() {
293         public int compare(Object a_, Object b_) {
294             return ((Ent)b_).n - ((Ent)a_).n;
295         }
296     };
297     
298     void optimize() {
299         if (state != OPEN) throw new IllegalStateException("can't optimize a stable constant pool");
300         Ent[] ents = asArray();
301         Sort.sort(ents, reverseCompareFunc);
302         state = STABLE;
303         assignIndex(ents);
304     }
305     
306     void dump(DataOutput o) throws IOException {
307         Ent[] ents = asArray();
308         Sort.sort(ents, compareFunc);
309         o.writeShort(usedSlots);
310         for(int i=0;i<ents.length;i++) {
311             //System.err.println("" + ents[i].n + ": " + ents[i].toString());
312             ents[i].dump(o);
313         }
314     }
315     
316     ConstantPool(DataInput in) throws ClassFile.ClassReadExn, IOException {
317         usedSlots = in.readUnsignedShort();
318         if (usedSlots==0) throw new ClassFile.ClassReadExn("invalid used slots");
319         
320         // these are to remember the descriptor ents we have to fix up
321         int[] e1s = new int[usedSlots];
322         int[] e2s = new int[usedSlots];
323         
324         entriesByIndex = new Ent[usedSlots];
325         
326         for(int i=1;i<usedSlots;) {
327             byte tag = in.readByte();
328             Ent e;
329             switch(tag) {
330                 case CONSTANT_CLASS: // Object Type
331                     e = new ClassEnt();
332                     e1s[i] = in.readUnsignedShort();
333                     break;
334                 case CONSTANT_STRING: // String
335                     e = new StringLitEnt();
336                     e1s[i] = in.readUnsignedShort();
337                     break;
338                 case CONSTANT_FIELDREF: // Type.Class.Field
339                 case CONSTANT_METHODREF: // Type.Class.Method
340                 case CONSTANT_INTERFACEMETHODREF: // Instance Method Ref
341                 case CONSTANT_NAMEANDTYPE:
342                     e = tag == CONSTANT_NAMEANDTYPE ? (Ent) new NameAndTypeEnt() : (Ent) new MemberEnt(tag);
343                     e1s[i] = in.readUnsignedShort();
344                     e2s[i] = in.readUnsignedShort();
345                     break;
346                 case CONSTANT_INTEGER: // Integer
347                     e = new IntLitEnt(in.readInt());
348                     break;
349                 case CONSTANT_FLOAT: // Float
350                     e = new FloatLitEnt(in.readFloat());
351                     break;
352                 case CONSTANT_LONG: // Long
353                     e = new LongLitEnt(in.readLong());
354                     break;
355                 case CONSTANT_DOUBLE: // Double
356                     e = new DoubleLitEnt(in.readDouble());
357                     break;
358                 case CONSTANT_UTF8: // Utf8
359                     e = new Utf8Ent(in.readUTF());
360                     break;
361                 default:
362                     throw new ClassFile.ClassReadExn("invalid cp ent tag: " + tag + " (slot " + i + ")");
363             }
364             entriesByIndex[i] = e;
365             i += e.slots();
366         }
367         
368         for(int i=1;i<usedSlots;) {
369             Ent e = entriesByIndex[i];
370             if (e == null) throw new Error("should never happen: " + i + "/"+usedSlots);
371             boolean isMem = e instanceof MemberEnt;
372             boolean isString = e instanceof StringLitEnt;
373             boolean isClass =  e instanceof ClassEnt;
374             boolean isNameAndType = e instanceof NameAndTypeEnt;
375             if (isMem || isClass || isString || isNameAndType) {
376                 if (e1s[i] == 0 || e1s[i] >= usedSlots) throw new ClassFile.ClassReadExn("invalid cp index");
377                 Ent e1 = entriesByIndex[e1s[i]];
378                 if(e1 == null) throw new ClassFile.ClassReadExn("invalid cp index");
379                 if(isClass) {
380                     if(!(e1 instanceof Utf8Ent)) throw new ClassFile.ClassReadExn("expected a uft8ent");
381                     ((ClassEnt)e).utf8 = (Utf8Ent) e1;
382                 } else if(isString) {
383                     if(!(e1 instanceof Utf8Ent)) throw new ClassFile.ClassReadExn("expected a uft8ent");
384                     ((StringLitEnt)e).utf8 = (Utf8Ent) e1;
385                 } else if(isMem || isNameAndType) {
386                     if (e2s[i] == 0 || e2s[i] >= usedSlots) throw new ClassFile.ClassReadExn("invalid cp index");
387                     Ent e2 = entriesByIndex[e2s[i]];
388                     if(isMem) {
389                         if(!(e1 instanceof ClassEnt)) throw new ClassFile.ClassReadExn("expected a classent");
390                         if(!(e2 instanceof NameAndTypeEnt)) throw new ClassFile.ClassReadExn("expected a nameandtypeent, not " + e2);
391                         MemberEnt me = (MemberEnt) e;
392                         me.klass = (ClassEnt) e1;
393                         me.member = (NameAndTypeEnt) e2;
394                     } else if(isNameAndType) {
395                         if(!(e1 instanceof Utf8Ent)) throw new ClassFile.ClassReadExn("expected a uft8ent");
396                         if(!(e2 instanceof Utf8Ent)) throw new ClassFile.ClassReadExn("expected a uft8ent");
397                         NameAndTypeEnt nte = (NameAndTypeEnt) e;
398                         nte.name = (Utf8Ent) e1;
399                         nte.type = (Utf8Ent) e2;
400                     }
401                 }
402             }
403             i += e.slots();
404         }
405         for(int i=1; i<usedSlots;) {
406             Ent e = entriesByIndex[i];
407             entries.put(e.key(), e);
408             i += e.slots();
409         }
410         state = STABLE;
411     }
412 }