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 if (args.length == 0) args = new String[] { "--help" };
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)) {
37 if (args[i].equals("--help")) printHelp();
38 else System.out.println("Unknown switch: -");
41 if (i == args.length - 1) {
42 System.out.println("Missing parameter: "+args[i]); return; }
46 if (i == args.length - 1) {
47 System.out.println("Missing parameter: "+args[i]); return; }
51 if (i == args.length - 1) {
52 System.out.println("Missing parameter: "+args[i]); return; }
61 } else srcdir.add(args[i]);
64 Compiler c = new Compiler();
65 if (blddir != null) c.setBuildDir(blddir);
66 if (source != null) c.setSource(source);
67 if (target != null) c.setTarget(target);
69 String[] s = new String[srcdir.size()];
73 c.setVerbose(verbose);
76 private static void printHelp() {
77 System.out.println("Usage java -cp ... org.ibex.tool.Compiler [options] <source dir> ...");
78 System.out.println("Options:");
79 System.out.println(" -d <directory> Location for generated class files.");
80 System.out.println(" -s <release> Compile with specified source compatibility.");
81 System.out.println(" -t <release> Compile with specified class file compatibility.");
82 System.out.println(" -v Verbose output.");
83 System.out.println(" -h or --help Print this message.");
84 System.out.println("");
88 // Compiler Interface /////////////////////////////////////////////////////
90 private ClassLoader loader = ClassLoader.getSystemClassLoader();
91 private Map loaded = new HashMap();
92 private PrintWriter out = new PrintWriter(System.out);
93 private Preprocessor preprocessor;
95 private Source[] sources;
97 private File builddir = new File(".");
98 private String[] sourcedirs = new String[0];
100 private PrintWriter warn;
101 private boolean hasErrors;
102 private boolean verbose = false;
105 List defs = Collections.EMPTY_LIST;
107 String define = System.getProperty("org.ibex.tool.preprocessor.define");
108 if (define != null) {
109 defs = new ArrayList();
110 StringTokenizer st = new StringTokenizer(define.toUpperCase(), ",");
111 while (st.hasMoreTokens()) defs.add(st.nextToken().trim());
114 preprocessor = new Preprocessor(null, null, defs);
118 public void setBuildDir(String dir) { builddir = new File(dir == null ? "." : dir); }
119 public void setSourceDirs(String[] dir) { sourcedirs = dir; }
121 /** Pass CompilerOptions.VERSION_1_*. A String of form "1.1", ".2", etc. */
122 public void setSource(String v) { settings.put(CompilerOptions.OPTION_Source, v); }
124 /** Pass CompilerOptions.VERSION_1_*. A String of form "1.1", ".2", etc. */
125 public void setTarget(String v) { settings.put(CompilerOptions.OPTION_TargetPlatform, v); }
127 public void setBuilddir(File f) { builddir = f; }
129 public void setVerbose(boolean v) { verbose = v; }
131 public void compile() {
132 List s = new ArrayList();
133 for (int i=0; i < sourcedirs.length; i++) {
134 File src = new File(sourcedirs[i]);
136 if (verbose) System.err.println("source directory not found: "+sourcedirs[i]);
139 filterSources(s, src, new char[0][], sourcedirs[i]);
142 if (verbose) System.out.println("working with "+s.size() +" sources");
143 sources = new Source[s.size()]; s.toArray(sources);
144 ICompilationUnit[] units = new ICompilationUnit[s.size()];
145 int u = 0; for (int i=0; i < sources.length; i++)
146 if (sources[i].compiled == null) units[u++] = sources[i].unit;
147 if (u != units.length) {
148 ICompilationUnit[] newu = new ICompilationUnit[u];
149 System.arraycopy(units, 0, newu, 0, u);
155 StringWriter sw = new StringWriter();
156 StringBuffer w = sw.getBuffer();
157 warn = new PrintWriter(sw);
159 org.eclipse.jdt.internal.compiler.Compiler jdt =
160 new org.eclipse.jdt.internal.compiler.Compiler(
161 env, policy, settings, results, problems);
164 if (!hasErrors) { out.write(w.toString()); out.flush(); }
168 private final FilenameFilter filterSrcs = new FilenameFilter() {
169 public boolean accept(File dir, String name) { return name.endsWith(".java"); }
171 private final FileFilter filterDirs = new FileFilter() {
172 public boolean accept(File path) { return path.isDirectory(); }
174 private byte[] bytes(File bfile) {
175 byte[] bytes = new byte[2 * 1024];
178 InputStream bin = new FileInputStream(bfile);
179 while ((in = bin.read(bytes, pos, bytes.length - pos)) != -1) {
181 if (pos == bytes.length) {
182 byte[] newbytes= new byte[pos * 2];
183 System.arraycopy(bytes, 0, newbytes, 0, pos);
188 } catch (IOException e) {
189 System.out.println("Error reading class file"); // FIXME
190 e.printStackTrace(); return null;
193 if (pos != bytes.length) {
194 byte[] newbytes= new byte[pos * 2];
195 System.arraycopy(bytes, 0, newbytes, 0, pos);
201 private void filterSources(List s, File dir, char[][] pack, String srcdir) {
202 List bclasses = new ArrayList();
203 File bdir = new File(builddir, str(pack, File.separatorChar));
205 // add the java files in this directory
206 File[] ja = dir.listFiles(filterSrcs);
207 for (int i=0; i < ja.length; i++) {
208 char[] n = name(classname(ja[i].getName()));
209 Source src = new Source(ja[i], n, pack, srcdir);
211 // skip the file if the build version is newer than the source
212 String bclass = new String(n);
213 File bfile = new File(bdir, bclass + ".class");
214 if (bfile.lastModified() > ja[i].lastModified()) {
215 src.compiled = bytes(bfile);
216 bclasses.add(bclass);
222 // process the inner classes of any binary files
223 for (int i=0; i < bclasses.size(); i++) {
224 final String bc = (String)bclasses.get(i);
225 final FilenameFilter f = new FilenameFilter() {
226 public boolean accept(File dir, String name) {
227 return name.length() > bc.length() && name.startsWith(bc) &&
228 name.charAt(bc.length()) == '$' && name.endsWith(".class");
231 File[] bfile = bdir.listFiles(f);
232 for (int j=0; j < bfile.length; j++) {
233 Source src = new Source(bfile[j],
234 name(classname(bfile[j].getName())), pack, srcdir);
235 src.compiled = bytes(bfile[j]);
240 // add the subdirectories as packages
241 File[] d = dir.listFiles(filterDirs);
242 for (int i=0; i < d.length; i++) {
243 char[][] newpack = new char[pack.length + 1][];
244 for (int j=0; j < pack.length; j++) newpack[j] = pack[j];
245 newpack[pack.length] = d[i].getName().toCharArray();
246 filterSources(s, d[i], newpack, srcdir);
251 /** Represents a file to be compiled. */
254 char[] n; char[][] p;
256 char[] processed = null;
257 byte[] compiled = null;
258 ClassFileReader reader = null;
260 final ICompilationUnit unit = new ICompilationUnit() {
261 public char[] getMainTypeName() { return n; }
262 public char[][] getPackageName() { return p; }
263 public char[] getFileName() { return fileName; }
264 public char[] getContents() {
265 if (processed != null) return processed;
268 Reader r = new InputStreamReader(new BufferedInputStream(
269 new FileInputStream(orig)));
270 StringWriter w = new StringWriter();
273 synchronized (preprocessor) {
274 preprocessor.setReader(r);
275 preprocessor.setWriter(w);
276 err = preprocessor.process();
279 if (err.size() > 0) {
280 for (int i=0; i < err.size(); i++) {
281 Preprocessor.Warning warn = (Preprocessor.Warning)err.get(i);
282 out.print(getFileName());
284 out.print(warn.getLine());
286 out.print(warn instanceof Preprocessor.Error ?
287 " error: " : " warning: ");
288 out.println(warn.getMessage());
293 processed = w.toString().toCharArray();
294 } catch (IOException e) {
295 System.out.println("IOException: "+e); // FIXME
303 private Source(File o, char[] n, char[][] p, String srcdir) {
304 orig = o; this.n = n; this.p = p;
305 String file = srcdir;
306 file += File.separatorChar + str(p, File.separatorChar);
307 file += File.separatorChar + new String(n) + ".java";
308 fileName = file.toCharArray();
312 // ClassLoader Wrappers ///////////////////////////////////////////////////
314 final static class LoadedNestedType implements IBinaryNestedType {
316 LoadedNestedType(Class c) { this.c = c; }
317 public char[] getName() { return name(c); }
318 public char[] getEnclosingTypeName() { return name(c.getDeclaringClass()); }
319 public int getModifiers() { return c.getModifiers(); }
322 final static class LoadedField implements IBinaryField {
326 LoadedField(Field f) {
328 int m = f.getModifiers();
330 c = Constant.NotAConstant;
331 if (Modifier.isFinal(m) && Modifier.isStatic(m)) {
333 Class type = f.getType();
334 if (type == Boolean.TYPE) {
335 c = new BooleanConstant(f.getBoolean(null));
336 } else if (type == Byte.TYPE) {
337 c = new ByteConstant(f.getByte(null));
338 } else if (type == Character.TYPE) {
339 c = new CharConstant(f.getChar(null));
340 } else if (type == Double.TYPE) {
341 c = new DoubleConstant(f.getDouble(null));
342 } else if (type == Float.TYPE) {
343 c = new FloatConstant(f.getFloat(null));
344 } else if (type == Integer.TYPE) {
345 c = new IntConstant(f.getInt(null));
346 } else if (type == Long.TYPE) {
347 c = new LongConstant(f.getLong(null));
348 } else if (type == Short.TYPE) {
349 c = new ShortConstant(f.getShort(null));
350 } else if (type == String.class) {
351 c = new StringConstant((String)f.get(null));
353 } catch (IllegalAccessException e) {}
356 public Constant getConstant() { return c; }
357 public char[] getTypeName() { return typeName(f.getType()); }
358 public char[] getName() { return f.getName().toCharArray(); }
359 public int getModifiers() { return f.getModifiers(); }
362 final static class LoadedConstructor implements IBinaryMethod {
363 private Constructor c;
367 LoadedConstructor(Constructor c) {
370 Class[] exs = c.getExceptionTypes();
371 ex = new char[exs.length][];
372 for (int i=0; i < ex.length; i++) ex[i] = name(exs[i]);
374 desc = descriptor(c.getParameterTypes(), null);
376 public int getModifiers() { return c.getModifiers(); }
377 public char[] getSelector() { return c.getName().toCharArray(); }
378 public boolean isConstructor() { return true; }
379 public boolean isClinit() { return false; }
380 public char[][] getArgumentNames() { return null; }
381 public char[][] getExceptionTypeNames() { return ex; }
382 public char[] getMethodDescriptor() { return desc; }
385 final static class LoadedMethod implements IBinaryMethod {
390 LoadedMethod(Method m) {
393 Class[] exs = m.getExceptionTypes();
394 ex = new char[exs.length][];
395 for (int i=0; i < ex.length; i++) ex[i] = name(exs[i]);
397 desc = descriptor(m.getParameterTypes(), m.getReturnType());
399 public int getModifiers() { return m.getModifiers(); }
400 public char[] getSelector() { return m.getName().toCharArray(); }
401 public boolean isConstructor() { return false; }
402 public boolean isClinit() { return false; }
403 public char[][] getArgumentNames() { return null; } // FEATURE: does this do anything cool?
404 public char[][] getExceptionTypeNames() { return ex; }
405 public char[] getMethodDescriptor() { return desc; }
408 final static class LoadedClass implements IBinaryType {
410 private IBinaryField[] f;
411 private char[][] inf;
412 private IBinaryNestedType[] nested;
413 private IBinaryMethod[] meth = null;
415 LoadedClass(Class c) {
418 Field[] fields = c.getDeclaredFields();
419 List flist = new ArrayList(fields.length);
420 for (int i=0; i < fields.length; i++)
421 if (!Modifier.isPrivate(fields[i].getModifiers()))
422 flist.add(new LoadedField(fields[i]));
423 f = new IBinaryField[flist.size()];
426 Class[] interfaces = c.getInterfaces();
427 inf = new char[interfaces.length][];
428 for (int i=0; i < inf.length; i++) inf[i] = name(interfaces[i]);
430 Class[] classes = c.getClasses();
431 nested = new IBinaryNestedType[classes.length];
432 for (int i=0; i < nested.length; i++)
433 nested[i] = new LoadedNestedType(classes[i]);
435 Constructor[] constructors = c.getDeclaredConstructors();
436 Method[] methods = c.getDeclaredMethods();
437 if (methods.length + constructors.length > 0) {
438 List m = new ArrayList(methods.length + constructors.length);
439 for (int j=0; j < methods.length; j++)
440 if (!Modifier.isPrivate(methods[j].getModifiers()))
441 m.add(new LoadedMethod(methods[j]));
442 for (int j=0; j < constructors.length; j++)
443 if (!Modifier.isPrivate(constructors[j].getModifiers()))
444 m.add(new LoadedConstructor(constructors[j]));
445 meth = new IBinaryMethod[m.size()]; m.toArray(meth);
449 public char[] getName() { return name(c); }
450 public char[] getEnclosingTypeName() { return name(c.getDeclaringClass()); }
451 public char[] getSuperclassName() { return name(c.getSuperclass()); }
452 public IBinaryField[] getFields() { return f; }
453 public char[][] getInterfaceNames() { return inf; }
454 public IBinaryNestedType[] getMemberTypes() { return nested; }
455 public IBinaryMethod[] getMethods() { return meth; }
456 public int getModifiers() { return c.getModifiers(); }
458 public boolean isBinaryType() { return true; }
459 public boolean isClass() { return true; }
460 public boolean isInterface() { return c.isInterface(); }
461 public boolean isAnonymous() { return false; }
462 public boolean isLocal() { return false; } // FIXME
463 public boolean isMember() { return false; } // FIXME
464 public char[] sourceFileName() { return null; }
465 public char[] getFileName() { return null; }
467 public boolean equals(Object o) {
468 return o == this || super.equals(o) ||
469 (o != null && o instanceof LoadedClass &&
470 c.equals(((LoadedClass)o).c));
475 // Compiler Parameters ////////////////////////////////////////////////////
477 /** Used by compiler to resolve classes. */
478 final INameEnvironment env = new INameEnvironment() {
479 public NameEnvironmentAnswer findType(char[][] c) { return findType(name(c), pack(c)); }
480 public NameEnvironmentAnswer findType(char[] n, char[][] p) {
481 if (verbose) System.out.print("findType: "+ str(p, '.') + "."+new String(n));
484 Class c = Class.forName(str(p, '.') + '.' + new String(n));
485 if (verbose) System.out.println(" found in classloader: "+ c);
486 IBinaryType b = (IBinaryType)loaded.get(c);
487 if (b == null) loaded.put(c, b = new LoadedClass(c));
488 return new NameEnvironmentAnswer(b);
489 } catch (ClassNotFoundException e) {}
491 // cut out searches for java.* packages in sources list
492 if (p.length > 0 && eq(p[0], "java".toCharArray())) {
493 if (verbose) System.out.println(" not found, unknown java.*");
498 for (int i=0; i < sources.length; i++) {
499 Source s = sources[i];
500 if (eq(n, s.n) && eq(p, s.p)) {
501 if (s.reader != null) {
502 if (verbose) System.out.println(" found reader");
503 return new NameEnvironmentAnswer(s.reader);
505 if (s.compiled != null) {
506 if (verbose) System.out.println(" found compiled, new reader");
507 s.reader = new ClassFileReader(s.compiled,
508 s.orig.getName().toCharArray(), true);
509 return new NameEnvironmentAnswer(s.reader);
511 if (verbose) System.out.println(" found unit");
512 return new NameEnvironmentAnswer(sources[i].unit);
515 } catch (ClassFormatException e) {
516 System.out.println("Unexpected ClassFormatException"); // FIXME
517 e.printStackTrace(); return null;
519 if (verbose) System.out.println(" not found");
522 public boolean isPackage(char[][] parent, char[] name) {
523 if (verbose) System.out.println("isPackage: "+ str(parent, '.') + "."+new String(name));
524 String parentName = str(parent, '/');
525 for (int i=0; i < sources.length; i++) {
526 if (eq(name, sources[i].n) && eq(parent, sources[i].p)) return false;
527 if (eq(pack(sources[i].p), parent) && eq(name(sources[i].p), name)) return true;
530 loader.getResource(parentName + ".class") == null &&
531 loader.getResource(parentName + '/' + new String(name) + ".class") == null;
533 public void cleanup() {}
536 /** Used by compiler to decide what do with problems.. */
537 private final IErrorHandlingPolicy policy =
538 DefaultErrorHandlingPolicies.proceedWithAllProblems();
540 /** Used by compiler for general options. */
541 private final Map settings = new HashMap();
543 settings.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE);
544 settings.put(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE);
545 settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_3);
546 settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_1);
549 /** Used by compiler for processing compiled classes and their errors. */
550 private final ICompilerRequestor results = new ICompilerRequestor() {
551 public void acceptResult(CompilationResult result) {
552 if (verbose) System.out.println("got result: "+result);
553 if (result.hasProblems()) {
555 IProblem[] p = result.getProblems();
557 for (int i=0; i < p.length; i++) {
558 if (p[i].isError()) { o = out; err = true; }
561 o.print(p[i].getOriginatingFileName());
563 o.print(p[i].getSourceLineNumber());
565 o.print(p[i].isError() ? " error: " : " warning: ");
566 o.println(p[i].getMessage());
569 if (err) { hasErrors = true; return; }
572 ClassFile[] c = result.getClassFiles();
573 for (int i=0; i < c.length; i++) {
575 // build package path to new class file
576 File path = builddir;
577 char[][] name = c[i].getCompoundName();
578 path = new File(builddir, str(pack(name), '/'));
579 if (!path.exists()) path.mkdirs();
581 // write new class file
582 path = new File(path, new String(name(name)) + ".class");
583 OutputStream o = new BufferedOutputStream(
584 new FileOutputStream(path));
585 o.write(c[i].getBytes());
587 } catch (IOException e) {
588 System.out.println("IOException writing class"); // FIXME
595 /** Problem creater for compiler. */
596 private final IProblemFactory problems = new DefaultProblemFactory();
599 // Helper Functiosn ///////////////////////////////////////////////////////
601 /** Convert source file path into class name block.
602 * eg. in: java/lang/String.java -> { {java} {lang} {String} } */
603 private char[][] classname(String name) {
604 String delim = name.indexOf('/') == -1 ? "." : "/";
606 if (name.endsWith(".java")) name = name.substring(0, name.length() - 5);
607 if (name.endsWith(".class")) name = name.substring(0, name.length() - 6);
608 if (name.startsWith(delim)) name = name.substring(1);
610 StringTokenizer st = new StringTokenizer(name, delim);
611 char[][] n = new char[st.countTokens()][];
612 for (int i=0; st.hasMoreTokens(); i++) n[i] = st.nextToken().toCharArray();
616 /** Convert class name into a String. */
617 private static String str(char[][] name, char delim) {
618 StringBuffer b = new StringBuffer();
619 for (int i=0; name != null && i < name.length; i++) {
620 if (name[i] == null || name[i].length == 0) continue;
621 if (i > 0) b.append(delim);
627 /** Returns the package component of a class name.
628 * Effectively returns char[length - 1][]. */
629 private static char[][] pack(char[][] c) {
630 char[][] p = new char[c.length - 1][];
631 for (int i=0; i < p.length; i++) p[i] = c[i];
635 /** Returns the direct-name component of a class name.
636 * eg. String from java.lang.String */
637 private static char[] name(char[][] c) { return c[c.length - 1]; }
639 /** Returns true of contents of both char arrays are equal. */
640 private static boolean eq(char[][] c1, char[][] c2) {
641 if (c1 == null || c2 == null) return c1 == c2;
642 if (c1.length != c2.length) return false;
643 for (int i=0; i < c1.length; i++) if (!eq(c1[i], c2[i])) return false;
647 /** Returns true of contents of both char arrays are equal. */
648 private static boolean eq(char[] c1, char[] c2) {
649 if (c1 == null || c2 == null) return c1 == c2;
650 if (c1.length != c2.length) return false;
651 for (int i=0; i < c1.length; i++) if (c1[i] != c2[i]) return false;
655 /** Returns class name as per VM Spec 4.2. eg. java/lang/String */
656 private static char[] name(Class c) {
657 return c == null ? null : c.getName().replace('.', '/').toCharArray();
660 /** Returns the type name of a class as per VM Spec 4.3.2. */
661 private static char[] typeName(Class p) {
662 StringBuffer sb = new StringBuffer();
664 return sb.toString().toCharArray();
667 /** Returns the type name of a class as per VM Spec 4.3.2.
668 * eg. int -> I, String -> Ljava/lang/String; */
669 private static void typeName(Class p, StringBuffer sb) {
670 String name = p.getName();
671 switch (name.charAt(0)) {
672 case 'B': case 'C': case 'D': case 'F': case 'I':
673 case 'J': case 'S': case 'Z': case 'V': case '[':
674 sb.append(name(p)); break;
676 case 'b': if (name.equals("boolean")) { sb.append('Z'); break; }
677 if (name.equals("byte")) { sb.append('B'); break; }
678 case 'c': if (name.equals("char")) { sb.append('C'); break; }
679 case 'd': if (name.equals("double")) { sb.append('D'); break; }
680 case 'f': if (name.equals("float")) { sb.append('F'); break; }
681 case 'i': if (name.equals("int")) { sb.append('I'); break; }
682 case 'l': if (name.equals("long")) { sb.append('J'); break; }
683 case 's': if (name.equals("short")) { sb.append('S'); break; }
684 case 'v': if (name.equals("void")) { sb.append('V'); break; }
686 sb.append('L'); sb.append(name(p)); sb.append(';');
690 /** Returns the descriptor of a method per VM Spec 4.3.3.
691 * eg. int get(String n, boolean b) -> (Ljava/lang/String;B)I */
692 private static char[] descriptor(Class[] p, Class r) {
693 StringBuffer sb = new StringBuffer();
695 if (p != null) for (int i=0; i < p.length; i++) typeName(p[i], sb);
697 if (r != null) typeName(r, sb);
698 return sb.toString().toCharArray();