allow Type.Primitive as an arg to NEWARRAY
[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", 10);
14     public static final Type LONG = new Primitive("J", "long", 11);
15     public static final Type BOOLEAN = new Primitive("Z", "boolean", 4);
16     public static final Type DOUBLE = new Primitive("D", "double", 7);
17     public static final Type FLOAT = new Primitive("F", "float", 6);
18     public static final Type BYTE = new Primitive("B", "byte", 8);
19     public static final Type CHAR = new Primitive("C", "char", 5);
20     public static final Type SHORT = new Primitive("S", "short", 9);
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         private int arraySpec;
97         Primitive(String descriptor, String humanReadable) { this(descriptor, humanReadable, -1); }
98         Primitive(String descriptor, String humanReadable, int arraySpec) {
99             super(descriptor);
100             this.humanReadable = humanReadable;
101             this.arraySpec = arraySpec;
102         }
103         public String toString() { return humanReadable; }
104         public boolean     isPrimitive() { return true; }
105         public int toArraySpec() {
106             if (arraySpec < 0) throw new Error("you can't make arrays of " + this);
107             return arraySpec;
108         }
109     }
110     
111     public abstract static class Ref extends Type {
112         protected Ref(String descriptor) { super(descriptor); }
113         public abstract String toString();
114         public    Type.Ref asRef() { return this; }
115         public    boolean  isRef() { return true; }
116         abstract String internalForm();
117     }
118
119     public static class Array extends Type.Ref {
120         public final Type base;
121         protected Array(Type t) { super("[" + t.getDescriptor()); base = t; }
122         public Type.Array asArray() { return this; }
123         public boolean isArray() { return true; }
124         public String toString() { return base.toString() + "[]"; }
125         public Type getElementType() { return base; }
126         String internalForm() { return getDescriptor(); }
127     }
128
129     public static class Class extends Type.Ref {
130         protected Class(String s) { super(_initHelper(s)); }
131         public Type.Class asClass() { return this; }
132         public boolean isClass() { return true; }
133         public static Type.Class instance(String className) {
134             return (Type.Class)Type.fromDescriptor("L"+className.replace('.', '/')+";"); }
135         public boolean extendsOrImplements(Type.Class c, Context cx) {
136             if (this==c) return true;
137             if (this==OBJECT) return false;
138             ClassFile cf = cx.resolve(getName());
139             if (cf==null) {
140                 System.err.println("warning: could not resolve class " + getName());
141                 return false;
142             }
143             if (cf.superType == c) return true;
144             for(int i=0; i<cf.interfaces.length; i++) if (cf.interfaces[i].extendsOrImplements(c,cx)) return true;
145             if (cf.superType == null) return false;
146             return cf.superType.extendsOrImplements(c, cx);
147         }
148         String internalForm() { return descriptor.substring(1, descriptor.length()-1); }
149         public String toString() { return internalForm().replace('/','.'); }
150         public String getName() { return internalForm().replace('/','.'); }
151         public String getShortName() {
152             int p = descriptor.lastIndexOf('/');
153             return p == -1 ? descriptor.substring(1,descriptor.length()-1) : descriptor.substring(p+1,descriptor.length()-1);
154         }
155         private static String _initHelper(String s) {
156             if (!s.startsWith("L") || !s.endsWith(";")) throw new Error("invalid: " + s);
157             return s;
158         }
159         String[] components() {
160             StringTokenizer st = new StringTokenizer(descriptor.substring(1, descriptor.length()-1), "/");
161             String[] a = new String[st.countTokens()];
162             for(int i=0;st.hasMoreTokens();i++) a[i] = st.nextToken();
163             return a;
164         }
165
166         public Type.Class.Body getBody(Context cx) { return cx.resolve(this.getName()); }
167         public abstract class Body extends HasAttributes {
168             public abstract Type.Class.Method.Body[] methods();
169             public abstract Type.Class.Field.Body[] fields();
170             public Body(int flags, ClassFile.AttrGen attrs) {
171                 super(flags, attrs);
172                 if ((flags & ~(PUBLIC|FINAL|SUPER|INTERFACE|ABSTRACT)) != 0)
173                     throw new IllegalArgumentException("invalid flags: " + Integer.toString(flags,16));
174             }
175         }
176
177         public Field field(String name, Type type) { return new Field(name, type); }
178         public Field field(String name, String descriptor) { return field(name,Type.fromDescriptor(descriptor)); }
179
180         public Method method(String name, Type returnType, Type[] argTypes) { return new Method(name, returnType, argTypes); }
181
182         /** see JVM Spec section 2.10.2 */
183         public Method method(String name, String descriptor) {
184             // FEATURE: This parser is ugly but it works (and shouldn't be a problem) might want to clean it up though
185             String s = descriptor;
186             if(!s.startsWith("(")) throw new IllegalArgumentException("invalid method type descriptor");
187             int p = s.indexOf(')');
188             if(p == -1) throw new IllegalArgumentException("invalid method type descriptor");
189             String argsDesc = s.substring(1,p);
190             String retDesc = s.substring(p+1);
191             Type[] argsBuf = new Type[argsDesc.length()];
192             int i;
193             for(i=0,p=0;argsDesc.length() > 0;i++,p=0) {
194                 while(p < argsDesc.length() && argsDesc.charAt(p) == '[') p++;
195                 if(p == argsDesc.length())  throw new IllegalArgumentException("invalid method type descriptor");
196                 if(argsDesc.charAt(p) == 'L') {
197                     p = argsDesc.indexOf(';');
198                     if(p == -1) throw new IllegalArgumentException("invalid method type descriptor");
199                 }
200                 argsBuf[i] = Type.fromDescriptor(argsDesc.substring(0,p+1));
201                 argsDesc = argsDesc.substring(p+1);
202             }
203             Type args[] = new Type[i];
204             System.arraycopy(argsBuf,0,args,0,i);
205             return method(name, Type.fromDescriptor(retDesc), args);
206         }
207
208         public abstract class Member {
209             public final String name;
210             private Member(String name) { this.name = name; }
211             public Type.Class getDeclaringClass() { return Type.Class.this; }
212             public String getName() { return name; }
213             public abstract String getTypeDescriptor();
214             public abstract String toString();
215             public abstract int hashCode();
216             public abstract boolean equals(Object o);
217         }
218     
219         public class Field extends Member {
220             public final Type type;
221             private Field(String name, Type t) { super(name); this.type = t; }
222             public String getTypeDescriptor() { return type.getDescriptor(); }
223             public Type getType() { return type; }
224             public String toString() { return getDeclaringClass().toString()+"."+name+"["+type.toString()+"]"; }
225             public class Body extends HasAttributes {
226                 public Field getField() { return Field.this; }
227                 public Body(int flags, ClassFile.AttrGen attrs) {
228                     super(flags, attrs);
229                     if ((flags & ~VALID_FIELD_FLAGS) != 0) throw new IllegalArgumentException("invalid flags");
230                 }
231             }
232             public int hashCode() {
233                 return type.hashCode() ^ name.hashCode() ^ getDeclaringClass().hashCode();
234             }
235             public boolean equals(Object o_) {
236                 if(o_ == this) return true;
237                 if(!(o_ instanceof Field)) return false;
238                 Field o = (Field) o_;
239                 return o.getDeclaringClass() == getDeclaringClass() && o.type == type && o.name.equals(name);
240             }
241         }
242
243         public class Method extends Member {
244             final Type[] argTypes;
245             public final Type   returnType;
246             public Type getReturnType()   { return returnType; }
247             public int  getNumArgs()      { return argTypes.length; }
248             public Type getArgType(int i) { return argTypes[i]; }
249             public Type[] getArgTypes()   {
250                 Type[] ret = new Type[argTypes.length];
251                 System.arraycopy(argTypes, 0, ret, 0, ret.length);
252                 return ret;
253             }
254             public boolean isConstructor() { return getName().equals("<init>"); }
255             public boolean isClassInitializer() { return getName().equals("<clinit>"); }
256             
257             public String toString() {
258                 StringBuffer sb = new StringBuffer();
259                 if (name.equals("<clinit>")) sb.append("static ");
260                 else {
261                     if (name.equals("<init>"))
262                         sb.append(Class.this.getShortName());
263                     else
264                         sb.append(returnType.toString()).append(" ").append(name);
265                     sb.append("(");
266                     for(int i=0; i<argTypes.length; i++)
267                         sb.append((i==0?"":", ")+argTypes[i].toString());
268                     sb.append(") ");
269                 }
270                 return sb.toString();
271             }
272             private Method(String name, Type returnType, Type[] argTypes) {
273                 super(name);
274                 this.argTypes = argTypes;
275                 this.returnType = returnType;
276             }
277             //public Method.Body getBody(Context cx) { }
278             public String getTypeDescriptor() {
279                 StringBuffer sb = new StringBuffer(argTypes.length*4);
280                 sb.append("(");
281                 for(int i=0;i<argTypes.length;i++) sb.append(argTypes[i].getDescriptor());
282                 sb.append(")");
283                 sb.append(returnType.getDescriptor());
284                 return sb.toString();
285             }
286             public abstract class Body extends HasAttributes {
287                 public abstract java.util.Hashtable getThrownExceptions();
288                 public abstract void debugBodyToString(StringBuffer sb);
289                 public Method getMethod() { return Method.this; }
290                 public Body(int flags, ClassFile.AttrGen attrs) {
291                     super(flags, attrs);
292                     if ((flags & ~VALID_METHOD_FLAGS) != 0) throw new IllegalArgumentException("invalid flags");
293                 }
294                 public boolean isConcrete() { return !isAbstract() && !isNative() /*FIXME: !inAnInterface*/; }
295                 public void toString(StringBuffer sb, String constructorName) {
296                     int flags = getFlags();
297                     sb.append("  ").append(ClassFile.flagsToString(flags,false));
298                     sb.append(Method.this.toString());
299                     java.util.Hashtable thrownExceptions = getThrownExceptions();
300                     if (thrownExceptions.size() > 0) {
301                         sb.append("throws");
302                         for(java.util.Enumeration e = thrownExceptions.keys();e.hasMoreElements();)
303                             sb.append(" ").append(((Type.Class)e.nextElement()).toString()).append(",");
304                         sb.setLength(sb.length()-1);
305                         sb.append(" ");
306                     }
307                     if ((flags & (NATIVE|ABSTRACT))==0) {
308                         sb.append("{\n");
309                         debugBodyToString(sb);
310                         sb.append("  }\n");
311                     } else {
312                         sb.append(";");
313                     }
314                 }
315             }
316             public int hashCode() {
317                 int h = returnType.hashCode() ^ name.hashCode() ^ getDeclaringClass().hashCode();
318                 for(int i=0;i<argTypes.length;i++) h ^= argTypes[i].hashCode();
319                 return h;
320             }
321             public boolean equals(Object o_) {
322                 if(o_ == this) return true;
323                 if(!(o_ instanceof Method)) return false;
324                 Method o = (Method) o_;
325                 if(!(o.getDeclaringClass() == getDeclaringClass() && o.returnType == returnType && o.name.equals(name))) return false;
326                 if(o.argTypes.length != argTypes.length) return false;
327                 for(int i=0;i<argTypes.length;i++)
328                     if(o.argTypes[i] != argTypes[i]) return false;
329                 return true;
330             }
331         }
332     }
333     
334     // FEATURE: This probably isn't the best place for these
335     static String methodTypeDescriptor(Type[] argTypes, Type returnType) {
336         StringBuffer sb = new StringBuffer(argTypes.length*4);
337         sb.append("(");
338         for(int i=0;i<argTypes.length;i++) sb.append(argTypes[i].getDescriptor());
339         sb.append(")");
340         sb.append(returnType.getDescriptor());
341         return sb.toString();
342     }
343
344 }