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 setVerbose(boolean v) { verbose = v; }
129 public void compile() {
130 List s = new ArrayList();
131 for (int i=0; i < sourcedirs.length; i++) {
132 File src = new File(sourcedirs[i]);
134 if (verbose) System.err.println("source directory not found: "+sourcedirs[i]);
137 filterSources(s, src, new char[0][], sourcedirs[i]);
140 if (verbose) System.out.println("working with "+s.size() +" sources");
141 sources = new Source[s.size()]; s.toArray(sources);
142 ICompilationUnit[] units = new ICompilationUnit[s.size()];
143 int u = 0; for (int i=0; i < sources.length; i++)
144 if (sources[i].compiled == null) units[u++] = sources[i].unit;
145 if (u != units.length) {
146 ICompilationUnit[] newu = new ICompilationUnit[u];
147 System.arraycopy(units, 0, newu, 0, u);
153 StringWriter sw = new StringWriter();
154 StringBuffer w = sw.getBuffer();
155 warn = new PrintWriter(sw);
157 org.eclipse.jdt.internal.compiler.Compiler jdt =
158 new org.eclipse.jdt.internal.compiler.Compiler(
159 env, policy, settings, results, problems);
162 if (!hasErrors) { out.write(w.toString()); out.flush(); }
166 private final FilenameFilter filterSrcs = new FilenameFilter() {
167 public boolean accept(File dir, String name) { return name.endsWith(".java"); }
169 private final FileFilter filterDirs = new FileFilter() {
170 public boolean accept(File path) { return path.isDirectory(); }
172 private byte[] bytes(File bfile) {
173 byte[] bytes = new byte[2 * 1024];
176 InputStream bin = new FileInputStream(bfile);
177 while ((in = bin.read(bytes, pos, bytes.length - pos)) != -1) {
179 if (pos == bytes.length) {
180 byte[] newbytes= new byte[pos * 2];
181 System.arraycopy(bytes, 0, newbytes, 0, pos);
186 } catch (IOException e) {
187 System.out.println("Error reading class file"); // FIXME
188 e.printStackTrace(); return null;
191 if (pos != bytes.length) {
192 byte[] newbytes= new byte[pos * 2];
193 System.arraycopy(bytes, 0, newbytes, 0, pos);
199 private void filterSources(List s, File dir, char[][] pack, String srcdir) {
200 List bclasses = new ArrayList();
201 File bdir = new File(builddir, str(pack, File.separatorChar));
203 // add the java files in this directory
204 File[] ja = dir.listFiles(filterSrcs);
205 for (int i=0; i < ja.length; i++) {
206 char[] n = name(classname(ja[i].getName()));
207 Source src = new Source(ja[i], n, pack, srcdir);
209 // skip the file if the build version is newer than the source
210 String bclass = new String(n);
211 File bfile = new File(bdir, bclass + ".class");
212 if (bfile.lastModified() > ja[i].lastModified()) {
213 src.compiled = bytes(bfile);
214 bclasses.add(bclass);
220 // process the inner classes of any binary files
221 for (int i=0; i < bclasses.size(); i++) {
222 final String bc = (String)bclasses.get(i);
223 final FilenameFilter f = new FilenameFilter() {
224 public boolean accept(File dir, String name) {
225 return name.length() > bc.length() && name.startsWith(bc) &&
226 name.charAt(bc.length()) == '$' && name.endsWith(".class");
229 File[] bfile = bdir.listFiles(f);
230 for (int j=0; j < bfile.length; j++) {
231 Source src = new Source(bfile[j],
232 name(classname(bfile[j].getName())), pack, srcdir);
233 src.compiled = bytes(bfile[j]);
238 // add the subdirectories as packages
239 File[] d = dir.listFiles(filterDirs);
240 for (int i=0; i < d.length; i++) {
241 char[][] newpack = new char[pack.length + 1][];
242 for (int j=0; j < pack.length; j++) newpack[j] = pack[j];
243 newpack[pack.length] = d[i].getName().toCharArray();
244 filterSources(s, d[i], newpack, srcdir);
249 /** Represents a file to be compiled. */
252 char[] n; char[][] p;
254 char[] processed = null;
255 byte[] compiled = null;
256 ClassFileReader reader = null;
258 final ICompilationUnit unit = new ICompilationUnit() {
259 public char[] getMainTypeName() { return n; }
260 public char[][] getPackageName() { return p; }
261 public char[] getFileName() { return fileName; }
262 public char[] getContents() {
263 if (processed != null) return processed;
266 Reader r = new InputStreamReader(new BufferedInputStream(
267 new FileInputStream(orig)));
268 StringWriter w = new StringWriter();
271 synchronized (preprocessor) {
272 preprocessor.setReader(r);
273 preprocessor.setWriter(w);
274 err = preprocessor.process();
277 if (err.size() > 0) {
278 for (int i=0; i < err.size(); i++) {
279 Preprocessor.Warning warn = (Preprocessor.Warning)err.get(i);
280 out.print(getFileName());
282 out.print(warn.getLine());
284 out.print(warn instanceof Preprocessor.Error ?
285 " error: " : " warning: ");
286 out.println(warn.getMessage());
291 processed = w.toString().toCharArray();
292 } catch (IOException e) {
293 System.out.println("IOException: "+e); // FIXME
301 private Source(File o, char[] n, char[][] p, String srcdir) {
302 orig = o; this.n = n; this.p = p;
303 String file = srcdir;
304 file += File.separatorChar + str(p, File.separatorChar);
305 file += File.separatorChar + new String(n) + ".java";
306 fileName = file.toCharArray();
310 // ClassLoader Wrappers ///////////////////////////////////////////////////
312 final static class LoadedNestedType implements IBinaryNestedType {
314 LoadedNestedType(Class c) { this.c = c; }
315 public char[] getName() { return name(c); }
316 public char[] getEnclosingTypeName() { return name(c.getDeclaringClass()); }
317 public int getModifiers() { return c.getModifiers(); }
320 final static class LoadedField implements IBinaryField {
324 LoadedField(Field f) {
326 int m = f.getModifiers();
328 c = Constant.NotAConstant;
329 if (Modifier.isFinal(m) && Modifier.isStatic(m)) {
331 Class type = f.getType();
332 if (type == Boolean.TYPE) {
333 c = new BooleanConstant(f.getBoolean(null));
334 } else if (type == Byte.TYPE) {
335 c = new ByteConstant(f.getByte(null));
336 } else if (type == Character.TYPE) {
337 c = new CharConstant(f.getChar(null));
338 } else if (type == Double.TYPE) {
339 c = new DoubleConstant(f.getDouble(null));
340 } else if (type == Float.TYPE) {
341 c = new FloatConstant(f.getFloat(null));
342 } else if (type == Integer.TYPE) {
343 c = new IntConstant(f.getInt(null));
344 } else if (type == Long.TYPE) {
345 c = new LongConstant(f.getLong(null));
346 } else if (type == Short.TYPE) {
347 c = new ShortConstant(f.getShort(null));
348 } else if (type == String.class) {
349 c = new StringConstant((String)f.get(null));
351 } catch (IllegalAccessException e) {}
354 public Constant getConstant() { return c; }
355 public char[] getTypeName() { return typeName(f.getType()); }
356 public char[] getName() { return f.getName().toCharArray(); }
357 public int getModifiers() { return f.getModifiers(); }
360 final static class LoadedConstructor implements IBinaryMethod {
361 private Constructor c;
365 LoadedConstructor(Constructor c) {
368 Class[] exs = c.getExceptionTypes();
369 ex = new char[exs.length][];
370 for (int i=0; i < ex.length; i++) ex[i] = name(exs[i]);
372 desc = descriptor(c.getParameterTypes(), null);
374 public int getModifiers() { return c.getModifiers(); }
375 public char[] getSelector() { return c.getName().toCharArray(); }
376 public boolean isConstructor() { return true; }
377 public boolean isClinit() { return false; }
378 public char[][] getArgumentNames() { return null; }
379 public char[][] getExceptionTypeNames() { return ex; }
380 public char[] getMethodDescriptor() { return desc; }
383 final static class LoadedMethod implements IBinaryMethod {
388 LoadedMethod(Method m) {
391 Class[] exs = m.getExceptionTypes();
392 ex = new char[exs.length][];
393 for (int i=0; i < ex.length; i++) ex[i] = name(exs[i]);
395 desc = descriptor(m.getParameterTypes(), m.getReturnType());
397 public int getModifiers() { return m.getModifiers(); }
398 public char[] getSelector() { return m.getName().toCharArray(); }
399 public boolean isConstructor() { return false; }
400 public boolean isClinit() { return false; }
401 public char[][] getArgumentNames() { return null; } // FEATURE: does this do anything cool?
402 public char[][] getExceptionTypeNames() { return ex; }
403 public char[] getMethodDescriptor() { return desc; }
406 final static class LoadedClass implements IBinaryType {
408 private IBinaryField[] f;
409 private char[][] inf;
410 private IBinaryNestedType[] nested;
411 private IBinaryMethod[] meth = null;
413 LoadedClass(Class c) {
416 Field[] fields = c.getDeclaredFields();
417 List flist = new ArrayList(fields.length);
418 for (int i=0; i < fields.length; i++)
419 if (!Modifier.isPrivate(fields[i].getModifiers()))
420 flist.add(new LoadedField(fields[i]));
421 f = new IBinaryField[flist.size()];
424 Class[] interfaces = c.getInterfaces();
425 inf = new char[interfaces.length][];
426 for (int i=0; i < inf.length; i++) inf[i] = name(interfaces[i]);
428 Class[] classes = c.getClasses();
429 nested = new IBinaryNestedType[classes.length];
430 for (int i=0; i < nested.length; i++)
431 nested[i] = new LoadedNestedType(classes[i]);
433 Constructor[] constructors = c.getDeclaredConstructors();
434 Method[] methods = c.getDeclaredMethods();
435 if (methods.length + constructors.length > 0) {
436 List m = new ArrayList(methods.length + constructors.length);
437 for (int j=0; j < methods.length; j++)
438 if (!Modifier.isPrivate(methods[j].getModifiers()))
439 m.add(new LoadedMethod(methods[j]));
440 for (int j=0; j < constructors.length; j++)
441 if (!Modifier.isPrivate(constructors[j].getModifiers()))
442 m.add(new LoadedConstructor(constructors[j]));
443 meth = new IBinaryMethod[m.size()]; m.toArray(meth);
447 public char[] getName() { return name(c); }
448 public char[] getEnclosingTypeName() { return name(c.getDeclaringClass()); }
449 public char[] getSuperclassName() { return name(c.getSuperclass()); }
450 public IBinaryField[] getFields() { return f; }
451 public char[][] getInterfaceNames() { return inf; }
452 public IBinaryNestedType[] getMemberTypes() { return nested; }
453 public IBinaryMethod[] getMethods() { return meth; }
454 public int getModifiers() { return c.getModifiers(); }
456 public boolean isBinaryType() { return true; }
457 public boolean isClass() { return true; }
458 public boolean isInterface() { return c.isInterface(); }
459 public boolean isAnonymous() { return false; }
460 public boolean isLocal() { return false; } // FIXME
461 public boolean isMember() { return false; } // FIXME
462 public char[] sourceFileName() { return null; }
463 public char[] getFileName() { return null; }
465 public boolean equals(Object o) {
466 return o == this || super.equals(o) ||
467 (o != null && o instanceof LoadedClass &&
468 c.equals(((LoadedClass)o).c));
473 // Compiler Parameters ////////////////////////////////////////////////////
475 /** Used by compiler to resolve classes. */
476 final INameEnvironment env = new INameEnvironment() {
477 public NameEnvironmentAnswer findType(char[][] c) { return findType(name(c), pack(c)); }
478 public NameEnvironmentAnswer findType(char[] n, char[][] p) {
479 if (verbose) System.out.print("findType: "+ str(p, '.') + "."+new String(n));
482 Class c = Class.forName(str(p, '.') + '.' + new String(n));
483 if (verbose) System.out.println(" found in classloader: "+ c);
484 IBinaryType b = (IBinaryType)loaded.get(c);
485 if (b == null) loaded.put(c, b = new LoadedClass(c));
486 return new NameEnvironmentAnswer(b);
487 } catch (ClassNotFoundException e) {}
489 // cut out searches for java.* packages in sources list
490 if (p.length > 0 && eq(p[0], "java".toCharArray())) {
491 if (verbose) System.out.println(" not found, unknown java.*");
496 for (int i=0; i < sources.length; i++) {
497 Source s = sources[i];
498 if (eq(n, s.n) && eq(p, s.p)) {
499 if (s.reader != null) {
500 if (verbose) System.out.println(" found reader");
501 return new NameEnvironmentAnswer(s.reader);
503 if (s.compiled != null) {
504 if (verbose) System.out.println(" found compiled, new reader");
505 s.reader = new ClassFileReader(s.compiled,
506 s.orig.getName().toCharArray(), true);
507 return new NameEnvironmentAnswer(s.reader);
509 if (verbose) System.out.println(" found unit");
510 return new NameEnvironmentAnswer(sources[i].unit);
513 } catch (ClassFormatException e) {
514 System.out.println("Unexpected ClassFormatException"); // FIXME
515 e.printStackTrace(); return null;
517 if (verbose) System.out.println(" not found");
520 public boolean isPackage(char[][] parent, char[] name) {
521 if (verbose) System.out.println("isPackage: "+ str(parent, '.') + "."+new String(name));
522 String parentName = str(parent, '/');
523 for (int i=0; i < sources.length; i++) {
524 if (eq(name, sources[i].n) && eq(parent, sources[i].p)) return false;
525 if (eq(pack(sources[i].p), parent) && eq(name(sources[i].p), name)) return true;
528 loader.getResource(parentName + ".class") == null &&
529 loader.getResource(parentName + '/' + new String(name) + ".class") == null;
531 public void cleanup() {}
534 /** Used by compiler to decide what do with problems.. */
535 private final IErrorHandlingPolicy policy =
536 DefaultErrorHandlingPolicies.proceedWithAllProblems();
538 /** Used by compiler for general options. */
539 private final Map settings = new HashMap();
541 settings.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE);
542 settings.put(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE);
543 settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_3);
544 settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_1);
547 /** Used by compiler for processing compiled classes and their errors. */
548 private final ICompilerRequestor results = new ICompilerRequestor() {
549 public void acceptResult(CompilationResult result) {
550 if (verbose) System.out.println("got result: "+result);
551 if (result.hasProblems()) {
553 IProblem[] p = result.getProblems();
555 for (int i=0; i < p.length; i++) {
556 if (p[i].isError()) { o = out; err = true; }
559 o.print(p[i].getOriginatingFileName());
561 o.print(p[i].getSourceLineNumber());
563 o.print(p[i].isError() ? " error: " : " warning: ");
564 o.println(p[i].getMessage());
567 if (err) { hasErrors = true; return; }
570 ClassFile[] c = result.getClassFiles();
571 for (int i=0; i < c.length; i++) {
573 // build package path to new class file
574 File path = builddir;
575 char[][] name = c[i].getCompoundName();
576 path = new File(builddir, str(pack(name), '/'));
577 if (!path.exists()) path.mkdirs();
579 // write new class file
580 path = new File(path, new String(name(name)) + ".class");
581 OutputStream o = new BufferedOutputStream(
582 new FileOutputStream(path));
583 o.write(c[i].getBytes());
585 } catch (IOException e) {
586 System.out.println("IOException writing class"); // FIXME
593 /** Problem creater for compiler. */
594 private final IProblemFactory problems = new DefaultProblemFactory();
597 // Helper Functiosn ///////////////////////////////////////////////////////
599 /** Convert source file path into class name block.
600 * eg. in: java/lang/String.java -> { {java} {lang} {String} } */
601 private char[][] classname(String name) {
602 String delim = name.indexOf('/') == -1 ? "." : "/";
604 if (name.endsWith(".java")) name = name.substring(0, name.length() - 5);
605 if (name.endsWith(".class")) name = name.substring(0, name.length() - 6);
606 if (name.startsWith(delim)) name = name.substring(1);
608 StringTokenizer st = new StringTokenizer(name, delim);
609 char[][] n = new char[st.countTokens()][];
610 for (int i=0; st.hasMoreTokens(); i++) n[i] = st.nextToken().toCharArray();
614 /** Convert class name into a String. */
615 private static String str(char[][] name, char delim) {
616 StringBuffer b = new StringBuffer();
617 for (int i=0; name != null && i < name.length; i++) {
618 if (name[i] == null || name[i].length == 0) continue;
619 if (i > 0) b.append(delim);
625 /** Returns the package component of a class name.
626 * Effectively returns char[length - 1][]. */
627 private static char[][] pack(char[][] c) {
628 char[][] p = new char[c.length - 1][];
629 for (int i=0; i < p.length; i++) p[i] = c[i];
633 /** Returns the direct-name component of a class name.
634 * eg. String from java.lang.String */
635 private static char[] name(char[][] c) { return c[c.length - 1]; }
637 /** Returns true of contents of both char arrays are equal. */
638 private static boolean eq(char[][] c1, char[][] c2) {
639 if (c1 == null || c2 == null) return c1 == c2;
640 if (c1.length != c2.length) return false;
641 for (int i=0; i < c1.length; i++) if (!eq(c1[i], c2[i])) return false;
645 /** Returns true of contents of both char arrays are equal. */
646 private static boolean eq(char[] c1, char[] c2) {
647 if (c1 == null || c2 == null) return c1 == c2;
648 if (c1.length != c2.length) return false;
649 for (int i=0; i < c1.length; i++) if (c1[i] != c2[i]) return false;
653 /** Returns class name as per VM Spec 4.2. eg. java/lang/String */
654 private static char[] name(Class c) {
655 return c == null ? null : c.getName().replace('.', '/').toCharArray();
658 /** Returns the type name of a class as per VM Spec 4.3.2. */
659 private static char[] typeName(Class p) {
660 StringBuffer sb = new StringBuffer();
662 return sb.toString().toCharArray();
665 /** Returns the type name of a class as per VM Spec 4.3.2.
666 * eg. int -> I, String -> Ljava/lang/String; */
667 private static void typeName(Class p, StringBuffer sb) {
668 String name = p.getName();
669 switch (name.charAt(0)) {
670 case 'B': case 'C': case 'D': case 'F': case 'I':
671 case 'J': case 'S': case 'Z': case 'V': case '[':
672 sb.append(name(p)); break;
674 case 'b': if (name.equals("boolean")) { sb.append('Z'); break; }
675 if (name.equals("byte")) { sb.append('B'); break; }
676 case 'c': if (name.equals("char")) { sb.append('C'); break; }
677 case 'd': if (name.equals("double")) { sb.append('D'); break; }
678 case 'f': if (name.equals("float")) { sb.append('F'); break; }
679 case 'i': if (name.equals("int")) { sb.append('I'); break; }
680 case 'l': if (name.equals("long")) { sb.append('J'); break; }
681 case 's': if (name.equals("short")) { sb.append('S'); break; }
682 case 'v': if (name.equals("void")) { sb.append('V'); break; }
684 sb.append('L'); sb.append(name(p)); sb.append(';');
688 /** Returns the descriptor of a method per VM Spec 4.3.3.
689 * eg. int get(String n, boolean b) -> (Ljava/lang/String;B)I */
690 private static char[] descriptor(Class[] p, Class r) {
691 StringBuffer sb = new StringBuffer();
693 if (p != null) for (int i=0; i < p.length; i++) typeName(p[i], sb);
695 if (r != null) typeName(r, sb);
696 return sb.toString().toCharArray();