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