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