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