added Type.Primitive, generate toString() output on demand
[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 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     
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 final String  toString() { return super.toString(); }
41     public abstract String debugToString();
42     
43     public final String  getDescriptor() { return descriptor; }
44     public       int     hashCode() { return descriptor.hashCode(); }
45     public       boolean equals(java.lang.Object o) { return this==o; }
46
47     public Type.Array  makeArray() { return (Type.Array)instance("["+descriptor); }
48     public Type.Array  makeArray(int i) { return i==0 ? (Type.Array)this : makeArray().makeArray(i-1); }
49
50     public Type.Ref    asRef()       { throw new RuntimeException("attempted to use "+this+" as a Type.Ref, which it is not"); }
51     public Type.Class  asClass()     { throw new RuntimeException("attempted to use "+this+" as a Type.Class, which it is not"); }
52     public Type.Array  asArray()     { throw new RuntimeException("attempted to use "+this+" as a Type.Array, which it is not"); }
53     public boolean     isPrimitive() { return false; }
54     public boolean     isRef()       { return false; }
55     public boolean     isClass()     { return false; }
56     public boolean     isArray()     { return false; }
57
58     // Protected/Private //////////////////////////////////////////////////////////////////////////////
59
60     protected final String descriptor;
61     
62     protected Type(String descriptor) {
63         this.descriptor = descriptor;
64         instances.put(descriptor, this);
65     }
66
67     static class Primitive extends Type {
68         private String humanReadable;
69         protected Primitive(String descriptor, String humanReadable) {
70             super(descriptor);
71             this.humanReadable = humanReadable;
72         }
73         public String debugToString() { return humanReadable; }
74         public boolean     isPrimitive() { return true; }
75     }
76     
77     public abstract static class Ref extends Type {
78         protected Ref(String descriptor) { super(descriptor); }
79         public abstract String debugToString();
80         public    Type.Ref asRef() { return this; }
81         public    boolean  isRef() { return true; }
82     }
83
84     public static class Array extends Type.Ref {
85         public final Type base;
86         protected Array(Type t) { super("[" + t.getDescriptor()); base = t; }
87         public Type.Array asArray() { return this; }
88         public boolean isArray() { return true; }
89         public String debugToString() { return base.debugToString() + "[]"; }
90         public Type getElementType() { return Type.instance(getDescriptor().substring(0, getDescriptor().length()-1)); }
91     }
92
93     public static class Class extends Type.Ref {
94         protected Class(String s) { super(_initHelper(s)); }
95         public Type.Class asClass() { return this; }
96         public boolean isClass() { return true; }
97         public String getShortName() { return toString.substring(toString.lastIndexOf('.')+1); }
98         String internalForm() { return descriptor.substring(1, descriptor.length()-1); }
99         public String debugToString() { return internalForm().replace('/','.'); }
100         public String getShortName() {
101             int p = descriptor.lastIndexOf('/');
102             return p == -1 ? descriptor.substring(1,descriptor.length()-1) : descriptor.substring(p+1,descriptor.length()-1);
103         }
104         private static String _initHelper(String s) {
105             if (!s.startsWith("L") || !s.endsWith(";")) s = "L" + s.replace('.', '/') + ";";
106             return s;
107         }
108         String[] components() {
109             StringTokenizer st = new StringTokenizer(descriptor.substring(1, descriptor.length()-1), "/");
110             String[] a = new String[st.countTokens()];
111             for(int i=0;st.hasMoreTokens();i++) a[i] = st.nextToken();
112             return a;
113         }
114
115         public Field  field(String name, Type type) { return new Field(name, type); }
116         public Method method(String name, Type returnType, Type[] argTypes) { return new Method(name, returnType, argTypes); }
117         public Method method(String name, String typeDescriptor) {
118             // FEATURE: This parser is ugly but it works (and shouldn't be a problem) might want to clean it up though
119             String s = typeDescriptor;
120             if(!s.startsWith("(")) throw new IllegalArgumentException("invalid method type descriptor");
121             int p = s.indexOf(')');
122             if(p == -1) throw new IllegalArgumentException("invalid method type descriptor");
123             String argsDesc = s.substring(1,p);
124             String retDesc = s.substring(p+1);
125             Type[] argsBuf = new Type[argsDesc.length()];
126             int i;
127             for(i=0,p=0;argsDesc.length() > 0;i++,p=0) {
128                 while(p < argsDesc.length() && argsDesc.charAt(p) == '[') p++;
129                 if(p == argsDesc.length())  throw new IllegalArgumentException("invalid method type descriptor");
130                 if(argsDesc.charAt(p) == 'L') {
131                     p = argsDesc.indexOf(';');
132                     if(p == -1) throw new IllegalArgumentException("invalid method type descriptor");
133                 }
134                 argsBuf[i] = Type.instance(argsDesc.substring(0,p+1));
135                 argsDesc = argsDesc.substring(p+1);
136             }
137             Type args[] = new Type[i];
138             System.arraycopy(argsBuf,0,args,0,i);
139             return method(name, Type.instance(retDesc), args);
140         }
141
142         public abstract class Member {
143             public final String name;
144             private Member(String name) { this.name = name; }
145             public Type.Class getDeclaringClass() { return Type.Class.this; }
146             public abstract String getDescriptor();
147             public boolean equals(Object o_) {
148                 if(!(o_ instanceof Member)) return false;
149                 Member o = (Member) o_;
150                 return o.getDeclaringClass().equals(getDeclaringClass()) &&
151                     o.name.equals(name) &&
152                     o.getDescriptor().equals(getDescriptor());
153             }
154             public int hashCode() { return getDeclaringClass().hashCode() ^ name.hashCode() ^ getDescriptor().hashCode(); }
155             public String toString() { return debugToString(); }
156             public abstract String debugToString();
157         }
158     
159         public class Field extends Member {
160             public final Type type;
161             private Field(String name, Type t) { super(name); this.type = t; }
162             public String getTypeDescriptor() { return type.getDescriptor(); }
163             public Type getType() { return type; }
164             public String debugToString() { return getDeclaringClass()+"."+name+"["+type+"]"; }
165         }
166
167         public class Method extends Member {
168             final Type[] argTypes;
169             public final Type   returnType;
170             public Type getReturnType()   { return returnType; }
171             public int  getNumArgs()      { return argTypes.length; }
172             public Type getArgType(int i) { return argTypes[i]; }
173             public Type[] getArgTypes()   {
174                 Type[] ret = new Type[argTypes.length];
175                 System.arraycopy(argTypes, 0, ret, 0, ret.length);
176                 return ret;
177             }
178
179             public boolean isConstructor() { return getName().equals("<init>"); }
180             public boolean isClassInitializer() { return getName().equals("<clinit>"); }
181             public String debugToString() {
182                 StringBuffer sb = new StringBuffer();
183                 if (name.equals("<clinit>")) sb.append("static ");
184                 else {
185                     if (name.equals("<init>"))
186                         sb.append(Class.this.getShortName());
187                     else
188                         sb.append(returnType.debugToString()).append(".").append(name);
189                     sb.append("(");
190                     for(int i=0; i<argTypes.length; i++)
191                         sb.append((i==0?"":", ")+argTypes[i].debugToString());
192                     sb.append(") ");
193                 }
194                 return sb.toString();
195             }
196             private Method(String name, Type returnType, Type[] argTypes) {
197                 super(name);
198                 this.argTypes = argTypes;
199                 this.returnType = returnType;
200             }
201             public String getDescriptor() {
202                 StringBuffer sb = new StringBuffer(argTypes.length*4);
203                 sb.append("(");
204                 for(int i=0;i<argTypes.length;i++) sb.append(argTypes[i].getDescriptor());
205                 sb.append(")");
206                 sb.append(returnType.getDescriptor());
207                 return sb.toString();
208             }
209             public abstract class Body extends HasFlags {
210                 public abstract java.util.Hashtable getThrownExceptions();
211                 public abstract void debugBodyToString(StringBuffer sb);
212                 public void debugToString(StringBuffer sb, String constructorName) {
213                     int flags = getFlags();
214                     sb.append("  ").append(ClassFile.flagsToString(flags,false));
215                     sb.append(Method.this.debugToString());
216                     java.util.Hashtable thrownExceptions = getThrownExceptions();
217                     if (thrownExceptions.size() > 0) {
218                         sb.append("throws");
219                         for(java.util.Enumeration e = thrownExceptions.keys();e.hasMoreElements();)
220                             sb.append(" ").append(((Type.Class)e.nextElement()).debugToString()).append(",");
221                         sb.setLength(sb.length()-1);
222                         sb.append(" ");
223                     }
224                     if ((flags & (NATIVE|ABSTRACT))==0) {
225                         sb.append("{\n");
226                         debugBodyToString(sb);
227                         sb.append("  }\n");
228                     } else {
229                         sb.append(";");
230                     }
231                 }
232             }
233         }
234     }
235     
236     // FEATURE: This probably isn't the best place for these
237     static String methodTypeDescriptor(Type[] argTypes, Type returnType) {
238         StringBuffer sb = new StringBuffer(argTypes.length*4);
239         sb.append("(");
240         for(int i=0;i<argTypes.length;i++) sb.append(argTypes[i].getDescriptor());
241         sb.append(")");
242         sb.append(returnType.getDescriptor());
243         return sb.toString();
244     }
245
246 }