introduced Type.Ref as common superclass of Type.Class and 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.Class thisType;
9     private final Type.Class superType;
10     private final Type.Class[] interfaces;
11     private short minor;
12     private short major;
13     final int flags;
14     
15     private String sourceFile; 
16     private final Vector fields = new Vector();
17     private final Vector methods = new Vector();
18     
19     final CPGen cp;
20     private final AttrGen attributes;
21
22     public static String flagsToString(int flags) {
23         String ret = "";
24         if ((flags & ACC_PUBLIC) != 0)       ret += "public ";
25         if ((flags & ACC_PRIVATE) != 0)      ret += "private ";
26         if ((flags & ACC_PROTECTED) != 0)    ret += "protected ";
27         if ((flags & ACC_STATIC) != 0)       ret += "static ";
28         if ((flags & ACC_FINAL) != 0)        ret += "final ";
29         if ((flags & ACC_ABSTRACT) != 0)     ret += "abstract ";
30         if ((flags & ACC_SYNCHRONIZED) != 0) ret += "synchronized ";
31         if ((flags & ACC_NATIVE) != 0)       ret += "native ";
32         if ((flags & ACC_STRICT) != 0)       ret += "strictfp ";
33         if ((flags & ACC_VOLATILE) != 0)     ret += "volatile ";
34         if ((flags & ACC_TRANSIENT) != 0)    ret += "transient ";
35         return ret;
36     }
37   
38     public String toString() { StringBuffer sb = new StringBuffer(); toString(sb); return sb.toString(); }
39     public void   toString(StringBuffer sb) {
40         sb.append(flagsToString(flags));
41         sb.append((flags & ACC_INTERFACE) != 0 ? "interface " : "class ");
42         sb.append(thisType);
43         if (superType != null) sb.append(" extends " + superType);
44         if (interfaces != null && interfaces.length > 0) sb.append(" implements");
45         for(int i=0; i<interfaces.length; i++) sb.append((i==0?" ":", ")+interfaces[i]);
46         sb.append(" {");
47         sb.append(" // [jcf v"+major+"."+minor+"]");
48         if (sourceFile != null) sb.append(" from " + sourceFile);
49         sb.append("\n");
50         for(int i=0; i<fields.size(); i++) {
51             sb.append("  ");
52             ((FieldGen)fields.elementAt(i)).toString(sb);
53             sb.append("\n");
54         }
55         for(int i=0; i<methods.size(); i++) {
56             sb.append("  ");
57             ((MethodGen)methods.elementAt(i)).toString(sb, thisType.getShortName());
58             sb.append("\n");
59         }
60         sb.append("}");
61     }
62
63     /** @see #ClassGen(Type.Class, Type.Class, int) */
64     public ClassGen(String name, String superName, int flags) {
65         this(Type.fromDescriptor(name).asClass(), Type.fromDescriptor(superName).asClass(), flags);
66     }
67
68     /** @see #ClassGen(Type.Class, Type.Class, int, Type.Class[]) */
69     public ClassGen(Type.Class thisType, Type.Class superType, int flags) {
70         this(thisType, superType, flags, null);
71     }
72     
73     /** Creates a new ClassGen object 
74         @param thisType The type of the class to generate
75         @param superType The superclass of the generated class (commonly Type.OBJECT) 
76         @param flags The access flags for this class (ACC_PUBLIC, ACC_FINAL, ACC_SUPER, ACC_INTERFACE, and ACC_ABSTRACT)
77     */
78     public ClassGen(Type.Class thisType, Type.Class superType, int flags, Type.Class[] interfaces) {
79         if((flags & ~(ACC_PUBLIC|ACC_FINAL|ACC_SUPER|ACC_INTERFACE|ACC_ABSTRACT)) != 0)
80             throw new IllegalArgumentException("invalid flags");
81         this.thisType = thisType;
82         this.superType = superType;
83         this.interfaces = interfaces;
84         this.flags = flags;
85         this.minor = 3;
86         this.major = 45;
87         
88         cp = new CPGen();
89         attributes = new AttrGen(cp);
90     }
91     
92     /** Adds a new method to this class 
93         @param name The name of the method (not the signature, just the name)
94         @param ret The return type of the method
95         @param args The arguments to the method
96         @param flags The flags for the method
97                      (ACC_PUBLIC, ACC_PRIVATE, ACC_PROTECTED, ACC_STATIC, ACC_SYNCHRONIZED, ACC_NATIVE, ACC_ABSTRACT, ACC_STRICT)
98         @return A new MethodGen object for the method
99         @exception IllegalArgumentException if illegal flags are specified
100         @see MethodGen
101         @see CGConst
102     */
103     public final MethodGen addMethod(String name, Type ret, Type[] args, int flags) {
104         MethodGen mg = new MethodGen(this, name, ret, args, flags);
105         methods.addElement(mg);
106         return mg;
107     }
108     
109     /** Adds a new field to this class 
110         @param name The name of the filed (not the signature, just the name)
111         @param type The type of the field
112         @param flags The flags for the field
113         (ACC_PUBLIC, ACC_PRIVATE, ACC_PROTECTED, ACC_STATIC, ACC_FINAL, ACC_VOLATILE, ACC_TRANSIENT)
114         @return A new FieldGen object for the method
115         @exception IllegalArgumentException if illegal flags are specified
116         @see FieldGen
117         @see CGConst
118         */  
119     public final FieldGen addField(String name, Type type, int flags) {
120         FieldGen fg = new FieldGen(this, name, type, flags);
121         fields.addElement(fg);
122         return fg;
123     }
124     
125     /** Sets the source value of the SourceFile attribute of this class 
126         @param sourceFile The string to be uses as the SourceFile of this class
127     */
128     public void setSourceFile(String sourceFile) { this.sourceFile = sourceFile; }
129     
130     /** Writes the classfile data to the file specifed
131         @see ClassGen#dump(OutputStream)
132     */
133     public void dump(String file) throws IOException { dump(new File(file)); }
134     
135     /** Writes the classfile data to the file specified
136         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)
137         @see ClassGen#dump(OutputStream)
138     */
139     public void dump(File f) throws IOException {
140         if(f.isDirectory()) {
141             String[] a = thisType.components();
142             int i;
143             for(i=0;i<a.length-1;i++) {
144                 f = new File(f, a[i]);
145                 f.mkdir();
146             }
147             f = new File(f, a[i] + ".class");
148         }
149         OutputStream os = new FileOutputStream(f);
150         dump(os);
151         os.close();
152     }
153    
154     /** Writes the classfile data to the outputstream specified
155         @param os The stream to write the class to
156         @exception IOException if an IOException occures while writing the class data
157         @exception IllegalStateException if the data for a method is in an inconsistent state (required arguments missing, etc)
158         @exception Exn if the classfile could not be written for any other reason (constant pool full, etc)
159     */
160     public void dump(OutputStream os) throws IOException {
161         DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(os));
162         _dump(dos);
163         dos.flush();
164     }
165     
166     private void _dump(DataOutput o) throws IOException {
167         cp.optimize();
168         cp.stable();
169         
170         cp.add(thisType);
171         cp.add(superType);
172         if(interfaces != null) for(int i=0;i<interfaces.length;i++) cp.add(interfaces[i]);
173         if(sourceFile != null && !attributes.contains("SourceFile")) attributes.add("SourceFile", cp.addUtf8(sourceFile));
174                 
175         for(int i=0;i<methods.size();i++) ((MethodGen)methods.elementAt(i)).finish();
176         for(int i=0;i<fields.size();i++) ((FieldGen)fields.elementAt(i)).finish();
177         
178         cp.seal();
179         
180         o.writeInt(0xcafebabe); // magic
181         o.writeShort(minor); // minor_version
182         o.writeShort(major); // major_version
183         
184         cp.dump(o); // constant_pool
185         
186         o.writeShort(flags);
187         o.writeShort(cp.getIndex(thisType)); // this_class
188         o.writeShort(cp.getIndex(superType)); // super_class
189         
190         o.writeShort(interfaces==null ? 0 : interfaces.length); // interfaces_count
191         if(interfaces != null) for(int i=0;i<interfaces.length;i++) o.writeShort(cp.getIndex(interfaces[i])); // interfaces
192         
193         o.writeShort(fields.size()); // fields_count
194         for(int i=0;i<fields.size();i++) ((FieldGen)fields.elementAt(i)).dump(o); // fields
195
196         o.writeShort(methods.size()); // methods_count
197         for(int i=0;i<methods.size();i++) ((MethodGen)methods.elementAt(i)).dump(o); // methods
198         
199         o.writeShort(attributes.size()); // attributes_count
200         attributes.dump(o); // attributes        
201     }
202     
203     public ClassGen read(File f) throws ClassReadExn, IOException {
204         InputStream is = new FileInputStream(f);
205         ClassGen ret = read(is);
206         is.close();
207         return ret;
208     }
209     
210     public ClassGen read(InputStream is) throws ClassReadExn, IOException {
211         return new ClassGen(new DataInputStream(new BufferedInputStream(is)));
212     }
213
214     ClassGen(DataInput i) throws ClassReadExn, IOException {
215         int magic = i.readInt();
216         if (magic != 0xcafebabe) throw new ClassReadExn("invalid magic: " + Long.toString(0xffffffffL & magic, 16));
217         minor = i.readShort();
218         //if (minor != 3) throw new ClassReadExn("invalid minor version: " + minor);
219         major = i.readShort();
220         //if (major != 45 && major != 46) throw new ClassReadExn("invalid major version");
221         cp = new CPGen(i);
222         flags = i.readShort();
223         thisType = (Type.Class)cp.getType(i.readShort());
224         superType = (Type.Class)cp.getType(i.readShort());
225         interfaces = new Type.Class[i.readShort()];
226         for(int j=0; j<interfaces.length; j++) interfaces[j] = (Type.Class)cp.getType(i.readShort());
227         int numFields = i.readShort();
228         for(int j=0; j<numFields; j++) fields.add(new FieldGen(cp, i));
229         int numMethods = i.readShort();
230         for(int j=0; j<numMethods; j++) methods.add(new MethodGen(cp, i));
231         attributes = new AttrGen(cp, i);
232         sourceFile = (String)attributes.get("SourceFile");
233     }
234     
235     /** Thrown when class generation fails for a reason not under the control of the user
236         (IllegalStateExceptions are thrown in those cases */
237     public static class Exn extends RuntimeException {
238         public Exn(String s) { super(s); }
239     }
240     
241     public static class ClassReadExn extends IOException {
242         public ClassReadExn(String s) { super(s); }
243     }
244     
245     /** A class representing a field or method reference. This is used as an argument to the INVOKE*, GET*, and PUT* bytecodes
246         @see MethodRef
247         @see FieldRef
248         @see MethodRef.I
249         @see FieldRef
250     */
251     public static abstract class FieldOrMethodRef {
252         Type.Class klass;
253         String name;
254         String descriptor;
255         
256         FieldOrMethodRef(Type.Class klass, String name, String descriptor) { this.klass = klass; this.name = name; this.descriptor = descriptor; }
257         FieldOrMethodRef(FieldOrMethodRef o) { this.klass = o.klass; this.name = o.name; this.descriptor = o.descriptor; }
258         public boolean equals(Object o_) {
259             if(!(o_ instanceof FieldOrMethodRef)) return false;
260             FieldOrMethodRef o = (FieldOrMethodRef) o_;
261             return o.klass.equals(klass) && o.name.equals(name) && o.descriptor.equals(descriptor);
262         }
263         public int hashCode() { return klass.hashCode() ^ name.hashCode() ^ descriptor.hashCode(); }
264     }
265     
266     static class AttrGen {
267         private final CPGen cp;
268         private final Hashtable ht = new Hashtable();
269         
270         public AttrGen(CPGen cp) { this.cp = cp; }
271         public AttrGen(CPGen cp, DataInput in) throws IOException {
272             this(cp);
273             int size = in.readShort();
274             for(int i=0; i<size; i++) {
275                 String name = null;
276                 int idx = in.readShort();
277                 CPGen.Ent e = cp.getByIndex(idx);
278                 Object key = e.key();
279                 if (key instanceof String) name = (String)key;
280                 else name = ((Type)key).getDescriptor();
281
282                 int length = in.readInt();
283                 if (length==2) {   // FIXME might be wrong assumption
284                     ht.put(name, cp.getByIndex(in.readShort()));
285                 } else {
286                     byte[] buf = new byte[length];
287                     in.readFully(buf);
288                     ht.put(name, buf);
289                 }
290             }
291         }
292
293         public Object get(String s) {
294             Object ret = ht.get(s);
295             if (ret instanceof CPGen.Utf8Ent) return ((CPGen.Utf8Ent)ret).s;
296             return ret;
297         }
298         
299         public void add(String s, Object data) {
300             cp.addUtf8(s);
301             ht.put(s, data);
302         }
303         
304         public boolean contains(String s) { return ht.get(s) != null; }
305         
306         public int size() { return ht.size(); }
307         
308         public void dump(DataOutput o) throws IOException {
309             for(Enumeration e = ht.keys(); e.hasMoreElements();) {
310                 String name = (String) e.nextElement();
311                 Object val = ht.get(name);
312                 o.writeShort(cp.getUtf8Index(name));
313                 if(val instanceof byte[]) {
314                     byte[] buf = (byte[]) val;
315                     o.writeInt(buf.length);
316                     o.write(buf);
317                 } else if(val instanceof CPGen.Ent) {
318                     o.writeInt(2);
319                     o.writeShort(cp.getIndex((CPGen.Ent)val));
320                 } else {
321                     throw new Error("should never happen");
322                 }
323             }
324         }
325     }
326     
327     public static void main(String[] args) throws Exception {
328         if (args.length==1) {
329             if (args[0].endsWith(".class")) {
330                 System.out.println(new ClassGen(new DataInputStream(new FileInputStream(args[0]))));
331             } else {
332                 InputStream is = Class.forName(args[0]).getClassLoader().getResourceAsStream(args[0].replace('.', '/')+".class");
333                 System.out.println(new ClassGen(new DataInputStream(is)));
334             }
335         } else {
336             /*
337             Type.Class me = new Type.Class("Test");
338             ClassGen cg = new ClassGen("Test", "java.lang.Object", ACC_PUBLIC|ACC_SUPER|ACC_FINAL);
339             FieldGen fg = cg.addField("foo", Type.INT, ACC_PUBLIC|ACC_STATIC);
340         
341             MethodGen mg = cg.addMethod("main", Type.VOID, new Type[]{Type.arrayType(Type.STRING)}, ACC_STATIC|ACC_PUBLIC);
342             mg.setMaxLocals(1);
343             mg.addPushConst(0);
344             //mg.add(ISTORE_0);
345             mg.add(PUTSTATIC, fieldRef(me, "foo", Type.INT));
346             int top = mg.size();
347             mg.add(GETSTATIC, cg.fieldRef(new Type.Class("java.lang.System"), "out", new Type.Class("java.io.PrintStream")));
348             //mg.add(ILOAD_0);
349             mg.add(GETSTATIC, cg.fieldRef(me, "foo", Type.INT));
350             mg.add(INVOKEVIRTUAL, cg.methodRef(new Type.Class("java.io.PrintStream"), "println",
351                                                Type.VOID, new Type[]{Type.INT}));
352             //mg.add(IINC, new int[]{0, 1});
353             //mg.add(ILOAD_0);
354             mg.add(GETSTATIC, cg.fieldRef(me, "foo", Type.INT));
355             mg.addPushConst(1);
356             mg.add(IADD);
357             mg.add(DUP);
358             mg.add(PUTSTATIC, cg.fieldRef(me, "foo", Type.INT));       
359             mg.addPushConst(10);
360             mg.add(IF_ICMPLT, top);
361             mg.add(RETURN);
362             cg.dump("Test.class");
363             */
364         }
365     }
366 }