refactored tons of functionality into Class.Body and HasAttributes
[org.ibex.classgen.git] / src / org / ibex / classgen / Type.java
1 package org.ibex.classgen;
2
3 import java.util.StringTokenizer;
4 import java.util.Hashtable;
5
6 public abstract class Type implements CGConst {
7
8     private static Hashtable instances = new Hashtable();  // this has to appear at the top of the file
9
10     // Public API //////////////////////////////////////////////////////////////////////////////
11
12     public static final Type VOID = new Primitive("V", "void");
13     public static final Type INT = new Primitive("I", "int");
14     public static final Type LONG = new Primitive("J", "long");
15     public static final Type BOOLEAN = new Primitive("Z", "boolean");
16     public static final Type DOUBLE = new Primitive("D", "double");
17     public static final Type FLOAT = new Primitive("F", "float");
18     public static final Type BYTE = new Primitive("B", "byte");
19     public static final Type CHAR = new Primitive("C", "char");
20     public static final Type SHORT = new Primitive("S", "short");
21     
22     public static final Type.Class OBJECT = Type.Class.instance("java.lang.Object");
23     public static final Type.Class STRING = Type.Class.instance("java.lang.String");
24     public static final Type.Class STRINGBUFFER = Type.Class.instance("java.lang.StringBuffer");
25     public static final Type.Class INTEGER_OBJECT = Type.Class.instance("java.lang.Integer");
26     public static final Type.Class DOUBLE_OBJECT = Type.Class.instance("java.lang.Double");
27     public static final Type.Class FLOAT_OBJECT = Type.Class.instance("java.lang.Float");
28     
29     /** A zero element Type[] array (can be passed as the "args" param when a method takes no arguments */
30     public static final Type[] NO_ARGS = new Type[0];
31     
32     /** 
33      *  A "descriptor" is the classfile-mangled text representation of a type (see JLS section 4.3)
34      *  guarantee: there will only be one instance of Type for a given descriptor ==> equals() and == are interchangeable
35      */
36     public static Type fromDescriptor(String d) {
37         Type ret = (Type)instances.get(d);
38         if (ret != null) return ret;
39         if (d.startsWith("[")) return new Type.Array(Type.fromDescriptor(d.substring(1)));
40         return new Type.Class(d);
41     }
42
43     public final String  toString() { return super.toString(); }
44     public abstract String debugToString();
45     
46     public final String  getDescriptor() { return descriptor; }
47
48     public Type.Array  makeArray() { return (Type.Array)Type.fromDescriptor("["+descriptor); }
49     public Type.Array  makeArray(int i) { return i==0 ? (Type.Array)this : makeArray().makeArray(i-1); }
50
51     public Type.Ref    asRef()       { throw new RuntimeException("attempted to use "+this+" as a Type.Ref, which it is not"); }
52     public Type.Class  asClass()     { throw new RuntimeException("attempted to use "+this+" as a Type.Class, which it is not"); }
53     public Type.Array  asArray()     { throw new RuntimeException("attempted to use "+this+" as a Type.Array, which it is not"); }
54     public boolean     isPrimitive() { return false; }
55     public boolean     isRef()       { return false; }
56     public boolean     isClass()     { return false; }
57     public boolean     isArray()     { return false; }
58
59     // Protected/Private //////////////////////////////////////////////////////////////////////////////
60
61     protected final String descriptor;
62     
63     protected Type(String descriptor) {
64         this.descriptor = descriptor;
65         instances.put(descriptor, this);
66     }
67
68     public static class Primitive extends Type {
69         private String humanReadable;
70         Primitive(String descriptor, String humanReadable) {
71             super(descriptor);
72             this.humanReadable = humanReadable;
73         }
74         public String debugToString() { return humanReadable; }
75         public boolean     isPrimitive() { return true; }
76     }
77     
78     public abstract static class Ref extends Type {
79         protected Ref(String descriptor) { super(descriptor); }
80         public abstract String debugToString();
81         public    Type.Ref asRef() { return this; }
82         public    boolean  isRef() { return true; }
83     }
84
85     public static class Array extends Type.Ref {
86         public final Type base;
87         protected Array(Type t) { super("[" + t.getDescriptor()); base = t; }
88         public Type.Array asArray() { return this; }
89         public boolean isArray() { return true; }
90         public String debugToString() { return base.debugToString() + "[]"; }
91         public Type getElementType() { return Type.fromDescriptor(getDescriptor().substring(0, getDescriptor().length()-1)); }
92     }
93
94     public static class Class extends Type.Ref {
95         protected Class(String s) { super(_initHelper(s)); }
96         public Type.Class asClass() { return this; }
97         public boolean isClass() { return true; }
98         public static Type.Class instance(String className) {
99             return (Type.Class)Type.fromDescriptor("L"+className.replace('.', '/')+";"); }
100         //public boolean extendsOrImplements(Type.Class c, Context cx) { }
101         String internalForm() { return descriptor.substring(1, descriptor.length()-1); }
102         public String debugToString() { return internalForm().replace('/','.'); }
103         public String getShortName() {
104             int p = descriptor.lastIndexOf('/');
105             return p == -1 ? descriptor.substring(1,descriptor.length()-1) : descriptor.substring(p+1,descriptor.length()-1);
106         }
107         private static String _initHelper(String s) {
108             if (!s.startsWith("L") || !s.endsWith(";")) s = "L" + s.replace('.', '/') + ";";
109             return s;
110         }
111         String[] components() {
112             StringTokenizer st = new StringTokenizer(descriptor.substring(1, descriptor.length()-1), "/");
113             String[] a = new String[st.countTokens()];
114             for(int i=0;st.hasMoreTokens();i++) a[i] = st.nextToken();
115             return a;
116         }
117
118         public abstract class Body extends HasAttributes {
119             public Body(int flags, ClassFile.AttrGen attrs) {
120                 super(flags, attrs);
121                 if ((flags & ~(PUBLIC|FINAL|SUPER|INTERFACE|ABSTRACT)) != 0)
122                     throw new IllegalArgumentException("invalid flags: " + Integer.toString(flags,16));
123             }
124         }
125
126         public Field field(String name, Type type) { return new Field(name, type); }
127
128         public Method method(String name, Type returnType, Type[] argTypes) { return new Method(name, returnType, argTypes); }
129         public Method method(String leftCrap, String rightCrap) { return method(leftCrap+rightCrap); }
130
131         /** see JVM Spec section 2.10.2 */
132         public Method method(String signature) {
133             // FEATURE: This parser is ugly but it works (and shouldn't be a problem) might want to clean it up though
134             String name = signature.substring(0, signature.indexOf('('));
135             String s = signature.substring(signature.indexOf('('));
136             if(!s.startsWith("(")) throw new IllegalArgumentException("invalid method type descriptor");
137             int p = s.indexOf(')');
138             if(p == -1) throw new IllegalArgumentException("invalid method type descriptor");
139             String argsDesc = s.substring(1,p);
140             String retDesc = s.substring(p+1);
141             Type[] argsBuf = new Type[argsDesc.length()];
142             int i;
143             for(i=0,p=0;argsDesc.length() > 0;i++,p=0) {
144                 while(p < argsDesc.length() && argsDesc.charAt(p) == '[') p++;
145                 if(p == argsDesc.length())  throw new IllegalArgumentException("invalid method type descriptor");
146                 if(argsDesc.charAt(p) == 'L') {
147                     p = argsDesc.indexOf(';');
148                     if(p == -1) throw new IllegalArgumentException("invalid method type descriptor");
149                 }
150                 argsBuf[i] = Type.fromDescriptor(argsDesc.substring(0,p+1));
151                 argsDesc = argsDesc.substring(p+1);
152             }
153             Type args[] = new Type[i];
154             System.arraycopy(argsBuf,0,args,0,i);
155             return method(name, Type.fromDescriptor(retDesc), args);
156         }
157
158         public abstract class Member {
159             public final String name;
160             private Member(String name) { this.name = name; }
161             public Type.Class getDeclaringClass() { return Type.Class.this; }
162             public String getName() { return name; }
163             public abstract String getTypeDescriptor();
164             public abstract String debugToString();
165         }
166     
167         public class Field extends Member {
168             public final Type type;
169             private Field(String name, Type t) { super(name); this.type = t; }
170             public String getTypeDescriptor() { return type.getDescriptor(); }
171             public Type getType() { return type; }
172             public String debugToString() { return getDeclaringClass().debugToString()+"."+name+"["+type.debugToString()+"]"; }
173             public class Body extends HasAttributes {
174                 public Field getField() { return Field.this; }
175                 public Body(int flags, ClassFile.AttrGen attrs) {
176                     super(flags, attrs);
177                     if ((flags & ~VALID_FIELD_FLAGS) != 0) throw new IllegalArgumentException("invalid flags");
178                 }
179             }
180         }
181
182         public class Method extends Member {
183             final Type[] argTypes;
184             public final Type   returnType;
185             public Type getReturnType()   { return returnType; }
186             public int  getNumArgs()      { return argTypes.length; }
187             public Type getArgType(int i) { return argTypes[i]; }
188             public Type[] getArgTypes()   {
189                 Type[] ret = new Type[argTypes.length];
190                 System.arraycopy(argTypes, 0, ret, 0, ret.length);
191                 return ret;
192             }
193             public boolean isConstructor() { return getName().equals("<init>"); }
194             public boolean isClassInitializer() { return getName().equals("<clinit>"); }
195             public String debugToString() {
196                 StringBuffer sb = new StringBuffer();
197                 if (name.equals("<clinit>")) sb.append("static ");
198                 else {
199                     if (name.equals("<init>"))
200                         sb.append(Class.this.getShortName());
201                     else
202                         sb.append(returnType.debugToString()).append(".").append(name);
203                     sb.append("(");
204                     for(int i=0; i<argTypes.length; i++)
205                         sb.append((i==0?"":", ")+argTypes[i].debugToString());
206                     sb.append(") ");
207                 }
208                 return sb.toString();
209             }
210             private Method(String name, Type returnType, Type[] argTypes) {
211                 super(name);
212                 this.argTypes = argTypes;
213                 this.returnType = returnType;
214             }
215             //public Method.Body getBody(Context cx) { }
216             public String getTypeDescriptor() {
217                 StringBuffer sb = new StringBuffer(argTypes.length*4);
218                 sb.append("(");
219                 for(int i=0;i<argTypes.length;i++) sb.append(argTypes[i].getDescriptor());
220                 sb.append(")");
221                 sb.append(returnType.getDescriptor());
222                 return sb.toString();
223             }
224             public abstract class Body extends HasAttributes {
225                 public abstract java.util.Hashtable getThrownExceptions();
226                 public abstract void debugBodyToString(StringBuffer sb);
227                 public Body(int flags, ClassFile.AttrGen attrs) {
228                     super(flags, attrs);
229                     if ((flags & ~VALID_METHOD_FLAGS) != 0) throw new IllegalArgumentException("invalid flags");
230                 }
231                 public void debugToString(StringBuffer sb, String constructorName) {
232                     int flags = getFlags();
233                     sb.append("  ").append(ClassFile.flagsToString(flags,false));
234                     sb.append(Method.this.debugToString());
235                     java.util.Hashtable thrownExceptions = getThrownExceptions();
236                     if (thrownExceptions.size() > 0) {
237                         sb.append("throws");
238                         for(java.util.Enumeration e = thrownExceptions.keys();e.hasMoreElements();)
239                             sb.append(" ").append(((Type.Class)e.nextElement()).debugToString()).append(",");
240                         sb.setLength(sb.length()-1);
241                         sb.append(" ");
242                     }
243                     if ((flags & (NATIVE|ABSTRACT))==0) {
244                         sb.append("{\n");
245                         debugBodyToString(sb);
246                         sb.append("  }\n");
247                     } else {
248                         sb.append(";");
249                     }
250                 }
251             }
252         }
253     }
254     
255     // FEATURE: This probably isn't the best place for these
256     static String methodTypeDescriptor(Type[] argTypes, Type returnType) {
257         StringBuffer sb = new StringBuffer(argTypes.length*4);
258         sb.append("(");
259         for(int i=0;i<argTypes.length;i++) sb.append(argTypes[i].getDescriptor());
260         sb.append(")");
261         sb.append(returnType.getDescriptor());
262         return sb.toString();
263     }
264
265 }