lots of formatting, refactored out Type.fromArraySpec()
[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     public static final Type NULL = new Null();
22     
23     public static final Type.Class OBJECT = Type.Class.instance("java.lang.Object");
24     public static final Type.Class STRING = Type.Class.instance("java.lang.String");
25     public static final Type.Class STRINGBUFFER = Type.Class.instance("java.lang.StringBuffer");
26     public static final Type.Class INTEGER_OBJECT = Type.Class.instance("java.lang.Integer");
27     public static final Type.Class DOUBLE_OBJECT = Type.Class.instance("java.lang.Double");
28     public static final Type.Class FLOAT_OBJECT = Type.Class.instance("java.lang.Float");
29     
30     /** A zero element Type[] array (can be passed as the "args" param when a method takes no arguments */
31     public static final Type[] NO_ARGS = new Type[0];
32     
33     /** 
34      *  A "descriptor" is the classfile-mangled text representation of a type (see JLS section 4.3)
35      *  guarantee: there will only be one instance of Type for a given descriptor ==> equals() and == are interchangeable
36      */
37     public static Type fromDescriptor(String d) {
38         Type ret = (Type)instances.get(d);
39         if (ret != null) return ret;
40         if (d.startsWith("[")) return new Type.Array(Type.fromDescriptor(d.substring(1)));
41         return new Type.Class(d);
42     }
43
44     public final String  getDescriptor() { return descriptor; }
45
46     public Type.Array  makeArray() { return (Type.Array)Type.fromDescriptor("["+descriptor); }
47     public Type.Array  makeArray(int i) { return i==0 ? (Type.Array)this : makeArray().makeArray(i-1); }
48
49     public Type.Ref    asRef()       { throw new RuntimeException("attempted to use "+this+" as a Type.Ref, which it is not"); }
50     public Type.Class  asClass()     { throw new RuntimeException("attempted to use "+this+" as a Type.Class, which it is not"); }
51     public Type.Array  asArray()     { throw new RuntimeException("attempted to use "+this+" as a Type.Array, which it is not"); }
52     public boolean     isPrimitive() { return false; }
53     public boolean     isRef()       { return false; }
54     public boolean     isClass()     { return false; }
55     public boolean     isArray()     { return false; }
56
57     public static Type unify(Type t1, Type t2) {
58         if(t1 == Type.NULL) return t2;
59         if(t2 == Type.NULL) return t1;
60         if((t1 == Type.INT && t2 == Type.BOOLEAN) || (t2 == Type.INT & t1 == Type.BOOLEAN)) return Type.BOOLEAN;
61         if(t1 == t2) return t1;
62         // FIXME: This needs to do a lot more (subclasses, etc)
63         // it probably should be in Context.java
64         return null;
65     }
66
67     public static Type fromArraySpec(int i) {
68         switch(i) {
69             case 4: return Type.BOOLEAN;
70             case 5: return Type.CHAR;
71             case 6: return Type.FLOAT;
72             case 7: return Type.DOUBLE;
73             case 8: return Type.BYTE;
74             case 9: return Type.SHORT;
75             case 10: return Type.INT;
76             case 11: return Type.LONG;
77             default: throw new IllegalStateException("invalid array type");
78         }
79     }
80     
81     // Protected/Private //////////////////////////////////////////////////////////////////////////////
82
83     protected final String descriptor;
84     
85     protected Type(String descriptor) {
86         this.descriptor = descriptor;
87         instances.put(descriptor, this);
88     }
89     
90     public static class Null extends Type {
91         protected Null() { super(""); } // not really correct....
92     }
93
94     public static class Primitive extends Type {
95         private String humanReadable;
96         Primitive(String descriptor, String humanReadable) {
97             super(descriptor);
98             this.humanReadable = humanReadable;
99         }
100         public String toString() { return humanReadable; }
101         public boolean     isPrimitive() { return true; }
102     }
103     
104     public abstract static class Ref extends Type {
105         protected Ref(String descriptor) { super(descriptor); }
106         public abstract String toString();
107         public    Type.Ref asRef() { return this; }
108         public    boolean  isRef() { return true; }
109     }
110
111     public static class Array extends Type.Ref {
112         public final Type base;
113         protected Array(Type t) { super("[" + t.getDescriptor()); base = t; }
114         public Type.Array asArray() { return this; }
115         public boolean isArray() { return true; }
116         public String toString() { return base.toString() + "[]"; }
117         public Type getElementType() { return base; }
118     }
119
120     public static class Class extends Type.Ref {
121         protected Class(String s) { super(_initHelper(s)); }
122         public Type.Class asClass() { return this; }
123         public boolean isClass() { return true; }
124         public static Type.Class instance(String className) {
125             return (Type.Class)Type.fromDescriptor("L"+className.replace('.', '/')+";"); }
126         public boolean extendsOrImplements(Type.Class c, Context cx) {
127             if (this==c) return true;
128             if (this==OBJECT) return false;
129             ClassFile cf = cx.resolve(getName());
130             if (cf==null) {
131                 System.err.println("warning: could not resolve class " + getName());
132                 return false;
133             }
134             if (cf.superType == c) return true;
135             for(int i=0; i<cf.interfaces.length; i++) if (cf.interfaces[i].extendsOrImplements(c,cx)) return true;
136             if (cf.superType == null) return false;
137             return cf.superType.extendsOrImplements(c, cx);
138         }
139         String internalForm() { return descriptor.substring(1, descriptor.length()-1); }
140         public String toString() { return internalForm().replace('/','.'); }
141         public String getName() { return internalForm().replace('/','.'); }
142         public String getShortName() {
143             int p = descriptor.lastIndexOf('/');
144             return p == -1 ? descriptor.substring(1,descriptor.length()-1) : descriptor.substring(p+1,descriptor.length()-1);
145         }
146         private static String _initHelper(String s) {
147             if (!s.startsWith("L") || !s.endsWith(";")) throw new Error("invalid: " + s);
148             return s;
149         }
150         String[] components() {
151             StringTokenizer st = new StringTokenizer(descriptor.substring(1, descriptor.length()-1), "/");
152             String[] a = new String[st.countTokens()];
153             for(int i=0;st.hasMoreTokens();i++) a[i] = st.nextToken();
154             return a;
155         }
156
157         public Type.Class.Body getBody(Context cx) { return cx.resolve(this.getName()); }
158         public abstract class Body extends HasAttributes {
159             public abstract Type.Class.Method.Body[] methods();
160             public abstract Type.Class.Field.Body[] fields();
161             public Body(int flags, ClassFile.AttrGen attrs) {
162                 super(flags, attrs);
163                 if ((flags & ~(PUBLIC|FINAL|SUPER|INTERFACE|ABSTRACT)) != 0)
164                     throw new IllegalArgumentException("invalid flags: " + Integer.toString(flags,16));
165             }
166         }
167
168         public Field field(String name, Type type) { return new Field(name, type); }
169         public Field field(String name, String descriptor) { return field(name,Type.fromDescriptor(descriptor)); }
170
171         public Method method(String name, Type returnType, Type[] argTypes) { return new Method(name, returnType, argTypes); }
172
173         /** see JVM Spec section 2.10.2 */
174         public Method method(String name, String descriptor) {
175             // FEATURE: This parser is ugly but it works (and shouldn't be a problem) might want to clean it up though
176             String s = descriptor;
177             if(!s.startsWith("(")) throw new IllegalArgumentException("invalid method type descriptor");
178             int p = s.indexOf(')');
179             if(p == -1) throw new IllegalArgumentException("invalid method type descriptor");
180             String argsDesc = s.substring(1,p);
181             String retDesc = s.substring(p+1);
182             Type[] argsBuf = new Type[argsDesc.length()];
183             int i;
184             for(i=0,p=0;argsDesc.length() > 0;i++,p=0) {
185                 while(p < argsDesc.length() && argsDesc.charAt(p) == '[') p++;
186                 if(p == argsDesc.length())  throw new IllegalArgumentException("invalid method type descriptor");
187                 if(argsDesc.charAt(p) == 'L') {
188                     p = argsDesc.indexOf(';');
189                     if(p == -1) throw new IllegalArgumentException("invalid method type descriptor");
190                 }
191                 argsBuf[i] = Type.fromDescriptor(argsDesc.substring(0,p+1));
192                 argsDesc = argsDesc.substring(p+1);
193             }
194             Type args[] = new Type[i];
195             System.arraycopy(argsBuf,0,args,0,i);
196             return method(name, Type.fromDescriptor(retDesc), args);
197         }
198
199         public abstract class Member {
200             public final String name;
201             private Member(String name) { this.name = name; }
202             public Type.Class getDeclaringClass() { return Type.Class.this; }
203             public String getName() { return name; }
204             public abstract String getTypeDescriptor();
205             public abstract String toString();
206             public abstract int hashCode();
207             public abstract boolean equals(Object o);
208         }
209     
210         public class Field extends Member {
211             public final Type type;
212             private Field(String name, Type t) { super(name); this.type = t; }
213             public String getTypeDescriptor() { return type.getDescriptor(); }
214             public Type getType() { return type; }
215             public String toString() { return getDeclaringClass().toString()+"."+name+"["+type.toString()+"]"; }
216             public class Body extends HasAttributes {
217                 public Field getField() { return Field.this; }
218                 public Body(int flags, ClassFile.AttrGen attrs) {
219                     super(flags, attrs);
220                     if ((flags & ~VALID_FIELD_FLAGS) != 0) throw new IllegalArgumentException("invalid flags");
221                 }
222             }
223             public int hashCode() {
224                 return type.hashCode() ^ name.hashCode() ^ getDeclaringClass().hashCode();
225             }
226             public boolean equals(Object o_) {
227                 if(o_ == this) return true;
228                 if(!(o_ instanceof Field)) return false;
229                 Field o = (Field) o_;
230                 return o.getDeclaringClass() == getDeclaringClass() && o.type == type && o.name.equals(name);
231             }
232         }
233
234         public class Method extends Member {
235             final Type[] argTypes;
236             public final Type   returnType;
237             public Type getReturnType()   { return returnType; }
238             public int  getNumArgs()      { return argTypes.length; }
239             public Type getArgType(int i) { return argTypes[i]; }
240             public Type[] getArgTypes()   {
241                 Type[] ret = new Type[argTypes.length];
242                 System.arraycopy(argTypes, 0, ret, 0, ret.length);
243                 return ret;
244             }
245             public boolean isConstructor() { return getName().equals("<init>"); }
246             public boolean isClassInitializer() { return getName().equals("<clinit>"); }
247             
248             public String toString() {
249                 StringBuffer sb = new StringBuffer();
250                 if (name.equals("<clinit>")) sb.append("static ");
251                 else {
252                     if (name.equals("<init>"))
253                         sb.append(Class.this.getShortName());
254                     else
255                         sb.append(returnType.toString()).append(" ").append(name);
256                     sb.append("(");
257                     for(int i=0; i<argTypes.length; i++)
258                         sb.append((i==0?"":", ")+argTypes[i].toString());
259                     sb.append(") ");
260                 }
261                 return sb.toString();
262             }
263             private Method(String name, Type returnType, Type[] argTypes) {
264                 super(name);
265                 this.argTypes = argTypes;
266                 this.returnType = returnType;
267             }
268             //public Method.Body getBody(Context cx) { }
269             public String getTypeDescriptor() {
270                 StringBuffer sb = new StringBuffer(argTypes.length*4);
271                 sb.append("(");
272                 for(int i=0;i<argTypes.length;i++) sb.append(argTypes[i].getDescriptor());
273                 sb.append(")");
274                 sb.append(returnType.getDescriptor());
275                 return sb.toString();
276             }
277             public abstract class Body extends HasAttributes {
278                 public abstract java.util.Hashtable getThrownExceptions();
279                 public abstract void debugBodyToString(StringBuffer sb);
280                 public Method getMethod() { return Method.this; }
281                 public Body(int flags, ClassFile.AttrGen attrs) {
282                     super(flags, attrs);
283                     if ((flags & ~VALID_METHOD_FLAGS) != 0) throw new IllegalArgumentException("invalid flags");
284                 }
285                 public boolean isConcrete() { return !isAbstract() && !isNative() /*FIXME: !inAnInterface*/; }
286                 public void toString(StringBuffer sb, String constructorName) {
287                     int flags = getFlags();
288                     sb.append("  ").append(ClassFile.flagsToString(flags,false));
289                     sb.append(Method.this.toString());
290                     java.util.Hashtable thrownExceptions = getThrownExceptions();
291                     if (thrownExceptions.size() > 0) {
292                         sb.append("throws");
293                         for(java.util.Enumeration e = thrownExceptions.keys();e.hasMoreElements();)
294                             sb.append(" ").append(((Type.Class)e.nextElement()).toString()).append(",");
295                         sb.setLength(sb.length()-1);
296                         sb.append(" ");
297                     }
298                     if ((flags & (NATIVE|ABSTRACT))==0) {
299                         sb.append("{\n");
300                         debugBodyToString(sb);
301                         sb.append("  }\n");
302                     } else {
303                         sb.append(";");
304                     }
305                 }
306             }
307             public int hashCode() {
308                 int h = returnType.hashCode() ^ name.hashCode() ^ getDeclaringClass().hashCode();
309                 for(int i=0;i<argTypes.length;i++) h ^= argTypes[i].hashCode();
310                 return h;
311             }
312             public boolean equals(Object o_) {
313                 if(o_ == this) return true;
314                 if(!(o_ instanceof Method)) return false;
315                 Method o = (Method) o_;
316                 if(!(o.getDeclaringClass() == getDeclaringClass() && o.returnType == returnType && o.name.equals(name))) return false;
317                 if(o.argTypes.length != argTypes.length) return false;
318                 for(int i=0;i<argTypes.length;i++)
319                     if(o.argTypes[i] != argTypes[i]) return false;
320                 return true;
321             }
322         }
323     }
324     
325     // FEATURE: This probably isn't the best place for these
326     static String methodTypeDescriptor(Type[] argTypes, Type returnType) {
327         StringBuffer sb = new StringBuffer(argTypes.length*4);
328         sb.append("(");
329         for(int i=0;i<argTypes.length;i++) sb.append(argTypes[i].getDescriptor());
330         sb.append(")");
331         sb.append(returnType.getDescriptor());
332         return sb.toString();
333     }
334
335 }