6 import java.lang.reflect.*;
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;
22 public class Compiler {
23 // Static Entry Point /////////////////////////////////////////////////////
25 public static void main(String[] args) {
26 boolean verbose = false;
27 List srcdir = new ArrayList();
28 String source = null, target = null, blddir = null;
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)) {
36 if (args[i].equals("--help")) printHelp();
37 else System.out.println("Unknown switch: -");
40 if (i == args.length - 1) {
41 System.out.println("Missing parameter: "+args[i]); return; }
45 if (i == args.length - 1) {
46 System.out.println("Missing parameter: "+args[i]); return; }
50 if (i == args.length - 1) {
51 System.out.println("Missing parameter: "+args[i]); return; }
60 } else srcdir.add(args[i]);
63 Compiler c = new Compiler();
64 if (blddir != null) c.setBuildDir(blddir);
65 if (source != null) c.setSource(source);
66 if (target != null) c.setTarget(target);
68 String[] s = new String[srcdir.size()];
72 c.setVerbose(verbose);
75 private static void printHelp() {
76 System.out.println("Usage java -cp ... org.ibex.tool.Compiler [options] <source dir> ...");
77 System.out.println("Options:");
78 System.out.println(" -d <directory> Location for generated class files.");
79 System.out.println(" -s <release> Compile with specified source compatibility.");
80 System.out.println(" -t <release> Compile with specified class file compatibility.");
81 System.out.println(" -v Verbose output.");
82 System.out.println(" -h or --help Print this message.");
83 System.out.println("");
87 // Compiler Interface /////////////////////////////////////////////////////
89 private ClassLoader loader = ClassLoader.getSystemClassLoader();
90 private Map loaded = new HashMap();
91 private PrintWriter out = new PrintWriter(System.out);
92 private Preprocessor preprocessor;
94 private Source[] sources;
96 private File builddir = new File(".");
97 private String[] sourcedirs = new String[0];
99 private PrintWriter warn;
100 private boolean hasErrors;
101 private boolean verbose = false;
104 List defs = Collections.EMPTY_LIST;
106 String define = System.getProperty("org.ibex.tool.preprocessor.define");
107 if (define != null) {
108 defs = new ArrayList();
109 StringTokenizer st = new StringTokenizer(define.toUpperCase(), ",");
110 while (st.hasMoreTokens()) defs.add(st.nextToken().trim());
113 preprocessor = new Preprocessor(null, null, defs);
117 public void setBuildDir(String dir) { builddir = new File(dir == null ? "." : dir); }
118 public void setSourceDirs(String[] dir) { sourcedirs = dir; }
120 /** Pass CompilerOptions.VERSION_1_*. A String of form "1.1", ".2", etc. */
121 public void setSource(String v) { settings.put(CompilerOptions.OPTION_Source, v); }
123 /** Pass CompilerOptions.VERSION_1_*. A String of form "1.1", ".2", etc. */
124 public void setTarget(String v) { settings.put(CompilerOptions.OPTION_TargetPlatform, v); }
126 public void setBuilddir(File f) { builddir = f; }
128 public void setVerbose(boolean v) { verbose = v; }
130 public void compile() {
131 List s = new ArrayList();
132 for (int i=0; i < sourcedirs.length; i++) {
133 File src = new File(sourcedirs[i]);
135 if (verbose) System.err.println("source directory not found: "+sourcedirs[i]);
138 filterSources(s, src, new char[0][], sourcedirs[i]);
141 if (verbose) System.out.println("working with "+s.size() +" sources");
142 sources = new Source[s.size()]; s.toArray(sources);
143 ICompilationUnit[] units = new ICompilationUnit[s.size()];
144 int u = 0; for (int i=0; i < sources.length; i++)
145 if (sources[i].compiled == null) units[u++] = sources[i].unit;
146 if (u != units.length) {
147 ICompilationUnit[] newu = new ICompilationUnit[u];
148 System.arraycopy(units, 0, newu, 0, u);
154 StringWriter sw = new StringWriter();
155 StringBuffer w = sw.getBuffer();
156 warn = new PrintWriter(sw);
158 org.eclipse.jdt.internal.compiler.Compiler jdt =
159 new org.eclipse.jdt.internal.compiler.Compiler(
160 env, policy, settings, results, problems);
163 if (!hasErrors) { out.write(w.toString()); out.flush(); }
167 private final FilenameFilter filterSrcs = new FilenameFilter() {
168 public boolean accept(File dir, String name) { return name.endsWith(".java"); }
170 private final FileFilter filterDirs = new FileFilter() {
171 public boolean accept(File path) { return path.isDirectory(); }
173 private byte[] bytes(File bfile) {
174 byte[] bytes = new byte[2 * 1024];
177 InputStream bin = new FileInputStream(bfile);
178 while ((in = bin.read(bytes, pos, bytes.length - pos)) != -1) {
180 if (pos == bytes.length) {
181 byte[] newbytes= new byte[pos * 2];
182 System.arraycopy(bytes, 0, newbytes, 0, pos);
187 } catch (IOException e) {
188 System.out.println("Error reading class file"); // FIXME
189 e.printStackTrace(); return null;
192 if (pos != bytes.length) {
193 byte[] newbytes= new byte[pos * 2];
194 System.arraycopy(bytes, 0, newbytes, 0, pos);
200 private void filterSources(List s, File dir, char[][] pack, String srcdir) {
201 List bclasses = new ArrayList();
202 File bdir = new File(builddir, str(pack, File.separatorChar));
204 // add the java files in this directory
205 File[] ja = dir.listFiles(filterSrcs);
206 for (int i=0; i < ja.length; i++) {
207 char[] n = name(classname(ja[i].getName()));
208 Source src = new Source(ja[i], n, pack, srcdir);
210 // skip the file if the build version is newer than the source
211 String bclass = new String(n);
212 File bfile = new File(bdir, bclass + ".class");
213 if (bfile.lastModified() > ja[i].lastModified()) {
214 src.compiled = bytes(bfile);
215 bclasses.add(bclass);
221 // process the inner classes of any binary files
222 for (int i=0; i < bclasses.size(); i++) {
223 final String bc = (String)bclasses.get(i);
224 final FilenameFilter f = new FilenameFilter() {
225 public boolean accept(File dir, String name) {
226 return name.length() > bc.length() && name.startsWith(bc) &&
227 name.charAt(bc.length()) == '$' && name.endsWith(".class");
230 File[] bfile = bdir.listFiles(f);
231 for (int j=0; j < bfile.length; j++) {
232 Source src = new Source(bfile[j],
233 name(classname(bfile[j].getName())), pack, srcdir);
234 src.compiled = bytes(bfile[j]);
239 // add the subdirectories as packages
240 File[] d = dir.listFiles(filterDirs);
241 for (int i=0; i < d.length; i++) {
242 char[][] newpack = new char[pack.length + 1][];
243 for (int j=0; j < pack.length; j++) newpack[j] = pack[j];
244 newpack[pack.length] = d[i].getName().toCharArray();
245 filterSources(s, d[i], newpack, srcdir);
250 /** Represents a file to be compiled. */
253 char[] n; char[][] p;
255 char[] processed = null;
256 byte[] compiled = null;
257 ClassFileReader reader = null;
259 final ICompilationUnit unit = new ICompilationUnit() {
260 public char[] getMainTypeName() { return n; }
261 public char[][] getPackageName() { return p; }
262 public char[] getFileName() { return fileName; }
263 public char[] getContents() {
264 if (processed != null) return processed;
267 Reader r = new InputStreamReader(new BufferedInputStream(
268 new FileInputStream(orig)));
269 StringWriter w = new StringWriter();
272 synchronized (preprocessor) {
273 preprocessor.setReader(r);
274 preprocessor.setWriter(w);
275 err = preprocessor.process();
278 if (err.size() > 0) {
279 System.out.println("Preprocessor Errors, "+err); // FIXME
283 processed = w.toString().toCharArray();
284 } catch (IOException e) {
285 System.out.println("IOException: "+e); // FIXME
293 private Source(File o, char[] n, char[][] p, String srcdir) {
294 orig = o; this.n = n; this.p = p;
295 String file = srcdir;
296 file += File.separatorChar + str(p, File.separatorChar);
297 file += File.separatorChar + new String(n) + ".java";
298 fileName = file.toCharArray();
302 // ClassLoader Wrappers ///////////////////////////////////////////////////
304 final static class LoadedNestedType implements IBinaryNestedType {
306 LoadedNestedType(Class c) { this.c = c; }
307 public char[] getName() { return name(c); }
308 public char[] getEnclosingTypeName() { return name(c.getDeclaringClass()); }
309 public int getModifiers() { return c.getModifiers(); }
312 final static class LoadedField implements IBinaryField {
316 LoadedField(Field f) {
318 int m = f.getModifiers();
320 c = Constant.NotAConstant;
321 if (Modifier.isFinal(m) && Modifier.isStatic(m)) {
323 Class type = f.getType();
324 if (type == Boolean.TYPE) {
325 c = new BooleanConstant(f.getBoolean(null));
326 } else if (type == Byte.TYPE) {
327 c = new ByteConstant(f.getByte(null));
328 } else if (type == Character.TYPE) {
329 c = new CharConstant(f.getChar(null));
330 } else if (type == Double.TYPE) {
331 c = new DoubleConstant(f.getDouble(null));
332 } else if (type == Float.TYPE) {
333 c = new FloatConstant(f.getFloat(null));
334 } else if (type == Integer.TYPE) {
335 c = new IntConstant(f.getInt(null));
336 } else if (type == Long.TYPE) {
337 c = new LongConstant(f.getLong(null));
338 } else if (type == Short.TYPE) {
339 c = new ShortConstant(f.getShort(null));
340 } else if (type == String.class) {
341 c = new StringConstant((String)f.get(null));
343 } catch (IllegalAccessException e) {}
346 public Constant getConstant() { return c; }
347 public char[] getTypeName() { return typeName(f.getType()); }
348 public char[] getName() { return f.getName().toCharArray(); }
349 public int getModifiers() { return f.getModifiers(); }
352 final static class LoadedConstructor implements IBinaryMethod {
353 private Constructor c;
357 LoadedConstructor(Constructor c) {
360 Class[] exs = c.getExceptionTypes();
361 ex = new char[exs.length][];
362 for (int i=0; i < ex.length; i++) ex[i] = name(exs[i]);
364 desc = descriptor(c.getParameterTypes(), null);
366 public int getModifiers() { return c.getModifiers(); }
367 public char[] getSelector() { return c.getName().toCharArray(); }
368 public boolean isConstructor() { return true; }
369 public boolean isClinit() { return false; }
370 public char[][] getArgumentNames() { return null; }
371 public char[][] getExceptionTypeNames() { return ex; }
372 public char[] getMethodDescriptor() { return desc; }
375 final static class LoadedMethod implements IBinaryMethod {
380 LoadedMethod(Method m) {
383 Class[] exs = m.getExceptionTypes();
384 ex = new char[exs.length][];
385 for (int i=0; i < ex.length; i++) ex[i] = name(exs[i]);
387 desc = descriptor(m.getParameterTypes(), m.getReturnType());
389 public int getModifiers() { return m.getModifiers(); }
390 public char[] getSelector() { return m.getName().toCharArray(); }
391 public boolean isConstructor() { return false; }
392 public boolean isClinit() { return false; }
393 public char[][] getArgumentNames() { return null; } // FEATURE: does this do anything cool?
394 public char[][] getExceptionTypeNames() { return ex; }
395 public char[] getMethodDescriptor() { return desc; }
398 final static class LoadedClass implements IBinaryType {
400 private IBinaryField[] f;
401 private char[][] inf;
402 private IBinaryNestedType[] nested;
403 private IBinaryMethod[] meth = null;
405 LoadedClass(Class c) {
408 Field[] fields = c.getFields();
409 f = new IBinaryField[fields.length];
410 for (int i=0; i < f.length; i++) f[i] = new LoadedField(fields[i]);
412 Class[] interfaces = c.getInterfaces();
413 inf = new char[interfaces.length][];
414 for (int i=0; i < inf.length; i++) inf[i] = name(interfaces[i]);
416 Class[] classes = c.getClasses();
417 nested = new IBinaryNestedType[classes.length];
418 for (int i=0; i < nested.length; i++)
419 nested[i] = new LoadedNestedType(classes[i]);
421 Constructor[] constructors = c.getDeclaredConstructors();
422 Method[] methods = c.getDeclaredMethods();
423 if (methods.length + constructors.length > 0) {
424 meth = new IBinaryMethod[methods.length + constructors.length];
426 for (int j=0; j < methods.length; j++)
427 meth[i++] = new LoadedMethod(methods[j]);
428 for (int j=0; j < constructors.length; j++)
429 meth[i++] = new LoadedConstructor(constructors[j]);
434 public char[] getName() { return name(c); }
435 public char[] getEnclosingTypeName() { return name(c.getDeclaringClass()); }
436 public char[] getSuperclassName() { return name(c.getSuperclass()); }
437 public IBinaryField[] getFields() { return f; }
438 public char[][] getInterfaceNames() { return inf; }
439 public IBinaryNestedType[] getMemberTypes() { return nested; }
440 public IBinaryMethod[] getMethods() { return meth; }
441 public int getModifiers() { return c.getModifiers(); }
443 public boolean isBinaryType() { return true; }
444 public boolean isClass() { return true; }
445 public boolean isInterface() { return c.isInterface(); }
446 public boolean isAnonymous() { return false; }
447 public boolean isLocal() { return false; } // FIXME
448 public boolean isMember() { return false; } // FIXME
449 public char[] sourceFileName() { return null; }
450 public char[] getFileName() { return null; }
452 public boolean equals(Object o) {
453 return o == this || super.equals(o) ||
454 (o != null && o instanceof LoadedClass &&
455 c.equals(((LoadedClass)o).c));
460 // Compiler Parameters ////////////////////////////////////////////////////
462 /** Used by compiler to resolve classes. */
463 final INameEnvironment env = new INameEnvironment() {
464 public NameEnvironmentAnswer findType(char[][] c) { return findType(name(c), pack(c)); }
465 public NameEnvironmentAnswer findType(char[] n, char[][] p) {
466 if (verbose) System.out.print("findType: "+ str(p, '.') + "."+new String(n));
469 Class c = Class.forName(str(p, '.') + '.' + new String(n));
470 if (verbose) System.out.println(" found in classloader: "+ c);
471 IBinaryType b = (IBinaryType)loaded.get(c);
472 if (b == null) loaded.put(c, b = new LoadedClass(c));
473 return new NameEnvironmentAnswer(b);
474 } catch (ClassNotFoundException e) {}
476 // cut out searches for java.* packages in sources list
477 if (p.length > 0 && eq(p[0], "java".toCharArray())) {
478 if (verbose) System.out.println(" not found, unknown java.*");
483 for (int i=0; i < sources.length; i++) {
484 Source s = sources[i];
485 if (eq(n, s.n) && eq(p, s.p)) {
486 if (s.reader != null) {
487 if (verbose) System.out.println(" found reader");
488 return new NameEnvironmentAnswer(s.reader);
490 if (s.compiled != null) {
491 if (verbose) System.out.println(" found compiled, new reader");
492 s.reader = new ClassFileReader(s.compiled,
493 s.orig.getName().toCharArray(), true);
494 return new NameEnvironmentAnswer(s.reader);
496 if (verbose) System.out.println(" found unit");
497 return new NameEnvironmentAnswer(sources[i].unit);
500 } catch (ClassFormatException e) {
501 System.out.println("Unexpected ClassFormatException"); // FIXME
502 e.printStackTrace(); return null;
504 if (verbose) System.out.println(" not found");
507 public boolean isPackage(char[][] parent, char[] name) {
508 if (verbose) System.out.println("isPackage: "+ str(parent, '.') + "."+new String(name));
509 String parentName = str(parent, '/');
510 for (int i=0; i < sources.length; i++) {
511 if (eq(name, sources[i].n) && eq(parent, sources[i].p)) return false;
512 if (eq(pack(sources[i].p), parent) && eq(name(sources[i].p), name)) return true;
515 loader.getResource(parentName + ".class") == null &&
516 loader.getResource(parentName + '/' + new String(name) + ".class") == null;
518 public void cleanup() {}
521 /** Used by compiler to decide what do with problems.. */
522 private final IErrorHandlingPolicy policy =
523 DefaultErrorHandlingPolicies.proceedWithAllProblems();
525 /** Used by compiler for general options. */
526 private final Map settings = new HashMap();
528 settings.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE);
529 settings.put(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE);
530 settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_3);
531 settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_1);
534 /** Used by compiler for processing compiled classes and their errors. */
535 private final ICompilerRequestor results = new ICompilerRequestor() {
536 public void acceptResult(CompilationResult result) {
537 if (verbose) System.out.println("got result: "+result);
538 if (result.hasProblems()) {
540 IProblem[] p = result.getProblems();
542 for (int i=0; i < p.length; i++) {
543 if (p[i].isError()) { o = out; err = true; }
546 o.print(p[i].getOriginatingFileName());
548 o.print(p[i].getSourceLineNumber());
550 o.print(p[i].isError() ? " error: " : " warning: ");
551 o.println(p[i].getMessage());
554 if (err) { hasErrors = true; return; }
557 ClassFile[] c = result.getClassFiles();
558 for (int i=0; i < c.length; i++) {
560 // build package path to new class file
561 File path = builddir;
562 char[][] name = c[i].getCompoundName();
563 path = new File(builddir, str(pack(name), '/'));
564 if (!path.exists()) path.mkdirs();
566 // write new class file
567 path = new File(path, new String(name(name)) + ".class");
568 OutputStream o = new BufferedOutputStream(
569 new FileOutputStream(path));
570 o.write(c[i].getBytes());
572 } catch (IOException e) {
573 System.out.println("IOException writing class"); // FIXME
580 /** Problem creater for compiler. */
581 private final IProblemFactory problems = new DefaultProblemFactory();
584 // Helper Functiosn ///////////////////////////////////////////////////////
586 /** Convert source file path into class name block.
587 * eg. in: java/lang/String.java -> { {java} {lang} {String} } */
588 private char[][] classname(String name) {
589 String delim = name.indexOf('/') == -1 ? "." : "/";
591 if (name.endsWith(".java")) name = name.substring(0, name.length() - 5);
592 if (name.endsWith(".class")) name = name.substring(0, name.length() - 6);
593 if (name.startsWith(delim)) name = name.substring(1);
595 StringTokenizer st = new StringTokenizer(name, delim);
596 char[][] n = new char[st.countTokens()][];
597 for (int i=0; st.hasMoreTokens(); i++) n[i] = st.nextToken().toCharArray();
601 /** Convert class name into a String. */
602 private static String str(char[][] name, char delim) {
603 StringBuffer b = new StringBuffer();
604 for (int i=0; name != null && i < name.length; i++) {
605 if (name[i] == null || name[i].length == 0) continue;
606 if (i > 0) b.append(delim);
612 /** Returns the package component of a class name.
613 * Effectively returns char[length - 1][]. */
614 private static char[][] pack(char[][] c) {
615 char[][] p = new char[c.length - 1][];
616 for (int i=0; i < p.length; i++) p[i] = c[i];
620 /** Returns the direct-name component of a class name.
621 * eg. String from java.lang.String */
622 private static char[] name(char[][] c) { return c[c.length - 1]; }
624 /** Returns true of contents of both char arrays are equal. */
625 private static boolean eq(char[][] c1, char[][] c2) {
626 if (c1 == null || c2 == null) return c1 == c2;
627 if (c1.length != c2.length) return false;
628 for (int i=0; i < c1.length; i++) if (!eq(c1[i], c2[i])) return false;
632 /** Returns true of contents of both char arrays are equal. */
633 private static boolean eq(char[] c1, char[] c2) {
634 if (c1 == null || c2 == null) return c1 == c2;
635 if (c1.length != c2.length) return false;
636 for (int i=0; i < c1.length; i++) if (c1[i] != c2[i]) return false;
640 /** Returns class name as per VM Spec 4.2. eg. java/lang/String */
641 private static char[] name(Class c) {
642 return c == null ? null : c.getName().replace('.', '/').toCharArray();
645 /** Returns the type name of a class as per VM Spec 4.3.2. */
646 private static char[] typeName(Class p) {
647 StringBuffer sb = new StringBuffer();
649 return sb.toString().toCharArray();
652 /** Returns the type name of a class as per VM Spec 4.3.2.
653 * eg. int -> I, String -> Ljava/lang/String; */
654 private static void typeName(Class p, StringBuffer sb) {
655 String name = p.getName();
656 switch (name.charAt(0)) {
657 case 'B': case 'C': case 'D': case 'F': case 'I':
658 case 'J': case 'S': case 'Z': case 'V': case '[':
659 sb.append(name(p)); break;
661 case 'b': if (name.equals("boolean")) { sb.append('Z'); break; }
662 if (name.equals("byte")) { sb.append('B'); break; }
663 case 'c': if (name.equals("char")) { sb.append('C'); break; }
664 case 'd': if (name.equals("double")) { sb.append('D'); break; }
665 case 'f': if (name.equals("float")) { sb.append('F'); break; }
666 case 'i': if (name.equals("int")) { sb.append('I'); break; }
667 case 'l': if (name.equals("long")) { sb.append('J'); break; }
668 case 's': if (name.equals("short")) { sb.append('S'); break; }
669 case 'v': if (name.equals("void")) { sb.append('V'); break; }
671 sb.append('L'); sb.append(name(p)); sb.append(';');
675 /** Returns the descriptor of a method per VM Spec 4.3.3.
676 * eg. int get(String n, boolean b) -> (Ljava/lang/String;B)I */
677 private static char[] descriptor(Class[] p, Class r) {
678 StringBuffer sb = new StringBuffer();
680 if (p != null) for (int i=0; i < p.length; i++) typeName(p[i], sb);
682 if (r != null) typeName(r, sb);
683 return sb.toString().toCharArray();