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