improved error output
[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     private static final boolean DEBUG = false;
24
25     // Static Entry Point /////////////////////////////////////////////////////
26
27     public static void main(String[] args) {
28         String source = null, target = null;
29         String srcdir = null, blddir = null;
30
31         for (int i=0; i < args.length; i++) {
32             if (args[i].charAt(0) == '-') {
33                 if (args[i].length() == 1) {
34                     System.out.println("Illegal switch: -"); return; }
35                 switch (args[i].charAt(1)) {
36                     case '-':
37                         if (args[i].equals("--help")) printHelp();
38                         else System.out.println("Unknown switch: -");
39                         return;
40                     case 'd':
41                         if (i == args.length - 1) {
42                             System.out.println("Missing parameter: "+args[i]); return; }
43                         blddir = args[++i];
44                         break;
45                     case 's':
46                         if (i == args.length - 1) {
47                             System.out.println("Missing parameter: "+args[i]); return; }
48                         source = args[++i];
49                         break;
50                     case 't':
51                         if (i == args.length - 1) {
52                             System.out.println("Missing parameter: "+args[i]); return; }
53                         target = args[++i];
54                         break;
55                     case 'h':
56                         printHelp(); return;
57
58                 }
59             } else srcdir = args[i];
60         }
61
62         Compiler c = new Compiler();
63         if (blddir != null) c.setBuildDir(blddir);
64         if (srcdir != null) c.setSourceDir(srcdir);
65         if (source != null) c.setSource(source);
66         if (target != null) c.setTarget(target);
67         c.compile();
68     }
69     private static void printHelp() {
70         System.out.println("Usage java -cp ... org.ibex.tool.Compiler <options> <source directory>");
71         System.out.println("Options:");
72         System.out.println("  -d <directory>   Location for generated class files.");
73         System.out.println("  -s <release>     Compile with specified source compatibility.");
74         System.out.println("  -t <release>     Compile with specified class file compatibility.");
75         System.out.println("  -h or --help     Print this message.");
76         System.out.println("");
77     }
78
79
80     // Compiler Interface /////////////////////////////////////////////////////
81
82     private ClassLoader loader = ClassLoader.getSystemClassLoader();
83     private Map loaded = new HashMap();
84     private PrintWriter out = new PrintWriter(System.out);
85     private Preprocessor preprocessor;
86
87     private Source[] sources;
88
89     private File builddir = new File(".");
90     private String sourcedir = null;
91
92     public Compiler() {
93         List defs = Collections.EMPTY_LIST;
94
95         String define = System.getProperty("org.ibex.tool.preprocessor.define");
96         if (define != null) {
97             defs = new ArrayList();
98             StringTokenizer st = new StringTokenizer(define.toUpperCase(), ",");
99             while (st.hasMoreTokens()) defs.add(st.nextToken().trim());
100         }
101
102         preprocessor = new Preprocessor(null, null, defs);
103     }
104
105
106     public void setBuildDir(String dir) { builddir = new File(dir == null ? "." : dir); }
107     public void setSourceDir(String dir) { sourcedir = dir; }
108
109     /** Pass CompilerOptions.VERSION_1_*. A String of form "1.1", ".2", etc. */
110     public void setSource(String v) { settings.put(CompilerOptions.OPTION_Source, v); }
111
112     /** Pass CompilerOptions.VERSION_1_*. A String of form "1.1", ".2", etc. */
113     public void setTarget(String v) { settings.put(CompilerOptions.OPTION_TargetPlatform, v); }
114
115     public void setBuilddir(File f) { builddir = f; }
116
117     public void compile() {
118         List s = new ArrayList();
119         filterSources(s, new File(sourcedir), new char[0][]);
120         if (DEBUG) System.out.println("working with "+s.size() +" sources");
121         sources = new Source[s.size()]; s.toArray(sources);
122         ICompilationUnit[] units = new ICompilationUnit[s.size()];
123         for (int i=0; i < sources.length; i++) units[i] = sources[i].unit;
124
125         org.eclipse.jdt.internal.compiler.Compiler jdt =
126             new org.eclipse.jdt.internal.compiler.Compiler(
127                 env, policy, settings, results, problems);
128         jdt.compile(units);
129     }
130
131     private final FilenameFilter filterSrcs = new FilenameFilter() {
132         public boolean accept(File dir, String name) { return name.endsWith(".java"); }
133     };
134     private final FileFilter filterDirs = new FileFilter() {
135         public boolean accept(File path) { return path.isDirectory(); }
136     };
137     private void filterSources(List s, File dir, char[][] pack) {
138         File[] ja = dir.listFiles(filterSrcs);
139         for (int i=0; i < ja.length; i++)
140             s.add(new Source(ja[i], name(classname(ja[i].getName())), pack));
141
142         File[] d = dir.listFiles(filterDirs);
143         for (int i=0; i < d.length; i++) {
144             char[][] newpack = new char[pack.length + 1][];
145             for (int j=0; j < pack.length; j++) newpack[j] = pack[j];
146             newpack[pack.length] = d[i].getName().toCharArray();
147             filterSources(s, d[i], newpack);
148         }
149     }
150
151
152     /** Represents a file to be compiled. */
153     final class Source {
154         char[] fileName;
155         char[] n; char[][] p;
156         File orig;
157         char[] processed = null;
158         byte[] compiled = null;
159
160         final ICompilationUnit unit = new ICompilationUnit() {
161             public char[] getMainTypeName() { return n; }
162             public char[][] getPackageName() { return p; }
163             public char[] getFileName() { return fileName; }
164             public char[] getContents() {
165                 if (processed != null) return processed;
166
167                 try {
168                     Reader r = new InputStreamReader(new BufferedInputStream(
169                                new FileInputStream(orig)));
170                     StringWriter w = new StringWriter();
171                     Vector err;
172
173                     synchronized (preprocessor) {
174                         preprocessor.setReader(r);
175                         preprocessor.setWriter(w);
176                         err = preprocessor.process();
177                     }
178
179                     if (err.size() > 0) {
180                         System.out.println("Preprocessor Errors, "+err); // FIXME
181                         return null;
182                     }
183
184                     processed  = w.toString().toCharArray();
185                 } catch (IOException e) {
186                     System.out.println("IOException: "+e); // FIXME
187                     return null;
188                 }
189
190                 return processed;
191             }
192         };
193
194         private Source(File o, char[] n, char[][] p) {
195             orig = o; this.n = n; this.p = p;
196             String file = sourcedir;
197             file += File.separatorChar +  str(p, File.separatorChar);
198             file += File.separatorChar + new String(n) + ".java";
199             fileName = file.toCharArray();
200         }
201     }
202
203     // ClassLoader Wrappers ///////////////////////////////////////////////////
204
205     final static class LoadedNestedType implements IBinaryNestedType {
206         private Class c;
207         LoadedNestedType(Class c) { this.c = c; }
208         public char[] getName() { return name(c); }
209         public char[] getEnclosingTypeName() { return name(c.getDeclaringClass()); }
210         public int getModifiers() { return c.getModifiers(); }
211     }
212
213     final static class LoadedField implements IBinaryField {
214         private Field f;
215         private Constant c;
216
217         LoadedField(Field f) {
218             this.f = f;
219             int m = f.getModifiers();
220
221             c = Constant.NotAConstant;
222             if (Modifier.isFinal(m) && Modifier.isStatic(m)) {
223                 try {
224                     Class type = f.getType();
225                     if (type == Boolean.TYPE) {
226                         c = new BooleanConstant(f.getBoolean(null));
227                     } else if (type == Byte.TYPE) {
228                         c = new ByteConstant(f.getByte(null));
229                     } else if (type == Character.TYPE) {
230                         c = new CharConstant(f.getChar(null));
231                     } else if (type == Double.TYPE) {
232                         c = new DoubleConstant(f.getDouble(null));
233                     } else if (type == Float.TYPE) {
234                         c = new FloatConstant(f.getFloat(null));
235                     } else if (type == Integer.TYPE) {
236                         c = new IntConstant(f.getInt(null));
237                     } else if (type == Long.TYPE) {
238                         c = new LongConstant(f.getLong(null));
239                     } else if (type == Short.TYPE) {
240                         c = new ShortConstant(f.getShort(null));
241                     } else if (type == String.class) {
242                         c = new StringConstant((String)f.get(null));
243                     }
244                 } catch (IllegalAccessException e) {}
245             }
246         }
247         public Constant getConstant() { return c; }
248         public char[] getTypeName() { return typeName(f.getType()); }
249         public char[] getName() { return f.getName().toCharArray(); }
250         public int getModifiers() { return f.getModifiers(); }
251     }
252
253     final static class LoadedConstructor implements IBinaryMethod {
254         private Constructor c;
255         private char[][] ex;
256         private char[] desc;
257
258         LoadedConstructor(Constructor c) {
259             this.c = c;
260
261             Class[] exs = c.getExceptionTypes();
262             ex = new char[exs.length][];
263             for (int i=0; i < ex.length; i++) ex[i] = name(exs[i]);
264
265             desc = descriptor(c.getParameterTypes(), null);
266         }
267         public int getModifiers() { return c.getModifiers(); }
268         public char[] getSelector() { return c.getName().toCharArray(); }
269         public boolean isConstructor() { return true; }
270         public boolean isClinit() { return false; }
271         public char[][] getArgumentNames() { return null; }
272         public char[][] getExceptionTypeNames() { return ex; }
273         public char[] getMethodDescriptor() { return desc; }
274     }
275
276     final static class LoadedMethod implements IBinaryMethod {
277         private Method m;
278         private char[][] ex;
279         private char[] desc;
280
281         LoadedMethod(Method m) {
282             this.m = m;
283
284             Class[] exs = m.getExceptionTypes();
285             ex = new char[exs.length][];
286             for (int i=0; i < ex.length; i++) ex[i] = name(exs[i]);
287
288             desc = descriptor(m.getParameterTypes(), m.getReturnType());
289         }
290         public int getModifiers() { return m.getModifiers(); }
291         public char[] getSelector() { return m.getName().toCharArray(); }
292         public boolean isConstructor() { return false; }
293         public boolean isClinit() { return false; }
294         public char[][] getArgumentNames() { return null; } // FEATURE: does this do anything cool?
295         public char[][] getExceptionTypeNames() { return ex; }
296         public char[] getMethodDescriptor() { return desc; }
297     }
298
299     final static class LoadedClass implements IBinaryType {
300         private Class c;
301         private IBinaryField[] f;
302         private char[][] inf;
303         private IBinaryNestedType[] nested;
304         private IBinaryMethod[] meth = null;
305
306         LoadedClass(Class c) {
307             this.c = c;
308
309             Field[] fields = c.getFields();
310             f = new IBinaryField[fields.length];
311             for (int i=0; i < f.length; i++) f[i] = new LoadedField(fields[i]);
312
313             Class[] interfaces = c.getInterfaces();
314             inf = new char[interfaces.length][];
315             for (int i=0; i < inf.length; i++) inf[i] = name(interfaces[i]);
316
317             Class[] classes = c.getClasses();
318             nested = new IBinaryNestedType[classes.length];
319             for (int i=0; i < nested.length; i++)
320                 nested[i] = new LoadedNestedType(classes[i]);
321
322             Constructor[] constructors = c.getDeclaredConstructors();
323             Method[] methods = c.getDeclaredMethods();
324             if (methods.length + constructors.length > 0) {
325                 meth = new IBinaryMethod[methods.length + constructors.length];
326                 int i=0;
327                 for (int j=0; j < methods.length; j++)
328                     meth[i++] = new LoadedMethod(methods[j]);
329                 for (int j=0; j < constructors.length; j++)
330                     meth[i++] = new LoadedConstructor(constructors[j]);
331             }
332
333         }
334
335         public char[] getName() { return name(c); }
336         public char[] getEnclosingTypeName() { return name(c.getDeclaringClass()); }
337         public char[] getSuperclassName() { return name(c.getSuperclass()); }
338         public IBinaryField[] getFields() { return f; }
339         public char[][] getInterfaceNames() { return inf; }
340         public IBinaryNestedType[] getMemberTypes() { return nested; }
341         public IBinaryMethod[] getMethods() { return meth; }
342         public int getModifiers() { return c.getModifiers(); }
343
344         public boolean isBinaryType() { return true; }
345         public boolean isClass() { return true; }
346         public boolean isInterface() { return c.isInterface(); }
347         public boolean isAnonymous() { return false; }
348         public boolean isLocal() { return false; } // FIXME
349         public boolean isMember() { return false; } // FIXME
350         public char[] sourceFileName() { return null; }
351         public char[] getFileName() { return null; }
352
353         public boolean equals(Object o) {
354             return o == this || super.equals(o) ||
355                    (o != null && o instanceof LoadedClass &&
356                     c.equals(((LoadedClass)o).c));
357         }
358     }
359
360
361     // Compiler Parameters ////////////////////////////////////////////////////
362
363     /** Used by compiler to resolve classes. */
364     final INameEnvironment env = new INameEnvironment() {
365         public NameEnvironmentAnswer findType(char[][] c) { return findType(name(c), pack(c)); }
366         public NameEnvironmentAnswer findType(char[] n, char[][] p) {
367             if (DEBUG) System.out.println("requesting: "+ str(p, '.') + "."+new String(n));
368
369             try {
370                 Class c = Class.forName(str(p, '.') + '.' + new String(n));
371                 if (DEBUG) System.out.println("found class: "+ c);
372                 IBinaryType b = (IBinaryType)loaded.get(c);
373                 if (b == null) loaded.put(c, b = new LoadedClass(c));
374                 if (DEBUG) System.out.println("returning "+b+", name="+new String(b.getName()));
375                 return new NameEnvironmentAnswer(b);
376             } catch (ClassNotFoundException e) {}
377
378             // cut out searches for java.* packages in sources list
379             if (p.length > 0 && eq(p[0], "java".toCharArray())) return null;
380
381             try {
382                 for (int i=0; i < sources.length; i++)
383                     if (eq(n, sources[i].n) && eq(p, sources[i].p))
384                         return sources[i].compiled == null ?
385                                new NameEnvironmentAnswer(sources[i].unit) :
386                                new NameEnvironmentAnswer(new ClassFileReader(sources[i].compiled,
387                                     sources[i].orig.getName().toCharArray(), true));
388             } catch (ClassFormatException e) {
389                 System.out.println("Unexpected ClassFormatException"); // FIXME
390                 e.printStackTrace();
391             }
392             return null;
393         }
394         public boolean isPackage(char[][] parent, char[] name) {
395             String parentName = str(parent, '/');
396             for (int i=0; i < sources.length; i++)
397                 if (eq(name, sources[i].n) && eq(parent, sources[i].p)) return false;
398             return
399                 loader.getResource(parentName + ".class") == null &&
400                 loader.getResource(parentName + '/' + new String(name) + ".class") == null;
401         }
402         public void cleanup() {}
403     };
404
405     /** Used by compiler to decide what do with problems.. */
406     private final IErrorHandlingPolicy policy =
407         DefaultErrorHandlingPolicies.proceedWithAllProblems();
408
409     /** Used by compiler for general options. */
410     private final Map settings = new HashMap();
411     {
412         settings.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE);
413         settings.put(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE);
414         settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_3);
415         settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_1);
416     };
417
418     /** Used by compiler for processing compiled classes and their errors. */
419     private final ICompilerRequestor results = new ICompilerRequestor() {
420         public void acceptResult(CompilationResult result) {
421             if (DEBUG) System.out.println("got result: "+result);
422             if (result.hasProblems()) {
423                 boolean hasErrors = false;
424                 IProblem[] p = result.getProblems();
425                 for (int i=0; i < p.length; i++) {
426                     out.print(p[i].getOriginatingFileName());
427                     out.print(':');
428                     out.print(p[i].getSourceLineNumber());
429                     out.print(':');
430                     if (p[i].isError()) { out.print(" error: "); hasErrors = true; }
431                     else out.print(" warning: ");
432                     out.println(p[i].getMessage());
433                 }
434                 out.flush();
435                 if (hasErrors) return;
436             }
437
438             ClassFile[] c = result.getClassFiles();
439             for (int i=0; i < c.length; i++) {
440                 try {
441                     // build package path to new class file
442                     File path = builddir;
443                     char[][] name = c[i].getCompoundName();
444                     path = new File(builddir, str(pack(name), '/'));
445                     if (DEBUG) System.out.println("DEBUG: creating path "+path+", out of builddir="+builddir);
446                     if (!path.exists()) path.mkdirs();
447
448                     // write new class file
449                     path = new File(path, new String(name(name)) + ".class");
450                     if (DEBUG) System.out.println("DEBUG: writing file "+path);
451                     OutputStream o = new BufferedOutputStream(
452                         new FileOutputStream(path));
453                     o.write(c[i].getBytes());
454                     o.close();
455                 } catch (IOException e) {
456                     System.out.println("IOException writing class"); // FIXME
457                     e.printStackTrace();
458                 }
459             }
460         }
461     };
462
463     /** Problem creater for compiler. */
464     private final IProblemFactory problems = new DefaultProblemFactory();
465
466
467     // Helper Functiosn ///////////////////////////////////////////////////////
468
469     /** Convert source file path into class name block.
470      *  eg. in:  java/lang/String.java -> { {java} {lang} {String} } */
471     private char[][] classname(String name) {
472         String delim = name.indexOf('/') == -1 ? "." : "/";
473         name = name.trim();
474         if (name.endsWith(".java")) name = name.substring(0, name.length() - 5);
475         if (name.startsWith(delim)) name = name.substring(1);
476
477         StringTokenizer st = new StringTokenizer(name, delim);
478         char[][] n = new char[st.countTokens()][];
479         for (int i=0; st.hasMoreTokens(); i++) n[i] = st.nextToken().toCharArray();
480         return n;
481     }
482
483     /** Convert class name into a String. */
484     private static String str(char[][] name, char delim) {
485         StringBuffer b = new StringBuffer();
486         for (int i=0; name != null && i < name.length; i++) {
487             if (name[i] == null || name[i].length == 0) continue;
488             if (i > 0) b.append(delim);
489             b.append(name[i]);
490         }
491         return b.toString();
492     }
493
494     /** Returns the package component of a class name.
495      *  Effectively returns char[length - 1][].  */
496     private static char[][] pack(char[][] c) {
497         char[][] p = new char[c.length - 1][];
498         for (int i=0; i < p.length; i++) p[i] = c[i];
499         return p;
500     }
501
502     /** Returns the direct-name component of a class name.
503      *  eg. String from java.lang.String */
504     private static char[] name(char[][] c) { return c[c.length - 1]; }
505
506     /** Returns true of contents of both char arrays are equal. */
507     private static boolean eq(char[][] c1, char[][] c2) {
508         if (c1.length != c2.length) return false;
509         for (int i=0; i < c1.length; i++) if (!eq(c1[i], c2[i])) return false;
510         return true;
511     }
512
513     /** Returns true of contents of both char arrays are equal. */
514     private static boolean eq(char[] c1, char[] c2) {
515         if (c1.length != c2.length) return false;
516         for (int i=0; i < c1.length; i++) if (c1[i] != c2[i]) return false;
517         return true;
518     }
519
520     /** Returns class name as per VM Spec 4.2. eg. java/lang/String */
521     private static char[] name(Class c) {
522         return c == null ? null : c.getName().replace('.', '/').toCharArray();
523     }
524
525     /** Returns the type name of a class as per VM Spec 4.3.2. */
526     private static char[] typeName(Class p) {
527         StringBuffer sb = new StringBuffer();
528         typeName(p, sb);
529         return sb.toString().toCharArray();
530     }
531
532     /** Returns the type name of a class as per VM Spec 4.3.2.
533      *  eg. int -> I, String -> Ljava/lang/String; */
534     private static void typeName(Class p, StringBuffer sb) {
535         String name = p.getName();
536         switch (name.charAt(0)) {
537             case 'B': case 'C': case 'D': case 'F': case 'I':
538             case 'J': case 'S': case 'Z': case 'V': case '[':
539                 sb.append(name(p)); break;
540
541             case 'b': if (name.equals("boolean")) { sb.append('Z'); break; }
542                       if (name.equals("byte"))    { sb.append('B'); break; }
543             case 'c': if (name.equals("char"))    { sb.append('C'); break; }
544             case 'd': if (name.equals("double"))  { sb.append('D'); break; }
545             case 'f': if (name.equals("float"))   { sb.append('F'); break; }
546             case 'i': if (name.equals("int"))     { sb.append('I'); break; }
547             case 'l': if (name.equals("long"))    { sb.append('J'); break; }
548             case 's': if (name.equals("short"))   { sb.append('S'); break; }
549             case 'v': if (name.equals("void"))    { sb.append('V'); break; }
550             default:
551                 sb.append('L'); sb.append(name(p)); sb.append(';');
552         }
553     }
554
555     /** Returns the descriptor of a method per VM Spec 4.3.3.
556      *  eg. int get(String n, boolean b) -> (Ljava/lang/String;B)I */
557     private static char[] descriptor(Class[] p, Class r) {
558         StringBuffer sb = new StringBuffer();
559         sb.append('(');
560         if (p != null) for (int i=0; i < p.length; i++) typeName(p[i], sb);
561         sb.append(')');
562         if (r != null) typeName(r, sb);
563         return sb.toString().toCharArray();
564     }
565
566 }