added Type.Array
[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(Type.fromDescriptor(name).asObject(), Type.fromDescriptor(superName).asObject(), 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         OutputStream os = new FileOutputStream(f);
105         dump(os);
106         os.close();
107     }
108    
109     /** Writes the classfile data to the outputstream specified
110         @param os The stream to write the class to
111         @exception IOException if an IOException occures while writing the class data
112         @exception IllegalStateException if the data for a method is in an inconsistent state (required arguments missing, etc)
113         @exception Exn if the classfile could not be written for any other reason (constant pool full, etc)
114     */
115     public void dump(OutputStream os) throws IOException {
116         DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(os));
117         _dump(dos);
118         dos.flush();
119     }
120     
121     private void _dump(DataOutput o) throws IOException {
122         cp.optimize();
123         cp.stable();
124         
125         cp.add(thisType);
126         cp.add(superType);
127         if(interfaces != null) for(int i=0;i<interfaces.length;i++) cp.add(interfaces[i]);
128         if(sourceFile != null && !attributes.contains("SourceFile")) attributes.add("SourceFile",cp.addUtf8(sourceFile));
129                 
130         for(int i=0;i<methods.size();i++) ((MethodGen)methods.elementAt(i)).finish();
131         for(int i=0;i<fields.size();i++) ((FieldGen)fields.elementAt(i)).finish();
132         
133         cp.seal();
134         
135         o.writeInt(0xcafebabe); // magic
136         o.writeShort(3); // minor_version
137         o.writeShort(45); // major_version
138         
139         cp.dump(o); // constant_pool
140         
141         o.writeShort(flags);
142         o.writeShort(cp.getIndex(thisType)); // this_class
143         o.writeShort(cp.getIndex(superType)); // super_class
144         
145         o.writeShort(interfaces==null ? 0 : interfaces.length); // interfaces_count
146         if(interfaces != null) for(int i=0;i<interfaces.length;i++) o.writeShort(cp.getIndex(interfaces[i])); // interfaces
147         
148         o.writeShort(fields.size()); // fields_count
149         for(int i=0;i<fields.size();i++) ((FieldGen)fields.elementAt(i)).dump(o); // fields
150
151         o.writeShort(methods.size()); // methods_count
152         for(int i=0;i<methods.size();i++) ((MethodGen)methods.elementAt(i)).dump(o); // methods
153         
154         o.writeShort(attributes.size()); // attributes_count
155         attributes.dump(o); // attributes        
156     }
157     
158     public ClassGen read(File f) throws ClassReadExn, IOException {
159         InputStream is = new FileInputStream(f);
160         ClassGen ret = read(is);
161         is.close();
162         return ret;
163     }
164     
165     public ClassGen read(InputStream is) throws ClassReadExn, IOException {
166         return new ClassGen(new DataInputStream(new BufferedInputStream(is)));
167     }
168
169     ClassGen(DataInput i) throws ClassReadExn, IOException {
170         if(i.readInt() != 0xcadebabe) throw new ClassReadExn("invalid magic");
171         short minor = (short)i.readInt();
172         if(minor != 3) throw new ClassReadExn("invalid minor version: " + minor);
173         if(i.readInt() != 45) throw new ClassReadExn("invalid major version");
174         cp = new CPGen(i);
175         flags = (short)i.readShort();
176         thisType = cp.getType(i.readShort());
177         superType = cp.getType(i.readShort());
178         interfaces = new Type.Object[i.readShort()];
179         for(int j=0; j<interfaces.length; j++) interfaces[j] = cp.getType(i.readShort());
180         int numFields = i.readShort();
181         for(int j=0; j<numFields; j++) fields.add(new FieldGen(i));
182         int numMethods = i.readShort();
183         for(int j=0; j<numMethods; j++) methods.add(new MethodGen(i));
184         attributes = new AttrGen(i);
185     }
186     
187     /** Thrown when class generation fails for a reason not under the control of the user
188         (IllegalStateExceptions are thrown in those cases */
189     public static class Exn extends RuntimeException {
190         public Exn(String s) { super(s); }
191     }
192     
193     public static class ClassReadExn extends IOException {
194         public ClassReadExn(String s) { super(s); }
195     }
196     
197     /** A class representing a field or method reference. This is used as an argument to the INVOKE*, GET*, and PUT* bytecodes
198         @see MethodRef
199         @see FieldRef
200         @see MethodRef.I
201         @see FieldRef
202     */
203     public static abstract class FieldOrMethodRef {
204         Type.Object klass;
205         String name;
206         String descriptor;
207         
208         FieldOrMethodRef(Type.Object klass, String name, String descriptor) { this.klass = klass; this.name = name; this.descriptor = descriptor; }
209         FieldOrMethodRef(FieldOrMethodRef o) { this.klass = o.klass; this.name = o.name; this.descriptor = o.descriptor; }
210         public boolean equals(Object o_) {
211             if(!(o_ instanceof FieldOrMethodRef)) return false;
212             FieldOrMethodRef o = (FieldOrMethodRef) o_;
213             return o.klass.equals(klass) && o.name.equals(name) && o.descriptor.equals(descriptor);
214         }
215         public int hashCode() { return klass.hashCode() ^ name.hashCode() ^ descriptor.hashCode(); }
216     }
217     
218     static class AttrGen {
219         private final CPGen cp;
220         private final Hashtable ht = new Hashtable();
221         
222         public AttrGen(DataInput in) {
223             throw new Error("Brian is superlame");
224         }
225         public AttrGen(CPGen cp) {
226             this.cp = cp;
227         }
228         
229         public void add(String s, Object data) {
230             cp.addUtf8(s);
231             ht.put(s,data);
232         }
233         
234         public boolean contains(String s) { return ht.get(s) != null; }
235         
236         public int size() { return ht.size(); }
237         
238         public void dump(DataOutput o) throws IOException {
239             for(Enumeration e = ht.keys(); e.hasMoreElements();) {
240                 String name = (String) e.nextElement();
241                 Object val = ht.get(name);
242                 o.writeShort(cp.getUtf8Index(name));
243                 if(val instanceof byte[]) {
244                     byte[] buf = (byte[]) val;
245                     o.writeInt(buf.length);
246                     o.write(buf);
247                 } else if(val instanceof CPGen.Ent) {
248                     o.writeInt(2);
249                     o.writeShort(cp.getIndex((CPGen.Ent)val));
250                 } else {
251                     throw new Error("should never happen");
252                 }
253             }
254         }
255     }
256     
257     /*public static void main(String[] args) throws Exception {
258         Type.Object me = new Type.Object("Test");
259         ClassGen cg = new ClassGen("Test","java.lang.Object",ACC_PUBLIC|ACC_SUPER|ACC_FINAL);
260         FieldGen fg = cg.addField("foo",Type.INT,ACC_PUBLIC|ACC_STATIC);
261         
262         MethodGen mg = cg.addMethod("main",Type.VOID,new Type[]{Type.arrayType(Type.STRING)},ACC_STATIC|ACC_PUBLIC);
263         mg.setMaxLocals(1);
264         mg.addPushConst(0);
265         //mg.add(ISTORE_0);
266         mg.add(PUTSTATIC, fieldRef(me,"foo",Type.INT));
267         int top = mg.size();
268         mg.add(GETSTATIC,cg.fieldRef(new Type.Object("java.lang.System"),"out",new Type.Object("java.io.PrintStream")));
269         //mg.add(ILOAD_0);
270         mg.add(GETSTATIC,cg.fieldRef(me,"foo",Type.INT));
271         mg.add(INVOKEVIRTUAL,cg.methodRef(new Type.Object("java.io.PrintStream"),"println",Type.VOID, new Type[]{Type.INT}));
272         //mg.add(IINC,new int[]{0,1});
273         //mg.add(ILOAD_0);
274         mg.add(GETSTATIC,cg.fieldRef(me,"foo",Type.INT));
275         mg.addPushConst(1);
276         mg.add(IADD);
277         mg.add(DUP);
278         mg.add(PUTSTATIC,cg.fieldRef(me,"foo",Type.INT));       
279         mg.addPushConst(10);
280         mg.add(IF_ICMPLT,top);
281         mg.add(RETURN);
282         cg.dump("Test.class");
283     }*/
284 }