add debug variable
[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 = new Preprocessor(null, null, Collections.EMPTY_LIST);
86
87     private Source[] sources;
88
89     private File builddir = new File(".");
90     private File sourcedir = new File(".");
91
92     public Compiler() { }
93
94     public void setBuildDir(String dir) { builddir = new File(dir == null ? "." : dir); }
95     public void setSourceDir(String dir) { sourcedir = new File(dir == null ? "." : dir); }
96
97     /** Pass CompilerOptions.VERSION_1_*. A String of form "1.1", ".2", etc. */
98     public void setSource(String v) { settings.put(CompilerOptions.OPTION_Source, v); }
99
100     /** Pass CompilerOptions.VERSION_1_*. A String of form "1.1", ".2", etc. */
101     public void setTarget(String v) { settings.put(CompilerOptions.OPTION_TargetPlatform, v); }
102
103     public void setBuilddir(File f) { builddir = f; }
104
105     public void compile() {
106         List s = new ArrayList();
107         filterSources(s, sourcedir, new char[0][]);
108         if (DEBUG) System.out.println("working with "+s.size() +" sources");
109         sources = new Source[s.size()]; s.toArray(sources);
110         ICompilationUnit[] units = new ICompilationUnit[s.size()];
111         for (int i=0; i < sources.length; i++) units[i] = sources[i].unit;
112
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         }
276         public int getModifiers() { return m.getModifiers(); }
277         public char[] getSelector() { return m.getName().toCharArray(); }
278         public boolean isConstructor() { return false; }
279         public boolean isClinit() { return false; }
280         public char[][] getArgumentNames() { return null; } // FEATURE: does this do anything cool?
281         public char[][] getExceptionTypeNames() { return ex; }
282         public char[] getMethodDescriptor() { return desc; }
283     }
284
285     final static class LoadedClass implements IBinaryType {
286         private Class c;
287         private IBinaryField[] f;
288         private char[][] inf;
289         private IBinaryNestedType[] nested;
290         private IBinaryMethod[] meth = null;
291
292         LoadedClass(Class c) {
293             this.c = c;
294
295             Field[] fields = c.getFields();
296             f = new IBinaryField[fields.length];
297             for (int i=0; i < f.length; i++) f[i] = new LoadedField(fields[i]);
298
299             Class[] interfaces = c.getInterfaces();
300             inf = new char[interfaces.length][];
301             for (int i=0; i < inf.length; i++) inf[i] = name(interfaces[i]);
302
303             Class[] classes = c.getClasses();
304             nested = new IBinaryNestedType[classes.length];
305             for (int i=0; i < nested.length; i++)
306                 nested[i] = new LoadedNestedType(classes[i]);
307
308             Constructor[] constructors = c.getConstructors();
309             Method[] methods = c.getDeclaredMethods();
310             if (methods.length + constructors.length > 0) {
311                 meth = new IBinaryMethod[methods.length + constructors.length];
312                 int i=0;
313                 for (int j=0; j < methods.length; j++)
314                     meth[i++] = new LoadedMethod(methods[j]);
315                 for (int j=0; j < constructors.length; j++)
316                     meth[i++] = new LoadedConstructor(constructors[j]);
317             }
318
319         }
320
321         public char[] getName() { return name(c); }
322         public char[] getEnclosingTypeName() { return name(c.getDeclaringClass()); }
323         public char[] getSuperclassName() { return name(c.getSuperclass()); }
324         public IBinaryField[] getFields() { return f; }
325         public char[][] getInterfaceNames() { return inf; }
326         public IBinaryNestedType[] getMemberTypes() { return nested; }
327         public IBinaryMethod[] getMethods() { return meth; }
328         public int getModifiers() { return c.getModifiers(); }
329
330         public boolean isBinaryType() { return true; }
331         public boolean isClass() { return true; }
332         public boolean isInterface() { return c.isInterface(); }
333         public boolean isAnonymous() { return false; }
334         public boolean isLocal() { return false; } // FIXME
335         public boolean isMember() { return false; } // FIXME
336         public char[] sourceFileName() { return null; }
337         public char[] getFileName() { return null; }
338
339         public boolean equals(Object o) {
340             return o == this || super.equals(o) ||
341                    (o != null && o instanceof LoadedClass &&
342                     c.equals(((LoadedClass)o).c));
343         }
344     }
345
346
347     // Compiler Parameters ////////////////////////////////////////////////////
348
349     /** Used by compiler to resolve classes. */
350     final INameEnvironment env = new INameEnvironment() {
351         public NameEnvironmentAnswer findType(char[][] c) { return findType(name(c), pack(c)); }
352         public NameEnvironmentAnswer findType(char[] n, char[][] p) {
353             if (DEBUG) System.out.println("requesting: "+ str(p, '.') + "."+new String(n));
354
355             try {
356                 Class c = Class.forName(str(p, '.') + '.' + new String(n));
357                 if (DEBUG) System.out.println("found class: "+ c);
358                 IBinaryType b = (IBinaryType)loaded.get(c);
359                 if (b == null) loaded.put(c, b = new LoadedClass(c));
360                 if (DEBUG) System.out.println("returning "+b+", name="+new String(b.getName()));
361                 return new NameEnvironmentAnswer(b);
362             } catch (ClassNotFoundException e) {}
363
364             // cut out searches for java.* packages in sources list
365             if (p.length > 0 && eq(p[0], "java".toCharArray())) return null;
366
367             try {
368                 for (int i=0; i < sources.length; i++)
369                     if (eq(n, sources[i].n) && eq(p, sources[i].p))
370                         return sources[i].compiled == null ?
371                                new NameEnvironmentAnswer(sources[i].unit) :
372                                new NameEnvironmentAnswer(new ClassFileReader(sources[i].compiled,
373                                     sources[i].orig.getName().toCharArray(), true));
374             } catch (ClassFormatException e) {
375                 System.out.println("Unexpected ClassFormatException"); // FIXME
376                 e.printStackTrace();
377             }
378             return null;
379         }
380         public boolean isPackage(char[][] parent, char[] name) {
381             String parentName = str(parent, '/');
382             for (int i=0; i < sources.length; i++)
383                 if (eq(name, sources[i].n) && eq(parent, sources[i].p)) return false;
384             return
385                 loader.getResource(parentName + ".class") == null &&
386                 loader.getResource(parentName + '/' + new String(name) + ".class") == null;
387         }
388         public void cleanup() {}
389     };
390
391     /** Used by compiler to decide what do with problems.. */
392     private final IErrorHandlingPolicy policy =
393         DefaultErrorHandlingPolicies.proceedWithAllProblems();
394
395     /** Used by compiler for general options. */
396     private final Map settings = new HashMap();
397     {
398         settings.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE);
399         settings.put(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE);
400         settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_3);
401         settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_1);
402     };
403
404     /** Used by compiler for processing compiled classes and their errors. */
405     private final ICompilerRequestor results = new ICompilerRequestor() {
406         public void acceptResult(CompilationResult result) {
407             if (DEBUG) System.out.println("got result: "+result);
408             if (result.hasProblems()) {
409                 boolean hasErrors = false;
410                 IProblem[] p = result.getProblems();
411                 for (int i=0; i < p.length; i++) {
412                     if (p[i].isError()) hasErrors = true;
413                     out.print(p[i].getOriginatingFileName());
414                     out.print(':');
415                     out.print(p[i].getSourceLineNumber());
416                     out.print(':');
417                     out.println(p[i].getMessage());
418                 }
419                 out.flush();
420                 if (hasErrors) return;
421             }
422
423             ClassFile[] c = result.getClassFiles();
424             for (int i=0; i < c.length; i++) {
425                 try {
426                     // build package path to new class file
427                     File path = builddir;
428                     char[][] name = c[i].getCompoundName();
429                     path = new File(builddir, str(pack(name), '/'));
430                     if (DEBUG) System.out.println("DEBUG: creating path "+path+", out of builddir="+builddir);
431                     if (!path.exists()) path.mkdirs();
432
433                     // write new class file
434                     path = new File(path, new String(name(name)) + ".class");
435                     if (DEBUG) System.out.println("DEBUG: writing file "+path);
436                     OutputStream o = new BufferedOutputStream(
437                         new FileOutputStream(path));
438                     o.write(c[i].getBytes());
439                     o.close();
440                 } catch (IOException e) {
441                     System.out.println("IOException writing class"); // FIXME
442                     e.printStackTrace();
443                 }
444             }
445         }
446     };
447
448     /** Problem creater for compiler. */
449     private final IProblemFactory problems = new DefaultProblemFactory();
450
451
452     // Helper Functiosn ///////////////////////////////////////////////////////
453
454     /** Convert source file path into class name block.
455      *  eg. in:  java/lang/String.java -> { {java} {lang} {String} } */
456     private char[][] classname(String name) {
457         String delim = name.indexOf('/') == -1 ? "." : "/";
458         name = name.trim();
459         if (name.endsWith(".java")) name = name.substring(0, name.length() - 5);
460         if (name.startsWith(delim)) name = name.substring(1);
461
462         StringTokenizer st = new StringTokenizer(name, delim);
463         char[][] n = new char[st.countTokens()][];
464         for (int i=0; st.hasMoreTokens(); i++) n[i] = st.nextToken().toCharArray();
465         return n;
466     }
467
468     /** Convert class name into a String. */
469     private static String str(char[][] name, char delim) {
470         StringBuffer b = new StringBuffer();
471         for (int i=0; name != null && i < name.length; i++) {
472             if (name[i] == null || name[i].length == 0) continue;
473             if (i > 0) b.append(delim);
474             b.append(name[i]);
475         }
476         return b.toString();
477     }
478
479     /** Returns the package component of a class name.
480      *  Effectively returns char[length - 1][].  */
481     private static char[][] pack(char[][] c) {
482         char[][] p = new char[c.length - 1][];
483         for (int i=0; i < p.length; i++) p[i] = c[i];
484         return p;
485     }
486
487     /** Returns the direct-name component of a class name.
488      *  eg. String from java.lang.String */
489     private static char[] name(char[][] c) { return c[c.length - 1]; }
490
491     /** Returns true of contents of both char arrays are equal. */
492     private static boolean eq(char[][] c1, char[][] c2) {
493         if (c1.length != c2.length) return false;
494         for (int i=0; i < c1.length; i++) if (!eq(c1[i], c2[i])) return false;
495         return true;
496     }
497
498     /** Returns true of contents of both char arrays are equal. */
499     private static boolean eq(char[] c1, char[] c2) {
500         if (c1.length != c2.length) return false;
501         for (int i=0; i < c1.length; i++) if (c1[i] != c2[i]) return false;
502         return true;
503     }
504
505     /** Returns class name as per VM Spec 4.2. eg. java/lang/String */
506     private static char[] name(Class c) {
507         return c == null ? null : c.getName().replace('.', '/').toCharArray();
508     }
509
510     /** Returns the type name of a class as per VM Spec 4.3.2. */
511     private static char[] typeName(Class p) {
512         StringBuffer sb = new StringBuffer();
513         typeName(p, sb);
514         return sb.toString().toCharArray();
515     }
516
517     /** Returns the type name of a class as per VM Spec 4.3.2.
518      *  eg. int -> I, String -> Ljava/lang/String; */
519     private static void typeName(Class p, StringBuffer sb) {
520         String name = p.getName();
521         switch (name.charAt(0)) {
522             case 'B': case 'C': case 'D': case 'F': case 'I':
523             case 'J': case 'S': case 'Z': case 'V': case '[':
524                 sb.append(name(p)); break;
525
526             case 'b': if (name.equals("boolean")) { sb.append('Z'); break; }
527                       if (name.equals("byte"))    { sb.append('B'); break; }
528             case 'c': if (name.equals("char"))    { sb.append('C'); break; }
529             case 'd': if (name.equals("double"))  { sb.append('D'); break; }
530             case 'f': if (name.equals("float"))   { sb.append('F'); break; }
531             case 'i': if (name.equals("int"))     { sb.append('I'); break; }
532             case 'l': if (name.equals("long"))    { sb.append('J'); break; }
533             case 's': if (name.equals("short"))   { sb.append('S'); break; }
534             case 'v': if (name.equals("void"))    { sb.append('V'); break; }
535             default:
536                 sb.append('L'); sb.append(name(p)); sb.append(';');
537         }
538     }
539
540     /** Returns the descriptor of a method per VM Spec 4.3.3.
541      *  eg. int get(String n, boolean b) -> (Ljava/lang/String;B)I */
542     private static char[] descriptor(Class[] p, Class r) {
543         StringBuffer sb = new StringBuffer();
544         sb.append('(');
545         if (p != null) for (int i=0; i < p.length; i++) typeName(p[i], sb);
546         sb.append(')');
547         if (r != null) typeName(r, sb);
548         return sb.toString().toCharArray();
549     }
550
551 }