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