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