add constants support to compiler
[org.ibex.tool.git] / src / java / org / ibex / tool / Compiler.java
1 package org.ibex.tool;
2
3 import java.util.*;
4 import java.io.*;
5
6 import java.lang.reflect.*;
7
8 import org.eclipse.jdt.core.compiler.IProblem;
9 import org.eclipse.jdt.internal.compiler.ClassFile;
10 import org.eclipse.jdt.internal.compiler.CompilationResult;
11 //import org.eclipse.jdt.internal.compiler.Compiler;
12 import org.eclipse.jdt.internal.compiler.DefaultErrorHandlingPolicies;
13 import org.eclipse.jdt.internal.compiler.ICompilerRequestor;
14 import org.eclipse.jdt.internal.compiler.IErrorHandlingPolicy;
15 import org.eclipse.jdt.internal.compiler.IProblemFactory;
16 import org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader;
17 import org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException;
18 import org.eclipse.jdt.internal.compiler.env.*;
19 import org.eclipse.jdt.internal.compiler.impl.*;
20 import org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory;
21
22 public class Compiler {
23
24     private ClassLoader loader = ClassLoader.getSystemClassLoader();
25     private Map loaded = new HashMap();
26     private Writer out = new PrintWriter(System.out);
27     private Preprocessor preprocessor = new Preprocessor(null, null, Collections.EMPTY_LIST);
28
29     private Source[] sources;
30     private ICompilationUnit[] units;
31
32
33     public static void main(String[] args) {
34         new Compiler(args);
35     }
36
37     public Compiler(String[] files) {
38         sources = new Source[files.length];
39         units = new ICompilationUnit[files.length];
40
41         for (int i=0; i < files.length; i++) {
42             char[][] n = classname(files[i]);
43             sources[i] = new Source(new File(files[i]), name(n), pack(n));
44             units[i] = sources[i].unit;
45         }
46
47         org.eclipse.jdt.internal.compiler.Compiler jdt =
48             new org.eclipse.jdt.internal.compiler.Compiler(
49                 env, policy, settings, results, problems);
50         jdt.compile(units);
51     }
52
53
54     /** Represents a file to be compiled. */
55     final class Source {
56         char[] n; char[][] p;
57         File orig;
58         char[] processed = null;
59         byte[] compiled = null;
60
61         ICompilationUnit unit = new ICompilationUnit() {
62             public char[] getMainTypeName() { return n; }
63             public char[][] getPackageName() { return p; }
64             public char[] getFileName() { return orig.getName().toCharArray(); }
65             public char[] getContents() {
66                 if (processed != null) return processed;
67
68                 try {
69                     Reader r = new InputStreamReader(new BufferedInputStream(
70                                new FileInputStream(orig)));
71                     StringWriter w = new StringWriter();
72                     Vector err;
73
74                     synchronized (preprocessor) {
75                         preprocessor.setReader(r);
76                         preprocessor.setWriter(w);
77                         err = preprocessor.process();
78                     }
79
80                     if (err.size() > 0) {
81                         System.out.println("Preprocessor Errors, "+err); // FIXME
82                         return null;
83                     }
84
85                     processed  = w.toString().toCharArray();
86                 } catch (IOException e) {
87                     System.out.println("IOException: "+e); // FIXME
88                     return null;
89                 }
90
91                 return processed;
92             }
93         };
94
95         private Source(File o, char[] n, char[][] p) {
96             orig = o; this.n = n; this.p = p;  }
97     }
98
99     // ClassLoader Wrappers ///////////////////////////////////////////////////
100
101     final static class LoadedNestedType implements IBinaryNestedType {
102         private Class c;
103         LoadedNestedType(Class c) { this.c = c; }
104         public char[] getName() { return name(c); }
105         public char[] getEnclosingTypeName() { return name(c.getDeclaringClass()); }
106         public int getModifiers() { return c.getModifiers(); }
107     }
108
109     final static class LoadedField implements IBinaryField {
110         private Field f;
111         private Constant c;
112
113         LoadedField(Field f) {
114             this.f = f;
115             int m = f.getModifiers();
116
117             c = Constant.NotAConstant;
118             if (Modifier.isFinal(m) && Modifier.isStatic(m)) {
119                 try {
120                     Class type = f.getType();
121                     if (type == Boolean.class) {
122                         c = new BooleanConstant(f.getBoolean(null));
123                     } else if (type == Byte.class) {
124                         c = new ByteConstant(f.getByte(null));
125                     } else if (type == Character.class) {
126                         c = new CharConstant(f.getChar(null));
127                     } else if (type == Double.class) {
128                         c = new DoubleConstant(f.getDouble(null));
129                     } else if (type == Float.class) {
130                         c = new FloatConstant(f.getFloat(null));
131                     } else if (type == Integer.class) {
132                         c = new IntConstant(f.getInt(null));
133                     } else if (type == Long.class) {
134                         c = new LongConstant(f.getLong(null));
135                     } else if (type == Short.class) {
136                         c = new ShortConstant(f.getShort(null));
137                     } else if (type == String.class) {
138                         c = new StringConstant((String)f.get(null));
139                     }
140                 } catch (IllegalAccessException e) {}
141             }
142         }
143         public Constant getConstant() { return c; }
144         public char[] getTypeName() { return typeName(f.getType()); }
145         public char[] getName() { return f.getName().toCharArray(); }
146         public int getModifiers() { return f.getModifiers(); }
147     }
148
149     final static class LoadedConstructor implements IBinaryMethod {
150         private Constructor c;
151         private char[][] ex;
152         private char[] desc;
153
154         LoadedConstructor(Constructor c) {
155             this.c = c;
156
157             Class[] exs = c.getExceptionTypes();
158             ex = new char[exs.length][];
159             for (int i=0; i < ex.length; i++) ex[i] = name(exs[i]);
160
161             desc = descriptor(c.getParameterTypes(), null);
162         }
163         public int getModifiers() { return c.getModifiers(); }
164         public char[] getSelector() { return c.getName().toCharArray(); }
165         public boolean isConstructor() { return true; }
166         public boolean isClinit() { return false; }
167         public char[][] getArgumentNames() { return null; }
168         public char[][] getExceptionTypeNames() { return ex; }
169         public char[] getMethodDescriptor() { return desc; }
170     }
171
172     final static class LoadedMethod implements IBinaryMethod {
173         private Method m;
174         private char[][] ex;
175         private char[] desc;
176
177         LoadedMethod(Method m) {
178             this.m = m;
179
180             Class[] exs = m.getExceptionTypes();
181             ex = new char[exs.length][];
182             for (int i=0; i < ex.length; i++) ex[i] = name(exs[i]);
183
184             desc = descriptor(m.getParameterTypes(), m.getReturnType());
185         }
186         public int getModifiers() { return m.getModifiers(); }
187         public char[] getSelector() { return m.getName().toCharArray(); }
188         public boolean isConstructor() { return false; }
189         public boolean isClinit() { return false; }
190         public char[][] getArgumentNames() { return null; } // FEATURE: does this do anything cool?
191         public char[][] getExceptionTypeNames() { return ex; }
192         public char[] getMethodDescriptor() { return desc; }
193     }
194
195     final static class LoadedClass implements IBinaryType {
196         private Class c;
197         private IBinaryField[] f;
198         private char[][] inf;
199         private IBinaryNestedType[] nested;
200         private IBinaryMethod[] meth = null;
201
202         LoadedClass(Class c) {
203             this.c = c;
204
205             Field[] fields = c.getFields();
206             f = new IBinaryField[fields.length];
207             for (int i=0; i < f.length; i++) f[i] = new LoadedField(fields[i]);
208
209             Class[] interfaces = c.getInterfaces();
210             inf = new char[interfaces.length][];
211             for (int i=0; i < inf.length; i++) inf[i] = name(interfaces[i]);
212
213             Class[] classes = c.getClasses();
214             nested = new IBinaryNestedType[classes.length];
215             for (int i=0; i < nested.length; i++)
216                 nested[i] = new LoadedNestedType(classes[i]);
217
218             Constructor[] constructors = c.getConstructors();
219             Method[] methods = c.getDeclaredMethods();
220             if (methods.length + constructors.length > 0) {
221                 meth = new IBinaryMethod[methods.length + constructors.length];
222                 int i=0;
223                 for (int j=0; j < methods.length; j++)
224                     meth[i++] = new LoadedMethod(methods[j]);
225                 for (int j=0; j < constructors.length; j++)
226                     meth[i++] = new LoadedConstructor(constructors[j]);
227             }
228
229         }
230
231         public char[] getName() { return name(c); }
232         public char[] getEnclosingTypeName() { return name(c.getDeclaringClass()); }
233         public char[] getSuperclassName() { return name(c.getSuperclass()); }
234         public IBinaryField[] getFields() { return f; }
235         public char[][] getInterfaceNames() { return inf; }
236         public IBinaryNestedType[] getMemberTypes() { return nested; }
237         public IBinaryMethod[] getMethods() { return meth; }
238         public int getModifiers() { return c.getModifiers(); }
239
240         public boolean isBinaryType() { return true; }
241         public boolean isClass() { return true; }
242         public boolean isInterface() { return c.isInterface(); }
243         public boolean isAnonymous() { return false; }
244         public boolean isLocal() { return false; } // FIXME
245         public boolean isMember() { return false; } // FIXME
246         public char[] sourceFileName() { return null; }
247         public char[] getFileName() { return null; }
248     }
249
250
251     // Compiler Parameters ////////////////////////////////////////////////////
252
253     /** Used by compiler to resolve classes. */
254     final INameEnvironment env = new INameEnvironment() {
255         public NameEnvironmentAnswer findType(char[][] c) { return findType(name(c), pack(c)); }
256         public NameEnvironmentAnswer findType(char[] n, char[][] p) {
257             try {
258                 Class c = Class.forName(str(p, '.') + '.' + new String(n));
259                 IBinaryType b = (IBinaryType)loaded.get(c);
260                 if (b == null) loaded.put(c, b = new LoadedClass(c));
261                 return new NameEnvironmentAnswer(b);
262             } catch (ClassNotFoundException e) {}
263
264             try {
265                 for (int i=0; i < sources.length; i++)
266                     if (eq(n, sources[i].n) && eq(p, sources[i].p))
267                         return sources[i].compiled == null ?
268                                new NameEnvironmentAnswer(sources[i].unit) :
269                                new NameEnvironmentAnswer(new ClassFileReader(sources[i].compiled,
270                                     sources[i].orig.getName().toCharArray(), true));
271             } catch (ClassFormatException e) {
272                 System.out.println("Unexpected ClassFormatException"); // FIXME
273                 e.printStackTrace();
274             }
275             return null;
276         }
277         public boolean isPackage(char[][] parent, char[] name) {
278             String parentName = str(parent, '/');
279             for (int i=0; i < sources.length; i++)
280                 if (eq(name, sources[i].n) && eq(parent, sources[i].p)) return false;
281             return
282                 loader.getResource(parentName + ".class") == null &&
283                 loader.getResource(parentName + '/' + name + ".class") == null;
284         }
285         public void cleanup() {}
286     };
287
288     /** Used by compiler to decide what do with problems.. */
289     private final IErrorHandlingPolicy policy =
290         DefaultErrorHandlingPolicies.proceedWithAllProblems();
291
292     /** Used by compiler for general options. */
293     private final Map settings = new HashMap();
294     {
295         settings.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE);
296         settings.put(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE);
297         settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_3);
298         settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_1);
299     };
300
301     /** Used by compiler for processing compiled classes and their errors. */
302     private final ICompilerRequestor results = new ICompilerRequestor() {
303         public void acceptResult(CompilationResult result) {
304             if (result.hasProblems()) {
305                 boolean hasErrors = false;
306                 IProblem[] p = result.getProblems();
307                 try {
308                     for (int i=0; i < p.length; i++) {
309                         if (p[i].isError()) hasErrors = true;
310                         out.write(p[i].getOriginatingFileName());
311                         out.write(':');
312                         out.write(p[i].getSourceLineNumber());
313                         out.write(':');
314                         out.write(p[i].getMessage());
315                     }
316                 } catch (IOException e) {
317                     System.out.println("severe: IOException on out"); // FIXME
318                     e.printStackTrace();
319                 }
320                 if (hasErrors) return;
321             }
322
323             ClassFile[] c = result.getClassFiles();
324             for (int i=0; i < c.length; i++) {
325                 try {
326                     String name = str(c[i].getCompoundName(), '/') + ".class";
327                     OutputStream o = new BufferedOutputStream(
328                         new FileOutputStream(new File(name)));
329                     o.write(c[i].getBytes());
330                     o.close();
331                 } catch (IOException e) {
332                     System.out.println("IOException writing class"); // FIXME
333                     e.printStackTrace();
334                 }
335             }
336         }
337     };
338
339     /** Problem creater for compiler. */
340     private final IProblemFactory problems = new DefaultProblemFactory();
341
342
343     // Helper Functiosn ///////////////////////////////////////////////////////
344
345     /** Convert source file path into class name block.
346      *  eg. in:  java/lang/String.java -> { {java} {lang} {String} } */
347     private char[][] classname(String name) {
348         String delim = name.indexOf('/') == -1 ? "." : "/";
349         name = name.trim();
350         if (name.endsWith(".java")) name = name.substring(0, name.length() - 5);
351         if (name.startsWith(delim)) name = name.substring(1);
352
353         StringTokenizer st = new StringTokenizer(name, delim);
354         char[][] n = new char[st.countTokens()][];
355         for (int i=0; st.hasMoreTokens(); i++) n[i] = st.nextToken().toCharArray();
356         return n;
357     }
358
359     /** Convert class name into a String. */
360     private static String str(char[][] name, char delim) {
361         StringBuffer b = new StringBuffer();
362         if (name != null) for (int i=0; i < name.length; i++)
363             if (name[i] != null) { b.append(delim); b.append(name[i]); }
364         if (b.length() > 0) b.deleteCharAt(0);
365         return b.toString();
366     }
367
368     /** Returns the package component of a class name.
369      *  Effectively returns char[length - 1][].  */
370     private static char[][] pack(char[][] c) {
371         char[][] p = new char[c.length - 1][];
372         for (int i=0; i < p.length; i++) p[i] = c[i];
373         return p;
374     }
375
376     /** Returns the direct-name component of a class name.
377      *  eg. String from java.lang.String */
378     private static char[] name(char[][] c) { return c[c.length - 1]; }
379
380     /** Returns true of contents of both char arrays are equal. */
381     private static boolean eq(char[][] c1, char[][] c2) {
382         if (c1.length != c2.length) return false;
383         for (int i=0; i < c1.length; i++) if (!eq(c1[i], c2[i])) return false;
384         return true;
385     }
386
387     /** Returns true of contents of both char arrays are equal. */
388     private static boolean eq(char[] c1, char[] c2) {
389         if (c1.length != c2.length) return false;
390         for (int i=0; i < c1.length; i++) if (c1[i] != c2[i]) return false;
391         return true;
392     }
393
394     /** Returns class name as per VM Spec 4.2. eg. java/lang/String */
395     private static char[] name(Class c) {
396         return c == null ? null : c.getName().replace('.', '/').toCharArray();
397     }
398
399     /** Returns the type name of a class as per VM Spec 4.3.2. */
400     private static char[] typeName(Class p) {
401         StringBuffer sb = new StringBuffer();
402         typeName(p, sb);
403         return sb.toString().toCharArray();
404     }
405
406     /** Returns the type name of a class as per VM Spec 4.3.2.
407      *  eg. int -> I, String -> Ljava/lang/String; */
408     private static void typeName(Class p, StringBuffer sb) {
409         String name = p.getName();
410         switch (name.charAt(0)) {
411             case 'B': case 'C': case 'D': case 'F': case 'I':
412             case 'J': case 'S': case 'Z': case 'V': case '[':
413                 sb.append(name); break;
414
415             case 'b': if (name.equals("boolean")) { sb.append('Z'); break; }
416                       if (name.equals("byte"))    { sb.append('B'); break; }
417             case 'c': if (name.equals("char"))    { sb.append('C'); break; }
418             case 'd': if (name.equals("double"))  { sb.append('D'); break; }
419             case 'f': if (name.equals("float"))   { sb.append('F'); break; }
420             case 'i': if (name.equals("int"))     { sb.append('I'); break; }
421             case 'l': if (name.equals("long"))    { sb.append('J'); break; }
422             case 's': if (name.equals("short"))   { sb.append('S'); break; }
423             case 'v': if (name.equals("void"))    { sb.append('V'); break; }
424             default:
425                 sb.append('L'); sb.append(name(p)); sb.append(';');
426         }
427     }
428
429     /** Returns the descriptor of a method per VM Spec 4.3.3.
430      *  eg. int get(String n, boolean b) -> (Ljava/lang/String;B)I */
431     private static char[] descriptor(Class[] p, Class r) {
432         StringBuffer sb = new StringBuffer();
433         sb.append('(');
434         if (p != null) for (int i=0; i < p.length; i++) typeName(p[i], sb);
435         sb.append(')');
436         if (r != null) typeName(r, sb);
437         return sb.toString().toCharArray();
438     }
439
440 }