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