ClassFile.addMethod(Method, int)
[org.ibex.classgen.git] / src / org / ibex / classgen / ClassFile.java
index 6be6bfa..9682150 100644 (file)
@@ -4,48 +4,59 @@ import java.util.*;
 import java.io.*;
 
 /** Class generation object representing the whole classfile */
-public class ClassFile implements CGConst {
+public class ClassFile extends Type.Class.Body {
     private final Type.Class thisType;
-    private final Type.Class superType;
-    private final Type.Class[] interfaces;
-    private short minor;
-    private short major;
-    final int flags;
+    final Type.Class superType;
+    final Type.Class[] interfaces;
+    private final short minor;
+    private final short major;
     
-    private String sourceFile; 
     private final Vector fields = new Vector();
     private final Vector methods = new Vector();
-    
-    final CPGen cp;
-    private final AttrGen attributes;
 
-    public static String flagsToString(int flags) {
-        String ret = "";
-        if ((flags & ACC_PUBLIC) != 0)       ret += "public ";
-        if ((flags & ACC_PRIVATE) != 0)      ret += "private ";
-        if ((flags & ACC_PROTECTED) != 0)    ret += "protected ";
-        if ((flags & ACC_STATIC) != 0)       ret += "static ";
-        if ((flags & ACC_FINAL) != 0)        ret += "final ";
-        if ((flags & ACC_ABSTRACT) != 0)     ret += "abstract ";
-        if ((flags & ACC_SYNCHRONIZED) != 0) ret += "synchronized ";
-        if ((flags & ACC_NATIVE) != 0)       ret += "native ";
-        if ((flags & ACC_STRICT) != 0)       ret += "strictfp ";
-        if ((flags & ACC_VOLATILE) != 0)     ret += "volatile ";
-        if ((flags & ACC_TRANSIENT) != 0)    ret += "transient ";
+    public Type.Class.Method.Body[] methods() {
+        Type.Class.Method.Body[] ret = new Type.Class.Method.Body[methods.size()];
+        methods.copyInto(ret);
+        return ret;
+    }
+
+    public Type.Class.Field.Body[] fields() {
+        Type.Class.Field.Body[] ret = new Type.Class.Field.Body[fields.size()];
+        fields.copyInto(ret);
         return ret;
     }
-  
-    public String toString() { StringBuffer sb = new StringBuffer(); toString(sb); return sb.toString(); }
-    public void   toString(StringBuffer sb) {
-        sb.append(flagsToString(flags));
-        sb.append((flags & ACC_INTERFACE) != 0 ? "interface " : "class ");
-        sb.append(thisType);
-        if (superType != null) sb.append(" extends " + superType);
+    
+    static String flagsToString(int flags, boolean isClass) {
+        StringBuffer sb = new StringBuffer(32);
+        if ((flags & PUBLIC) != 0)       sb.append("public ");
+        if ((flags & PRIVATE) != 0)      sb.append("private ");
+        if ((flags & PROTECTED) != 0)    sb.append("protected ");
+        if ((flags & STATIC) != 0)       sb.append("static ");
+        if ((flags & FINAL) != 0)        sb.append("final ");
+        if ((flags & ABSTRACT) != 0)     sb.append("abstract ");
+        if (!isClass && (flags & SYNCHRONIZED) != 0) sb.append("synchronized ");
+        if (!isClass && (flags & NATIVE) != 0)       sb.append("native ");
+        if (!isClass && (flags & STRICT) != 0)       sb.append("strictfp ");
+        if (!isClass && (flags & VOLATILE) != 0)     sb.append("volatile ");
+        if (!isClass && (flags & TRANSIENT) != 0)    sb.append("transient ");
+        return sb.toString();
+    }
+
+    public Type.Class getType() { return thisType; }
+    public int getFlags() { return flags; }
+    
+    public String toString() { return toString(new StringBuffer(4096)).toString(); }
+    StringBuffer toString(StringBuffer sb) {
+        sb.append(flagsToString(flags,true));
+        sb.append((flags & INTERFACE) != 0 ? "interface " : "class ");
+        sb.append(thisType.toString());
+        if (superType != null) sb.append(" extends " + superType.toString());
         if (interfaces != null && interfaces.length > 0) sb.append(" implements");
-        for(int i=0; i<interfaces.length; i++) sb.append((i==0?" ":", ")+interfaces[i]);
+        for(int i=0; i<interfaces.length; i++) sb.append((i==0?" ":", ")+interfaces[i].toString());
         sb.append(" {");
-        sb.append(" // [jcf v"+major+"."+minor+"]");
-        if (sourceFile != null) sb.append(" from " + sourceFile);
+        sb.append(" // v"+major+"."+minor);
+        ConstantPool.Utf8Key sourceFile = (ConstantPool.Utf8Key) attrs.get("SourceFile");
+        if (sourceFile != null) sb.append(" from " + sourceFile.s);
         sb.append("\n");
         for(int i=0; i<fields.size(); i++) {
             sb.append("  ");
@@ -53,40 +64,21 @@ public class ClassFile implements CGConst {
             sb.append("\n");
         }
         for(int i=0; i<methods.size(); i++) {
-            sb.append("  ");
-            ((MethodGen)methods.elementAt(i)).toString(sb, thisType.getShortName());
+            ((MethodGen)methods.elementAt(i)).toString(sb,thisType.getShortName());
             sb.append("\n");
         }
         sb.append("}");
+        return sb;
     }
 
-    /** @see #ClassFile(Type.Class, Type.Class, int) */
-    public ClassFile(String name, String superName, int flags) {
-        this(Type.instance(name).asClass(), Type.instance(superName).asClass(), flags);
-    }
-
-    /** @see #ClassFile(Type.Class, Type.Class, int, Type.Class[]) */
-    public ClassFile(Type.Class thisType, Type.Class superType, int flags) {
-        this(thisType, superType, flags, null);
-    }
-    
-    /** Creates a new ClassFile object 
-        @param thisType The type of the class to generate
-        @param superType The superclass of the generated class (commonly Type.OBJECT) 
-        @param flags The access flags for this class (ACC_PUBLIC, ACC_FINAL, ACC_SUPER, ACC_INTERFACE, and ACC_ABSTRACT)
-    */
+    public ClassFile(Type.Class thisType, Type.Class superType, int flags) { this(thisType, superType, flags, null); }
     public ClassFile(Type.Class thisType, Type.Class superType, int flags, Type.Class[] interfaces) {
-        if((flags & ~(ACC_PUBLIC|ACC_FINAL|ACC_SUPER|ACC_INTERFACE|ACC_ABSTRACT)) != 0)
-            throw new IllegalArgumentException("invalid flags");
+        thisType.super(flags, new AttrGen());
         this.thisType = thisType;
         this.superType = superType;
         this.interfaces = interfaces;
-        this.flags = flags;
         this.minor = 3;
-        this.major = 45;
-        
-        cp = new CPGen();
-        attributes = new AttrGen(cp);
+        this.major = 45;        
     }
     
     /** Adds a new method to this class 
@@ -94,14 +86,22 @@ public class ClassFile implements CGConst {
         @param ret The return type of the method
         @param args The arguments to the method
         @param flags The flags for the method
-                     (ACC_PUBLIC, ACC_PRIVATE, ACC_PROTECTED, ACC_STATIC, ACC_SYNCHRONIZED, ACC_NATIVE, ACC_ABSTRACT, ACC_STRICT)
+                     (PUBLIC, PRIVATE, PROTECTED, STATIC, SYNCHRONIZED, NATIVE, ABSTRACT, STRICT)
         @return A new MethodGen object for the method
         @exception IllegalArgumentException if illegal flags are specified
         @see MethodGen
         @see CGConst
     */
     public final MethodGen addMethod(String name, Type ret, Type[] args, int flags) {
-        MethodGen mg = new MethodGen(this, name, ret, args, flags);
+        return addMethod(getType().method(name, ret, args),flags);
+    }
+    public final MethodGen addMethod(Type.Class.Method method,int flags) {
+        MethodGen mg = new MethodGen(method, flags);
+        methods.addElement(mg);
+        return mg;
+    }
+    public final MethodGen addMethod(Type.Class.Method m, int flags) {
+        MethodGen mg = new MethodGen(m, flags);
         methods.addElement(mg);
         return mg;
     }
@@ -110,14 +110,17 @@ public class ClassFile implements CGConst {
         @param name The name of the filed (not the signature, just the name)
         @param type The type of the field
         @param flags The flags for the field
-        (ACC_PUBLIC, ACC_PRIVATE, ACC_PROTECTED, ACC_STATIC, ACC_FINAL, ACC_VOLATILE, ACC_TRANSIENT)
+        (PUBLIC, PRIVATE, PROTECTED, STATIC, FINAL, VOLATILE, TRANSIENT)
         @return A new FieldGen object for the method
         @exception IllegalArgumentException if illegal flags are specified
         @see FieldGen
         @see CGConst
         */  
     public final FieldGen addField(String name, Type type, int flags) {
-        FieldGen fg = new FieldGen(this, name, type, flags);
+        return addField(getType().field(name,type),flags);
+    }
+    public final FieldGen addField(Type.Class.Field field, int flags) {
+        FieldGen fg = new FieldGen(field , flags);
         fields.addElement(fg);
         return fg;
     }
@@ -125,7 +128,7 @@ public class ClassFile implements CGConst {
     /** Sets the source value of the SourceFile attribute of this class 
         @param sourceFile The string to be uses as the SourceFile of this class
     */
-    public void setSourceFile(String sourceFile) { this.sourceFile = sourceFile; }
+    public void setSourceFile(String sourceFile) { attrs.put("SourceFile", new ConstantPool.Utf8Key(sourceFile)); }
     
     /** Writes the classfile data to the file specifed
         @see ClassFile#dump(OutputStream)
@@ -164,17 +167,15 @@ public class ClassFile implements CGConst {
     }
     
     private void _dump(DataOutput o) throws IOException {
-        cp.optimize();
-        cp.stable();
-        
+        ConstantPool cp = new ConstantPool();
         cp.add(thisType);
         cp.add(superType);
         if(interfaces != null) for(int i=0;i<interfaces.length;i++) cp.add(interfaces[i]);
-        if(sourceFile != null && !attributes.contains("SourceFile")) attributes.add("SourceFile", cp.addUtf8(sourceFile));
-                
-        for(int i=0;i<methods.size();i++) ((MethodGen)methods.elementAt(i)).finish();
-        for(int i=0;i<fields.size();i++) ((FieldGen)fields.elementAt(i)).finish();
+        for(int i=0;i<methods.size();i++) ((MethodGen)methods.elementAt(i)).finish(cp);
+        for(int i=0;i<fields.size();i++) ((FieldGen)fields.elementAt(i)).finish(cp);
+        attrs.finish(cp);
         
+        cp.optimize();
         cp.seal();
         
         o.writeInt(0xcafebabe); // magic
@@ -191,49 +192,66 @@ public class ClassFile implements CGConst {
         if(interfaces != null) for(int i=0;i<interfaces.length;i++) o.writeShort(cp.getIndex(interfaces[i])); // interfaces
         
         o.writeShort(fields.size()); // fields_count
-        for(int i=0;i<fields.size();i++) ((FieldGen)fields.elementAt(i)).dump(o); // fields
+        for(int i=0;i<fields.size();i++) ((FieldGen)fields.elementAt(i)).dump(o,cp); // fields
 
         o.writeShort(methods.size()); // methods_count
-        for(int i=0;i<methods.size();i++) ((MethodGen)methods.elementAt(i)).dump(o); // methods
+        for(int i=0;i<methods.size();i++) ((MethodGen)methods.elementAt(i)).dump(o,cp); // methods
         
-        o.writeShort(attributes.size()); // attributes_count
-        attributes.dump(o); // attributes        
+        attrs.dump(o,cp); // attributes        
     }
     
-    public ClassFile read(File f) throws ClassReadExn, IOException {
+    public static ClassFile read(String s) throws IOException { return read(new File(s)); }
+    public static ClassFile read(File f) throws ClassReadExn, IOException {
         InputStream is = new FileInputStream(f);
         ClassFile ret = read(is);
         is.close();
         return ret;
     }
     
-    public ClassFile read(InputStream is) throws ClassReadExn, IOException {
-        return new ClassFile(new DataInputStream(new BufferedInputStream(is)));
+    public static ClassFile read(InputStream is) throws ClassReadExn, IOException {
+        try {
+            return new ClassFile(new DataInputStream(new BufferedInputStream(is)));
+        } catch(RuntimeException e) {
+            e.printStackTrace();
+            throw new ClassReadExn("invalid constant pool entry");
+        }
     }
 
-    ClassFile(DataInput i) throws ClassReadExn, IOException {
-        int magic = i.readInt();
+    public ClassFile(DataInput i) throws IOException { this(i, false); }
+    public ClassFile(DataInput i, boolean ssa) throws IOException {
+        this(i.readInt(), i.readShort(), i.readShort(), new ConstantPool(i), i.readShort(), i, ssa);
+    }
+    private ClassFile(int magic, short minor, short major, ConstantPool cp,
+                      short flags, DataInput i, boolean ssa) throws IOException {
+        this(magic, minor, major, cp, flags, (Type.Class)cp.getKeyByIndex(i.readShort()), i, ssa);
+    }
+    private ClassFile(int magic, short minor, short major, ConstantPool cp, short flags,
+                      Type.Class thisType, DataInput i, boolean ssa) throws IOException {
+        thisType.super(flags, null);
         if (magic != 0xcafebabe) throw new ClassReadExn("invalid magic: " + Long.toString(0xffffffffL & magic, 16));
-        minor = i.readShort();
-        //if (minor != 3) throw new ClassReadExn("invalid minor version: " + minor);
-        major = i.readShort();
-        //if (major != 45 && major != 46) throw new ClassReadExn("invalid major version");
-        cp = new CPGen(i);
-        flags = i.readShort();
-        thisType = (Type.Class)cp.getType(i.readShort());
-        superType = (Type.Class)cp.getType(i.readShort());
+        this.minor = minor;
+        this.major = major;
+        this.thisType = thisType;
+        superType = (Type.Class) cp.getKeyByIndex(i.readShort());
         interfaces = new Type.Class[i.readShort()];
-        for(int j=0; j<interfaces.length; j++) interfaces[j] = (Type.Class)cp.getType(i.readShort());
+        for(int j=0; j<interfaces.length; j++) interfaces[j] = (Type.Class) cp.getKeyByIndex(i.readShort());
         int numFields = i.readShort();
-        for(int j=0; j<numFields; j++) fields.add(new FieldGen(cp, i));
+        for(int j=0; j<numFields; j++) fields.addElement(new FieldGen(this.getType(), i, cp));
         int numMethods = i.readShort();
-        for(int j=0; j<numMethods; j++) methods.add(new MethodGen(cp, i));
-        attributes = new AttrGen(cp, i);
-        sourceFile = (String)attributes.get("SourceFile");
+        for(int j=0; j<numMethods; j++) methods.addElement(ssa 
+                                                           ? new JSSA(this.getType(), i, cp) 
+                                                           : new MethodGen(this.getType(), i, cp));
+        readAttributes(i, cp);
+        
+        // FEATURE: Support these
+        // NOTE: Until we can support them properly we HAVE to delete them,
+        //       they'll be incorrect after we rewrite the constant pool, etc
+        attrs.remove("InnerClasses");
     }
     
     /** Thrown when class generation fails for a reason not under the control of the user
         (IllegalStateExceptions are thrown in those cases */
+    // FEATURE: This should probably be a checked exception
     public static class Exn extends RuntimeException {
         public Exn(String s) { super(s); }
     }
@@ -243,24 +261,16 @@ public class ClassFile implements CGConst {
     }
     
     static class AttrGen {
-        private final CPGen cp;
         private final Hashtable ht = new Hashtable();
         
-        public AttrGen(CPGen cp) { this.cp = cp; }
-        public AttrGen(CPGen cp, DataInput in) throws IOException {
-            this(cp);
+        AttrGen() { }
+        AttrGen(DataInput in, ConstantPool cp) throws IOException {
             int size = in.readShort();
             for(int i=0; i<size; i++) {
-                String name = null;
-                int idx = in.readShort();
-                CPGen.Ent e = cp.getByIndex(idx);
-                Object key = e.key();
-                if (key instanceof String) name = (String)key;
-                else name = ((Type)key).getDescriptor();
-
+                String name = cp.getUtf8KeyByIndex(in.readUnsignedShort());
                 int length = in.readInt();
-                if (length==2) {   // FIXME might be wrong assumption
-                    ht.put(name, cp.getByIndex(in.readShort()));
+                if ((name.equals("SourceFile")||name.equals("ConstantValue")) && length == 2) {
+                    ht.put(name, cp.getKeyByIndex(in.readUnsignedShort()));
                 } else {
                     byte[] buf = new byte[length];
                     in.readFully(buf);
@@ -269,22 +279,23 @@ public class ClassFile implements CGConst {
             }
         }
 
-        public Object get(String s) {
-            Object ret = ht.get(s);
-            if (ret instanceof CPGen.Utf8Ent) return ((CPGen.Utf8Ent)ret).s;
-            return ret;
-        }
-        
-        public void add(String s, Object data) {
-            cp.addUtf8(s);
-            ht.put(s, data);
-        }
-        
+        public Object get(String s) { return ht.get(s); }
+        public void put(String s, Object data) { ht.put(s, data); }
         public boolean contains(String s) { return ht.get(s) != null; }
-        
+        public void remove(String s) { ht.remove(s); }
         public int size() { return ht.size(); }
         
-        public void dump(DataOutput o) throws IOException {
+        void finish(ConstantPool cp) {
+            for(Enumeration e = ht.keys(); e.hasMoreElements();) {
+                String name = (String) e.nextElement();
+                Object val = ht.get(name);
+                cp.addUtf8(name);
+                if(!(val instanceof byte[])) cp.add(val);
+            }
+        }
+        
+        void dump(DataOutput o, ConstantPool cp) throws IOException {
+            o.writeShort(size());
             for(Enumeration e = ht.keys(); e.hasMoreElements();) {
                 String name = (String) e.nextElement();
                 Object val = ht.get(name);
@@ -293,31 +304,37 @@ public class ClassFile implements CGConst {
                     byte[] buf = (byte[]) val;
                     o.writeInt(buf.length);
                     o.write(buf);
-                } else if(val instanceof CPGen.Ent) {
-                    o.writeInt(2);
-                    o.writeShort(cp.getIndex((CPGen.Ent)val));
                 } else {
-                    throw new Error("should never happen");
+                    o.writeInt(2);
+                    o.writeShort(cp.getIndex(val));
                 }
             }
         }
     }
     
     public static void main(String[] args) throws Exception {
-        if (args.length==1) {
+        if(args.length >= 2 && args[0].equals("copyto")) {
+            File dest = new File(args[1]);
+            dest.mkdirs();
+            for(int i=2;i<args.length;i++) {
+                System.err.println("Copying " + args[i]);
+                read(args[i]).dump(dest);
+            }
+        }
+        else if (args.length==1) {
             if (args[0].endsWith(".class")) {
-                System.out.println(new ClassFile(new DataInputStream(new FileInputStream(args[0]))));
+                System.out.println(new ClassFile(new DataInputStream(new FileInputStream(args[0]))).toString());
             } else {
                 InputStream is = Class.forName(args[0]).getClassLoader().getResourceAsStream(args[0].replace('.', '/')+".class");
-                System.out.println(new ClassFile(new DataInputStream(is)));
+                System.out.println(new ClassFile(new DataInputStream(is)).toString());
             }
         } else {
             /*
             Type.Class me = new Type.Class("Test");
-            ClassFile cg = new ClassFile("Test", "java.lang.Object", ACC_PUBLIC|ACC_SUPER|ACC_FINAL);
-            FieldGen fg = cg.addField("foo", Type.INT, ACC_PUBLIC|ACC_STATIC);
+            ClassFile cg = new ClassFile("Test", "java.lang.Object", PUBLIC|SUPER|FINAL);
+            FieldGen fg = cg.addField("foo", Type.INT, PUBLIC|STATIC);
         
-            MethodGen mg = cg.addMethod("main", Type.VOID, new Type[]{Type.arrayType(Type.STRING)}, ACC_STATIC|ACC_PUBLIC);
+            MethodGen mg = cg.addMethod("main", Type.VOID, new Type[]{Type.arrayType(Type.STRING)}, STATIC|PUBLIC);
             mg.setMaxLocals(1);
             mg.addPushConst(0);
             //mg.add(ISTORE_0);