optimized constant pool
[org.ibex.classgen.git] / src / org / ibex / classgen / ClassGen.java
1 package org.ibex.classgen;
2
3 import java.util.*;
4 import java.io.*;
5
6 /** Class generation object representing the whole classfile */
7 public class ClassGen implements CGConst {
8     private final Type.Object thisType;
9     private final Type.Object superType;
10     private final Type.Object[] interfaces;
11     final int flags;
12     
13     private String sourceFile; 
14     private final Vector fields = new Vector();
15     private final Vector methods = new Vector();
16     
17     final CPGen cp;
18     private final AttrGen attributes;
19     
20     /** @see #ClassGen(Type.Object,Type.Object,int) */
21     public ClassGen(String name, String superName, int flags) {
22         this(new Type.Object(name),new Type.Object(superName),flags);
23     }
24
25     /** @see #ClassGen(Type.Object,Type.Object,int,Type.Object[]) */
26     public ClassGen(Type.Object thisType,Type.Object superType, int flags) {
27         this(thisType,superType,flags,null);
28     }
29     
30     /** Creates a new ClassGen object 
31         @param thisType The type of the class to generate
32         @param superType The superclass of the generated class (commonly Type.OBJECT) 
33         @param flags The access flags for this class (ACC_PUBLIC, ACC_FINAL, ACC_SUPER, ACC_INTERFACE, and ACC_ABSTRACT)
34     */
35     public ClassGen(Type.Object thisType,Type.Object superType, int flags, Type.Object[] interfaces) {
36         if((flags & ~(ACC_PUBLIC|ACC_FINAL|ACC_SUPER|ACC_INTERFACE|ACC_ABSTRACT)) != 0)
37             throw new IllegalArgumentException("invalid flags");
38         this.thisType = thisType;
39         this.superType = superType;
40         this.interfaces = interfaces;
41         this.flags = flags;
42         
43         cp = new CPGen();
44         attributes = new AttrGen(cp);
45     }
46     
47     /** Adds a new method to this class 
48         @param name The name of the method (not the signature, just the name)
49         @param ret The return type of the method
50         @param args The arguments to the method
51         @param flags The flags for the method
52                      (ACC_PUBLIC, ACC_PRIVATE, ACC_PROTECTED, ACC_STATIC, ACC_SYNCHRONIZED, ACC_NATIVE, ACC_ABSTRACT, ACC_STRICT)
53         @return A new MethodGen object for the method
54         @exception IllegalArgumentException if illegal flags are specified
55         @see MethodGen
56         @see CGConst
57     */
58     public final MethodGen addMethod(String name, Type ret, Type[] args, int flags) {
59         MethodGen mg = new MethodGen(this,name,ret,args,flags);
60         methods.addElement(mg);
61         return mg;
62     }
63     
64     /** Adds a new field to this class 
65         @param name The name of the filed (not the signature, just the name)
66         @param type The type of the field
67         @param flags The flags for the field
68         (ACC_PUBLIC, ACC_PRIVATE, ACC_PROTECTED, ACC_STATIC, ACC_FINAL, ACC_VOLATILE, ACC_TRANSIENT)
69         @return A new FieldGen object for the method
70         @exception IllegalArgumentException if illegal flags are specified
71         @see FieldGen
72         @see CGConst
73         */  
74     public final FieldGen addField(String name, Type type, int flags) {
75         FieldGen fg = new FieldGen(this,name,type,flags);
76         fields.addElement(fg);
77         return fg;
78     }
79     
80     /** Sets the source value of the SourceFile attribute of this class 
81         @param sourceFile The string to be uses as the SourceFile of this class
82     */
83     public void setSourceFile(String sourceFile) { this.sourceFile = sourceFile; }
84     
85     /** Writes the classfile data to the file specifed
86         @see ClassGen#dump(OutputStream)
87     */
88     public void dump(String file) throws IOException { dump(new File(file)); }
89     
90     /** Writes the classfile data to the file specified
91         If <i>f</i> is a directory directory components under it are created for the package the class is in (like javac's -d option)
92         @see ClassGen#dump(OutputStream)
93     */
94     public void dump(File f) throws IOException {
95         if(f.isDirectory()) {
96             String[] a = thisType.components();
97             int i;
98             for(i=0;i<a.length-1;i++) {
99                 f = new File(f,a[i]);
100                 f.mkdir();
101             }
102             f = new File(f,a[i] + ".class");
103         }
104         dump(new FileOutputStream(f));
105     }
106    
107     /** Writes the classfile data to the outputstream specified
108         @param os The stream to write the class to
109         @exception IOException if an IOException occures while writing the class data
110         @exception IllegalStateException if the data for a method is in an inconsistent state (required arguments missing, etc)
111         @exception Exn if the classfile could not be written for any other reason (constant pool full, etc)
112     */
113     public void dump(OutputStream os) throws IOException {
114         DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(os));
115         _dump(dos);
116         dos.flush();
117     }
118     
119     private void _dump(DataOutput o) throws IOException {
120         cp.optimize();
121         cp.stable();
122         
123         cp.add(thisType);
124         cp.add(superType);
125         if(interfaces != null) for(int i=0;i<interfaces.length;i++) cp.add(interfaces[i]);
126         if(sourceFile != null && !attributes.contains("SourceFile")) attributes.add("SourceFile",cp.addUtf8(sourceFile));
127                 
128         for(int i=0;i<methods.size();i++) ((MethodGen)methods.elementAt(i)).finish();
129         for(int i=0;i<fields.size();i++) ((FieldGen)fields.elementAt(i)).finish();
130         
131         cp.seal();
132         
133         o.writeInt(0xcafebabe); // magic
134         o.writeShort(3); // minor_version
135         o.writeShort(45); // major_version
136         
137         o.writeShort(cp.slots()); // constant_pool_count
138         cp.dump(o); // constant_pool
139         
140         o.writeShort(flags);
141         o.writeShort(cp.getIndex(thisType)); // this_class
142         o.writeShort(cp.getIndex(superType)); // super_class
143         
144         o.writeShort(interfaces==null ? 0 : interfaces.length); // interfaces_count
145         if(interfaces != null) for(int i=0;i<interfaces.length;i++) o.writeShort(cp.getIndex(interfaces[i])); // interfaces
146         
147         o.writeShort(fields.size()); // fields_count
148         for(int i=0;i<fields.size();i++) ((FieldGen)fields.elementAt(i)).dump(o); // fields
149
150         o.writeShort(methods.size()); // methods_count
151         for(int i=0;i<methods.size();i++) ((MethodGen)methods.elementAt(i)).dump(o); // methods
152         
153         o.writeShort(attributes.size()); // attributes_count
154         attributes.dump(o); // attributes        
155     }
156     
157     /** Thrown when class generation fails for a reason not under the control of the user
158         (IllegalStateExceptions are thrown in those cases */
159     public static class Exn extends RuntimeException {
160         public Exn(String s) { super(s); }
161     }
162     
163     /** A class representing a field or method reference. This is used as an argument to the INVOKE*, GET*, and PUT* bytecodes
164         @see MethodRef
165         @see FieldRef
166         @see MethodRef.I
167         @see FieldRef
168     */
169     public static abstract class FieldOrMethodRef {
170         Type.Object klass;
171         String name;
172         String descriptor;
173         
174         FieldOrMethodRef(Type.Object klass, String name, String descriptor) { this.klass = klass; this.name = name; this.descriptor = descriptor; }
175         FieldOrMethodRef(FieldOrMethodRef o) { this.klass = o.klass; this.name = o.name; this.descriptor = o.descriptor; }
176         public boolean equals(Object o_) {
177             if(!(o_ instanceof FieldOrMethodRef)) return false;
178             FieldOrMethodRef o = (FieldOrMethodRef) o_;
179             return o.klass.equals(klass) && o.name.equals(name) && o.descriptor.equals(descriptor);
180         }
181         public int hashCode() { return klass.hashCode() ^ name.hashCode() ^ descriptor.hashCode(); }
182     }
183     
184     static class AttrGen {
185         private final CPGen cp;
186         private final Hashtable ht = new Hashtable();
187         
188         public AttrGen(CPGen cp) {
189             this.cp = cp;
190         }
191         
192         public void add(String s, Object data) {
193             cp.addUtf8(s);
194             ht.put(s,data);
195         }
196         
197         public boolean contains(String s) { return ht.get(s) != null; }
198         
199         public int size() { return ht.size(); }
200         
201         public void dump(DataOutput o) throws IOException {
202             for(Enumeration e = ht.keys(); e.hasMoreElements();) {
203                 String name = (String) e.nextElement();
204                 Object val = ht.get(name);
205                 o.writeShort(cp.getUtf8Index(name));
206                 if(val instanceof byte[]) {
207                     byte[] buf = (byte[]) val;
208                     o.writeInt(buf.length);
209                     o.write(buf);
210                 } else if(val instanceof CPGen.Ent) {
211                     o.writeInt(2);
212                     o.writeShort(cp.getIndex((CPGen.Ent)val));
213                 } else {
214                     throw new Error("should never happen");
215                 }
216             }
217         }
218     }
219     
220     /*public static void main(String[] args) throws Exception {
221         Type.Object me = new Type.Object("Test");
222         ClassGen cg = new ClassGen("Test","java.lang.Object",ACC_PUBLIC|ACC_SUPER|ACC_FINAL);
223         FieldGen fg = cg.addField("foo",Type.INT,ACC_PUBLIC|ACC_STATIC);
224         
225         MethodGen mg = cg.addMethod("main",Type.VOID,new Type[]{Type.arrayType(Type.STRING)},ACC_STATIC|ACC_PUBLIC);
226         mg.setMaxLocals(1);
227         mg.addPushConst(0);
228         //mg.add(ISTORE_0);
229         mg.add(PUTSTATIC, fieldRef(me,"foo",Type.INT));
230         int top = mg.size();
231         mg.add(GETSTATIC,cg.fieldRef(new Type.Object("java.lang.System"),"out",new Type.Object("java.io.PrintStream")));
232         //mg.add(ILOAD_0);
233         mg.add(GETSTATIC,cg.fieldRef(me,"foo",Type.INT));
234         mg.add(INVOKEVIRTUAL,cg.methodRef(new Type.Object("java.io.PrintStream"),"println",Type.VOID, new Type[]{Type.INT}));
235         //mg.add(IINC,new int[]{0,1});
236         //mg.add(ILOAD_0);
237         mg.add(GETSTATIC,cg.fieldRef(me,"foo",Type.INT));
238         mg.addPushConst(1);
239         mg.add(IADD);
240         mg.add(DUP);
241         mg.add(PUTSTATIC,cg.fieldRef(me,"foo",Type.INT));       
242         mg.addPushConst(10);
243         mg.add(IF_ICMPLT,top);
244         mg.add(RETURN);
245         cg.dump("Test.class");
246     }*/
247 }