85ff1696c48a31bb3bcded2aa72afdd68d2127b9
[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     // Protected/Private //////////////////////////////////////////////////////////////////////////////
68
69     protected final String descriptor;
70     
71     protected Type(String descriptor) {
72         this.descriptor = descriptor;
73         instances.put(descriptor, this);
74     }
75     
76     public static class Null extends Type {
77         protected Null() { super(""); } // not really correct....
78     }
79
80     public static class Primitive extends Type {
81         private String humanReadable;
82         Primitive(String descriptor, String humanReadable) {
83             super(descriptor);
84             this.humanReadable = humanReadable;
85         }
86         public String toString() { return humanReadable; }
87         public boolean     isPrimitive() { return true; }
88     }
89     
90     public abstract static class Ref extends Type {
91         protected Ref(String descriptor) { super(descriptor); }
92         public abstract String toString();
93         public    Type.Ref asRef() { return this; }
94         public    boolean  isRef() { return true; }
95     }
96
97     public static class Array extends Type.Ref {
98         public final Type base;
99         protected Array(Type t) { super("[" + t.getDescriptor()); base = t; }
100         public Type.Array asArray() { return this; }
101         public boolean isArray() { return true; }
102         public String toString() { return base.toString() + "[]"; }
103         public Type getElementType() { return base; }
104     }
105
106     public static class Class extends Type.Ref {
107         protected Class(String s) { super(_initHelper(s)); }
108         public Type.Class asClass() { return this; }
109         public boolean isClass() { return true; }
110         public static Type.Class instance(String className) {
111             return (Type.Class)Type.fromDescriptor("L"+className.replace('.', '/')+";"); }
112         public boolean extendsOrImplements(Type.Class c, Context cx) {
113             if (this==c) return true;
114             if (this==OBJECT) return false;
115             ClassFile cf = cx.resolve(getName());
116             if (cf==null) {
117                 System.err.println("warning: could not resolve class " + getName());
118                 return false;
119             }
120             if (cf.superType == c) return true;
121             for(int i=0; i<cf.interfaces.length; i++) if (cf.interfaces[i].extendsOrImplements(c,cx)) return true;
122             if (cf.superType == null) return false;
123             return cf.superType.extendsOrImplements(c, cx);
124         }
125         String internalForm() { return descriptor.substring(1, descriptor.length()-1); }
126         public String toString() { return internalForm().replace('/','.'); }
127         public String getName() { return internalForm().replace('/','.'); }
128         public String getShortName() {
129             int p = descriptor.lastIndexOf('/');
130             return p == -1 ? descriptor.substring(1,descriptor.length()-1) : descriptor.substring(p+1,descriptor.length()-1);
131         }
132         private static String _initHelper(String s) {
133             if (!s.startsWith("L") || !s.endsWith(";")) throw new Error("invalid: " + s);
134             return s;
135         }
136         String[] components() {
137             StringTokenizer st = new StringTokenizer(descriptor.substring(1, descriptor.length()-1), "/");
138             String[] a = new String[st.countTokens()];
139             for(int i=0;st.hasMoreTokens();i++) a[i] = st.nextToken();
140             return a;
141         }
142
143         public Type.Class.Body getBody(Context cx) { return cx.resolve(this.getName()); }
144         public abstract class Body extends HasAttributes {
145             public abstract Type.Class.Method.Body[] methods();
146             public abstract Type.Class.Field.Body[] fields();
147             public Body(int flags, ClassFile.AttrGen attrs) {
148                 super(flags, attrs);
149                 if ((flags & ~(PUBLIC|FINAL|SUPER|INTERFACE|ABSTRACT)) != 0)
150                     throw new IllegalArgumentException("invalid flags: " + Integer.toString(flags,16));
151             }
152         }
153
154         public Field field(String name, Type type) { return new Field(name, type); }
155         public Field field(String name, String descriptor) { return field(name,Type.fromDescriptor(descriptor)); }
156
157         public Method method(String name, Type returnType, Type[] argTypes) { return new Method(name, returnType, argTypes); }
158
159         /** see JVM Spec section 2.10.2 */
160         public Method method(String name, String descriptor) {
161             // FEATURE: This parser is ugly but it works (and shouldn't be a problem) might want to clean it up though
162             String s = descriptor;
163             if(!s.startsWith("(")) throw new IllegalArgumentException("invalid method type descriptor");
164             int p = s.indexOf(')');
165             if(p == -1) throw new IllegalArgumentException("invalid method type descriptor");
166             String argsDesc = s.substring(1,p);
167             String retDesc = s.substring(p+1);
168             Type[] argsBuf = new Type[argsDesc.length()];
169             int i;
170             for(i=0,p=0;argsDesc.length() > 0;i++,p=0) {
171                 while(p < argsDesc.length() && argsDesc.charAt(p) == '[') p++;
172                 if(p == argsDesc.length())  throw new IllegalArgumentException("invalid method type descriptor");
173                 if(argsDesc.charAt(p) == 'L') {
174                     p = argsDesc.indexOf(';');
175                     if(p == -1) throw new IllegalArgumentException("invalid method type descriptor");
176                 }
177                 argsBuf[i] = Type.fromDescriptor(argsDesc.substring(0,p+1));
178                 argsDesc = argsDesc.substring(p+1);
179             }
180             Type args[] = new Type[i];
181             System.arraycopy(argsBuf,0,args,0,i);
182             return method(name, Type.fromDescriptor(retDesc), args);
183         }
184
185         public abstract class Member {
186             public final String name;
187             private Member(String name) { this.name = name; }
188             public Type.Class getDeclaringClass() { return Type.Class.this; }
189             public String getName() { return name; }
190             public abstract String getTypeDescriptor();
191             public abstract String toString();
192         }
193     
194         public class Field extends Member {
195             public final Type type;
196             private Field(String name, Type t) { super(name); this.type = t; }
197             public String getTypeDescriptor() { return type.getDescriptor(); }
198             public Type getType() { return type; }
199             public String toString() { return getDeclaringClass().toString()+"."+name+"["+type.toString()+"]"; }
200             public class Body extends HasAttributes {
201                 public Field getField() { return Field.this; }
202                 public Body(int flags, ClassFile.AttrGen attrs) {
203                     super(flags, attrs);
204                     if ((flags & ~VALID_FIELD_FLAGS) != 0) throw new IllegalArgumentException("invalid flags");
205                 }
206             }
207         }
208
209         public class Method extends Member {
210             final Type[] argTypes;
211             public final Type   returnType;
212             public Type getReturnType()   { return returnType; }
213             public int  getNumArgs()      { return argTypes.length; }
214             public Type getArgType(int i) { return argTypes[i]; }
215             public Type[] getArgTypes()   {
216                 Type[] ret = new Type[argTypes.length];
217                 System.arraycopy(argTypes, 0, ret, 0, ret.length);
218                 return ret;
219             }
220             public boolean isConstructor() { return getName().equals("<init>"); }
221             public boolean isClassInitializer() { return getName().equals("<clinit>"); }
222             
223             public String toString() {
224                 StringBuffer sb = new StringBuffer();
225                 if (name.equals("<clinit>")) sb.append("static ");
226                 else {
227                     if (name.equals("<init>"))
228                         sb.append(Class.this.getShortName());
229                     else
230                         sb.append(returnType.toString()).append(" ").append(name);
231                     sb.append("(");
232                     for(int i=0; i<argTypes.length; i++)
233                         sb.append((i==0?"":", ")+argTypes[i].toString());
234                     sb.append(") ");
235                 }
236                 return sb.toString();
237             }
238             private Method(String name, Type returnType, Type[] argTypes) {
239                 super(name);
240                 this.argTypes = argTypes;
241                 this.returnType = returnType;
242             }
243             //public Method.Body getBody(Context cx) { }
244             public String getTypeDescriptor() {
245                 StringBuffer sb = new StringBuffer(argTypes.length*4);
246                 sb.append("(");
247                 for(int i=0;i<argTypes.length;i++) sb.append(argTypes[i].getDescriptor());
248                 sb.append(")");
249                 sb.append(returnType.getDescriptor());
250                 return sb.toString();
251             }
252             public abstract class Body extends HasAttributes {
253                 public abstract java.util.Hashtable getThrownExceptions();
254                 public abstract void debugBodyToString(StringBuffer sb);
255                 public Method getMethod() { return Method.this; }
256                 public Body(int flags, ClassFile.AttrGen attrs) {
257                     super(flags, attrs);
258                     if ((flags & ~VALID_METHOD_FLAGS) != 0) throw new IllegalArgumentException("invalid flags");
259                 }
260                 public boolean isConcrete() { return !isAbstract() && !isNative() /*FIXME: !inAnInterface*/; }
261                 public void toString(StringBuffer sb, String constructorName) {
262                     int flags = getFlags();
263                     sb.append("  ").append(ClassFile.flagsToString(flags,false));
264                     sb.append(Method.this.toString());
265                     java.util.Hashtable thrownExceptions = getThrownExceptions();
266                     if (thrownExceptions.size() > 0) {
267                         sb.append("throws");
268                         for(java.util.Enumeration e = thrownExceptions.keys();e.hasMoreElements();)
269                             sb.append(" ").append(((Type.Class)e.nextElement()).toString()).append(",");
270                         sb.setLength(sb.length()-1);
271                         sb.append(" ");
272                     }
273                     if ((flags & (NATIVE|ABSTRACT))==0) {
274                         sb.append("{\n");
275                         debugBodyToString(sb);
276                         sb.append("  }\n");
277                     } else {
278                         sb.append(";");
279                     }
280                 }
281             }
282         }
283     }
284     
285     // FEATURE: This probably isn't the best place for these
286     static String methodTypeDescriptor(Type[] argTypes, Type returnType) {
287         StringBuffer sb = new StringBuffer(argTypes.length*4);
288         sb.append("(");
289         for(int i=0;i<argTypes.length;i++) sb.append(argTypes[i].getDescriptor());
290         sb.append(")");
291         sb.append(returnType.getDescriptor());
292         return sb.toString();
293     }
294
295 }