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; }
62 } else srcdir.add(args[i]);
65 Compiler c = new Compiler();
66 if (blddir != null) c.setBuildDir(blddir);
67 if (source != null) c.setSource(source);
68 if (target != null) c.setTarget(target);
70 String[] s = new String[srcdir.size()];
74 c.setVerbose(verbose);
77 private static void printHelp() {
78 System.out.println("Usage java -cp ... org.ibex.tool.Compiler [options] <source dir> ...");
79 System.out.println("Options:");
80 System.out.println(" -d <directory> Location for generated class files.");
81 System.out.println(" -s <release> Compile with specified source compatibility.");
82 System.out.println(" -t <release> Compile with specified class file compatibility.");
83 System.out.println(" -v Verbose output.");
84 System.out.println(" -h or --help Print this message.");
85 System.out.println("");
89 // Compiler Interface /////////////////////////////////////////////////////
91 private ClassLoader loader = ClassLoader.getSystemClassLoader();
92 private Map loaded = new HashMap();
93 private PrintWriter out = new PrintWriter(System.out);
94 private Preprocessor preprocessor;
96 private Source[] sources;
98 private File builddir = new File(".");
99 private String[] sourcedirs = new String[0];
101 private PrintWriter warn;
102 private boolean hasErrors;
103 private boolean verbose = false;
106 List defs = Collections.EMPTY_LIST;
108 String define = System.getProperty("org.ibex.tool.preprocessor.define");
109 if (define != null) {
110 defs = new ArrayList();
111 StringTokenizer st = new StringTokenizer(define.toUpperCase(), ",");
112 while (st.hasMoreTokens()) defs.add(st.nextToken().trim());
115 preprocessor = new Preprocessor(null, null, defs);
119 public void setBuildDir(String dir) { builddir = new File(dir == null ? "." : dir); }
120 public void setSourceDirs(String[] dir) { sourcedirs = dir; }
122 /** Pass CompilerOptions.VERSION_1_*. A String of form "1.1", ".2", etc. */
123 public void setSource(String v) { settings.put(CompilerOptions.OPTION_Source, v); }
125 /** Pass CompilerOptions.VERSION_1_*. A String of form "1.1", ".2", etc. */
126 public void setTarget(String v) { settings.put(CompilerOptions.OPTION_TargetPlatform, v); }
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 for (int i=0; i < err.size(); i++) {
280 Preprocessor.Warning warn = (Preprocessor.Warning)err.get(i);
281 out.print(getFileName());
283 out.print(warn.getLine());
285 out.print(warn instanceof Preprocessor.Error ?
286 " error: " : " warning: ");
287 out.println(warn.getMessage());
292 processed = w.toString().toCharArray();
293 } catch (IOException e) {
294 System.out.println("IOException: "+e); // FIXME
302 private Source(File o, char[] n, char[][] p, String srcdir) {
303 orig = o; this.n = n; this.p = p;
304 String file = srcdir;
305 file += File.separatorChar + str(p, File.separatorChar);
306 file += File.separatorChar + new String(n) + ".java";
307 fileName = file.toCharArray();
311 // ClassLoader Wrappers ///////////////////////////////////////////////////
313 final static class LoadedNestedType implements IBinaryNestedType {
315 LoadedNestedType(Class c) { this.c = c; }
316 public char[] getName() { return name(c); }
317 public char[] getEnclosingTypeName() { return name(c.getDeclaringClass()); }
318 public int getModifiers() { return c.getModifiers(); }
321 final static class LoadedField implements IBinaryField {
325 LoadedField(Field f) {
327 int m = f.getModifiers();
329 c = Constant.NotAConstant;
330 if (Modifier.isFinal(m) && Modifier.isStatic(m)) {
332 Class type = f.getType();
333 if (type == Boolean.TYPE) {
334 c = new BooleanConstant(f.getBoolean(null));
335 } else if (type == Byte.TYPE) {
336 c = new ByteConstant(f.getByte(null));
337 } else if (type == Character.TYPE) {
338 c = new CharConstant(f.getChar(null));
339 } else if (type == Double.TYPE) {
340 c = new DoubleConstant(f.getDouble(null));
341 } else if (type == Float.TYPE) {
342 c = new FloatConstant(f.getFloat(null));
343 } else if (type == Integer.TYPE) {
344 c = new IntConstant(f.getInt(null));
345 } else if (type == Long.TYPE) {
346 c = new LongConstant(f.getLong(null));
347 } else if (type == Short.TYPE) {
348 c = new ShortConstant(f.getShort(null));
349 } else if (type == String.class) {
350 c = new StringConstant((String)f.get(null));
352 } catch (IllegalAccessException e) {}
355 public Constant getConstant() { return c; }
356 public char[] getTypeName() { return typeName(f.getType()); }
357 public char[] getName() { return f.getName().toCharArray(); }
358 public int getModifiers() { return f.getModifiers(); }
361 final static class LoadedConstructor implements IBinaryMethod {
362 private Constructor c;
366 LoadedConstructor(Constructor c) {
369 Class[] exs = c.getExceptionTypes();
370 ex = new char[exs.length][];
371 for (int i=0; i < ex.length; i++) ex[i] = name(exs[i]);
373 desc = descriptor(c.getParameterTypes(), null);
375 public int getModifiers() { return c.getModifiers(); }
376 public char[] getSelector() { return c.getName().toCharArray(); }
377 public boolean isConstructor() { return true; }
378 public boolean isClinit() { return false; }
379 public char[][] getArgumentNames() { return null; }
380 public char[][] getExceptionTypeNames() { return ex; }
381 public char[] getMethodDescriptor() { return desc; }
384 final static class LoadedMethod implements IBinaryMethod {
389 LoadedMethod(Method m) {
392 Class[] exs = m.getExceptionTypes();
393 ex = new char[exs.length][];
394 for (int i=0; i < ex.length; i++) ex[i] = name(exs[i]);
396 desc = descriptor(m.getParameterTypes(), m.getReturnType());
398 public int getModifiers() { return m.getModifiers(); }
399 public char[] getSelector() { return m.getName().toCharArray(); }
400 public boolean isConstructor() { return false; }
401 public boolean isClinit() { return false; }
402 public char[][] getArgumentNames() { return null; } // FEATURE: does this do anything cool?
403 public char[][] getExceptionTypeNames() { return ex; }
404 public char[] getMethodDescriptor() { return desc; }
407 final static class LoadedClass implements IBinaryType {
409 private IBinaryField[] f;
410 private char[][] inf;
411 private IBinaryNestedType[] nested;
412 private IBinaryMethod[] meth = null;
414 LoadedClass(Class c) {
417 Field[] fields = c.getDeclaredFields();
418 List flist = new ArrayList(fields.length);
419 for (int i=0; i < fields.length; i++)
420 if (!Modifier.isPrivate(fields[i].getModifiers()))
421 flist.add(new LoadedField(fields[i]));
422 f = new IBinaryField[flist.size()];
425 Class[] interfaces = c.getInterfaces();
426 inf = new char[interfaces.length][];
427 for (int i=0; i < inf.length; i++) inf[i] = name(interfaces[i]);
429 Class[] classes = c.getClasses();
430 nested = new IBinaryNestedType[classes.length];
431 for (int i=0; i < nested.length; i++)
432 nested[i] = new LoadedNestedType(classes[i]);
434 Constructor[] constructors = c.getDeclaredConstructors();
435 Method[] methods = c.getDeclaredMethods();
436 if (methods.length + constructors.length > 0) {
437 List m = new ArrayList(methods.length + constructors.length);
438 for (int j=0; j < methods.length; j++)
439 if (!Modifier.isPrivate(methods[j].getModifiers()))
440 m.add(new LoadedMethod(methods[j]));
441 for (int j=0; j < constructors.length; j++)
442 if (!Modifier.isPrivate(constructors[j].getModifiers()))
443 m.add(new LoadedConstructor(constructors[j]));
444 meth = new IBinaryMethod[m.size()]; m.toArray(meth);
448 public char[] getName() { return name(c); }
449 public char[] getEnclosingTypeName() { return name(c.getDeclaringClass()); }
450 public char[] getSuperclassName() { return name(c.getSuperclass()); }
451 public IBinaryField[] getFields() { return f; }
452 public char[][] getInterfaceNames() { return inf; }
453 public IBinaryNestedType[] getMemberTypes() { return nested; }
454 public IBinaryMethod[] getMethods() { return meth; }
455 public int getModifiers() { return c.getModifiers(); }
457 public boolean isBinaryType() { return true; }
458 public boolean isClass() { return true; }
459 public boolean isInterface() { return c.isInterface(); }
460 public boolean isAnonymous() { return false; }
461 public boolean isLocal() { return false; } // FIXME
462 public boolean isMember() { return false; } // FIXME
463 public char[] sourceFileName() { return null; }
464 public char[] getFileName() { return null; }
466 public boolean equals(Object o) {
467 return o == this || super.equals(o) ||
468 (o != null && o instanceof LoadedClass &&
469 c.equals(((LoadedClass)o).c));
474 // Compiler Parameters ////////////////////////////////////////////////////
476 /** Used by compiler to resolve classes. */
477 final INameEnvironment env = new INameEnvironment() {
478 public NameEnvironmentAnswer findType(char[][] c) { return findType(name(c), pack(c)); }
479 public NameEnvironmentAnswer findType(char[] n, char[][] p) {
480 if (verbose) System.out.print("findType: "+ str(p, '.') + "."+new String(n));
483 Class c = Class.forName(str(p, '.') + '.' + new String(n));
484 if (verbose) System.out.println(" found in classloader: "+ c);
485 IBinaryType b = (IBinaryType)loaded.get(c);
486 if (b == null) loaded.put(c, b = new LoadedClass(c));
487 return new NameEnvironmentAnswer(b);
488 } catch (ClassNotFoundException e) {}
490 // cut out searches for java.* packages in sources list
491 if (p.length > 0 && eq(p[0], "java".toCharArray())) {
492 if (verbose) System.out.println(" not found, unknown java.*");
497 for (int i=0; i < sources.length; i++) {
498 Source s = sources[i];
499 if (eq(n, s.n) && eq(p, s.p)) {
500 if (s.reader != null) {
501 if (verbose) System.out.println(" found reader");
502 return new NameEnvironmentAnswer(s.reader);
504 if (s.compiled != null) {
505 if (verbose) System.out.println(" found compiled, new reader");
506 s.reader = new ClassFileReader(s.compiled,
507 s.orig.getName().toCharArray(), true);
508 return new NameEnvironmentAnswer(s.reader);
510 if (verbose) System.out.println(" found unit");
511 return new NameEnvironmentAnswer(sources[i].unit);
514 } catch (ClassFormatException e) {
515 System.out.println("Unexpected ClassFormatException"); // FIXME
516 e.printStackTrace(); return null;
518 if (verbose) System.out.println(" not found");
521 public boolean isPackage(char[][] parent, char[] name) {
522 if (verbose) System.out.println("isPackage: "+ str(parent, '.') + "."+new String(name));
523 String parentName = str(parent, '/');
524 for (int i=0; i < sources.length; i++) {
525 if (eq(name, sources[i].n) && eq(parent, sources[i].p)) return false;
526 if (eq(pack(sources[i].p), parent) && eq(name(sources[i].p), name)) return true;
529 loader.getResource(parentName + ".class") == null &&
530 loader.getResource(parentName + '/' + new String(name) + ".class") == null;
532 public void cleanup() {}
535 /** Used by compiler to decide what do with problems.. */
536 private final IErrorHandlingPolicy policy =
537 DefaultErrorHandlingPolicies.proceedWithAllProblems();
539 /** Used by compiler for general options. */
540 private final Map settings = new HashMap();
542 settings.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE);
543 settings.put(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE);
544 settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_3);
545 settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_1);
548 /** Used by compiler for processing compiled classes and their errors. */
549 private final ICompilerRequestor results = new ICompilerRequestor() {
550 public void acceptResult(CompilationResult result) {
551 if (verbose) System.out.println("got result: "+result);
552 if (result.hasProblems()) {
554 IProblem[] p = result.getProblems();
556 for (int i=0; i < p.length; i++) {
557 if (p[i].isError()) { o = out; err = true; }
560 o.print(p[i].getOriginatingFileName());
562 o.print(p[i].getSourceLineNumber());
564 o.print(p[i].isError() ? " error: " : " warning: ");
565 o.println(p[i].getMessage());
568 if (err) { hasErrors = true; return; }
571 ClassFile[] c = result.getClassFiles();
572 for (int i=0; i < c.length; i++) {
574 // build package path to new class file
575 File path = builddir;
576 char[][] name = c[i].getCompoundName();
577 path = new File(builddir, str(pack(name), '/'));
578 if (!path.exists()) path.mkdirs();
580 // write new class file
581 path = new File(path, new String(name(name)) + ".class");
582 OutputStream o = new BufferedOutputStream(
583 new FileOutputStream(path));
584 o.write(c[i].getBytes());
586 } catch (IOException e) {
587 System.out.println("IOException writing class"); // FIXME
594 /** Problem creater for compiler. */
595 private final IProblemFactory problems = new DefaultProblemFactory();
598 // Helper Functiosn ///////////////////////////////////////////////////////
600 /** Convert source file path into class name block.
601 * eg. in: java/lang/String.java -> { {java} {lang} {String} } */
602 private char[][] classname(String name) {
603 String delim = name.indexOf('/') == -1 ? "." : "/";
605 if (name.endsWith(".java")) name = name.substring(0, name.length() - 5);
606 if (name.endsWith(".class")) name = name.substring(0, name.length() - 6);
607 if (name.startsWith(delim)) name = name.substring(1);
609 StringTokenizer st = new StringTokenizer(name, delim);
610 char[][] n = new char[st.countTokens()][];
611 for (int i=0; st.hasMoreTokens(); i++) n[i] = st.nextToken().toCharArray();
615 /** Convert class name into a String. */
616 private static String str(char[][] name, char delim) {
617 StringBuffer b = new StringBuffer();
618 for (int i=0; name != null && i < name.length; i++) {
619 if (name[i] == null || name[i].length == 0) continue;
620 if (i > 0) b.append(delim);
626 /** Returns the package component of a class name.
627 * Effectively returns char[length - 1][]. */
628 private static char[][] pack(char[][] c) {
629 char[][] p = new char[c.length - 1][];
630 for (int i=0; i < p.length; i++) p[i] = c[i];
634 /** Returns the direct-name component of a class name.
635 * eg. String from java.lang.String */
636 private static char[] name(char[][] c) { return c[c.length - 1]; }
638 /** Returns true of contents of both char arrays are equal. */
639 private static boolean eq(char[][] c1, char[][] c2) {
640 if (c1 == null || c2 == null) return c1 == c2;
641 if (c1.length != c2.length) return false;
642 for (int i=0; i < c1.length; i++) if (!eq(c1[i], c2[i])) return false;
646 /** Returns true of contents of both char arrays are equal. */
647 private static boolean eq(char[] c1, char[] c2) {
648 if (c1 == null || c2 == null) return c1 == c2;
649 if (c1.length != c2.length) return false;
650 for (int i=0; i < c1.length; i++) if (c1[i] != c2[i]) return false;
654 /** Returns class name as per VM Spec 4.2. eg. java/lang/String */
655 private static char[] name(Class c) {
656 return c == null ? null : c.getName().replace('.', '/').toCharArray();
659 /** Returns the type name of a class as per VM Spec 4.3.2. */
660 private static char[] typeName(Class p) {
661 StringBuffer sb = new StringBuffer();
663 return sb.toString().toCharArray();
666 /** Returns the type name of a class as per VM Spec 4.3.2.
667 * eg. int -> I, String -> Ljava/lang/String; */
668 private static void typeName(Class p, StringBuffer sb) {
669 String name = p.getName();
670 switch (name.charAt(0)) {
671 case 'B': case 'C': case 'D': case 'F': case 'I':
672 case 'J': case 'S': case 'Z': case 'V': case '[':
673 sb.append(name(p)); break;
675 case 'b': if (name.equals("boolean")) { sb.append('Z'); break; }
676 if (name.equals("byte")) { sb.append('B'); break; }
677 case 'c': if (name.equals("char")) { sb.append('C'); break; }
678 case 'd': if (name.equals("double")) { sb.append('D'); break; }
679 case 'f': if (name.equals("float")) { sb.append('F'); break; }
680 case 'i': if (name.equals("int")) { sb.append('I'); break; }
681 case 'l': if (name.equals("long")) { sb.append('J'); break; }
682 case 's': if (name.equals("short")) { sb.append('S'); break; }
683 case 'v': if (name.equals("void")) { sb.append('V'); break; }
685 sb.append('L'); sb.append(name(p)); sb.append(';');
689 /** Returns the descriptor of a method per VM Spec 4.3.3.
690 * eg. int get(String n, boolean b) -> (Ljava/lang/String;B)I */
691 private static char[] descriptor(Class[] p, Class r) {
692 StringBuffer sb = new StringBuffer();
694 if (p != null) for (int i=0; i < p.length; i++) typeName(p[i], sb);
696 if (r != null) typeName(r, sb);
697 return sb.toString().toCharArray();