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