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 private static final boolean DEBUG = false;
25 // Static Entry Point /////////////////////////////////////////////////////
27 public static void main(String[] args) {
28 String source = null, target = null;
29 String srcdir = null, blddir = null;
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; }
59 } else srcdir = args[i];
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);
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("");
80 // Compiler Interface /////////////////////////////////////////////////////
82 private ClassLoader loader = ClassLoader.getSystemClassLoader();
83 private Map loaded = new HashMap();
84 private PrintWriter out = new PrintWriter(System.out);
85 private Preprocessor preprocessor;
87 private Source[] sources;
89 private File builddir = new File(".");
90 private String sourcedir = null;
92 private boolean hasErrors;
93 private PrintWriter warn;
96 List defs = Collections.EMPTY_LIST;
98 String define = System.getProperty("org.ibex.tool.preprocessor.define");
100 defs = new ArrayList();
101 StringTokenizer st = new StringTokenizer(define.toUpperCase(), ",");
102 while (st.hasMoreTokens()) defs.add(st.nextToken().trim());
105 preprocessor = new Preprocessor(null, null, defs);
109 public void setBuildDir(String dir) { builddir = new File(dir == null ? "." : dir); }
110 public void setSourceDir(String dir) { sourcedir = dir; }
112 /** Pass CompilerOptions.VERSION_1_*. A String of form "1.1", ".2", etc. */
113 public void setSource(String v) { settings.put(CompilerOptions.OPTION_Source, v); }
115 /** Pass CompilerOptions.VERSION_1_*. A String of form "1.1", ".2", etc. */
116 public void setTarget(String v) { settings.put(CompilerOptions.OPTION_TargetPlatform, v); }
118 public void setBuilddir(File f) { builddir = f; }
120 public void compile() {
121 List s = new ArrayList();
122 filterSources(s, new File(sourcedir), new char[0][]);
123 if (DEBUG) System.out.println("working with "+s.size() +" sources");
124 sources = new Source[s.size()]; s.toArray(sources);
125 ICompilationUnit[] units = new ICompilationUnit[s.size()];
126 int u = 0; for (int i=0; i < sources.length; i++)
127 if (sources[i].compiled == null) units[u++] = sources[i].unit;
128 if (u != units.length) {
129 ICompilationUnit[] newu = new ICompilationUnit[u];
130 System.arraycopy(units, 0, newu, 0, u);
136 StringWriter sw = new StringWriter();
137 StringBuffer w = sw.getBuffer();
138 warn = new PrintWriter(sw);
140 org.eclipse.jdt.internal.compiler.Compiler jdt =
141 new org.eclipse.jdt.internal.compiler.Compiler(
142 env, policy, settings, results, problems);
145 if (!hasErrors) { out.write(w.toString()); out.flush(); }
149 private final FilenameFilter filterSrcs = new FilenameFilter() {
150 public boolean accept(File dir, String name) { return name.endsWith(".java"); }
152 private final FileFilter filterDirs = new FileFilter() {
153 public boolean accept(File path) { return path.isDirectory(); }
155 private byte[] bytes(File bfile) {
156 byte[] bytes = new byte[2 * 1024];
159 InputStream bin = new FileInputStream(bfile);
160 while ((in = bin.read(bytes, pos, bytes.length - pos)) != -1) {
162 if (pos == bytes.length) {
163 byte[] newbytes= new byte[pos * 2];
164 System.arraycopy(bytes, 0, newbytes, 0, pos);
169 } catch (IOException e) {
170 System.out.println("Error reading class file"); // FIXME
171 e.printStackTrace(); return null;
174 if (pos != bytes.length) {
175 byte[] newbytes= new byte[pos * 2];
176 System.arraycopy(bytes, 0, newbytes, 0, pos);
182 private void filterSources(List s, File dir, char[][] pack) {
183 List bclasses = new ArrayList();
184 File bdir = new File(builddir, str(pack, File.separatorChar));
186 // add the java files in this directory
187 File[] ja = dir.listFiles(filterSrcs);
188 for (int i=0; i < ja.length; i++) {
189 char[] n = name(classname(ja[i].getName()));
190 Source src = new Source(ja[i], n, pack);
192 // skip the file if the build version is newer than the source
193 String bclass = new String(n);
194 File bfile = new File(bdir, bclass + ".class");
195 if (bfile.lastModified() > ja[i].lastModified()) {
196 src.compiled = bytes(bfile);
197 bclasses.add(bclass);
203 // process the inner classes of any binary files
204 for (int i=0; i < bclasses.size(); i++) {
205 final String bc = (String)bclasses.get(i);
206 final FilenameFilter f = new FilenameFilter() {
207 public boolean accept(File dir, String name) {
208 return name.length() > bc.length() && name.startsWith(bc) &&
209 name.charAt(bc.length()) == '$' && name.endsWith(".class");
212 File[] bfile = bdir.listFiles(f);
213 for (int j=0; j < bfile.length; j++) {
214 Source src = new Source(bfile[j], name(classname(bfile[j].getName())), pack);
215 src.compiled = bytes(bfile[j]);
220 // add the subdirectories as packages
221 File[] d = dir.listFiles(filterDirs);
222 for (int i=0; i < d.length; i++) {
223 char[][] newpack = new char[pack.length + 1][];
224 for (int j=0; j < pack.length; j++) newpack[j] = pack[j];
225 newpack[pack.length] = d[i].getName().toCharArray();
226 filterSources(s, d[i], newpack);
231 /** Represents a file to be compiled. */
234 char[] n; char[][] p;
236 char[] processed = null;
237 byte[] compiled = null;
238 ClassFileReader reader = null;
240 final ICompilationUnit unit = new ICompilationUnit() {
241 public char[] getMainTypeName() { return n; }
242 public char[][] getPackageName() { return p; }
243 public char[] getFileName() { return fileName; }
244 public char[] getContents() {
245 if (processed != null) return processed;
248 Reader r = new InputStreamReader(new BufferedInputStream(
249 new FileInputStream(orig)));
250 StringWriter w = new StringWriter();
253 synchronized (preprocessor) {
254 preprocessor.setReader(r);
255 preprocessor.setWriter(w);
256 err = preprocessor.process();
259 if (err.size() > 0) {
260 System.out.println("Preprocessor Errors, "+err); // FIXME
264 processed = w.toString().toCharArray();
265 } catch (IOException e) {
266 System.out.println("IOException: "+e); // FIXME
274 private Source(File o, char[] n, char[][] p) {
275 orig = o; this.n = n; this.p = p;
276 String file = sourcedir;
277 file += File.separatorChar + str(p, File.separatorChar);
278 file += File.separatorChar + new String(n) + ".java";
279 fileName = file.toCharArray();
283 // ClassLoader Wrappers ///////////////////////////////////////////////////
285 final static class LoadedNestedType implements IBinaryNestedType {
287 LoadedNestedType(Class c) { this.c = c; }
288 public char[] getName() { return name(c); }
289 public char[] getEnclosingTypeName() { return name(c.getDeclaringClass()); }
290 public int getModifiers() { return c.getModifiers(); }
293 final static class LoadedField implements IBinaryField {
297 LoadedField(Field f) {
299 int m = f.getModifiers();
301 c = Constant.NotAConstant;
302 if (Modifier.isFinal(m) && Modifier.isStatic(m)) {
304 Class type = f.getType();
305 if (type == Boolean.TYPE) {
306 c = new BooleanConstant(f.getBoolean(null));
307 } else if (type == Byte.TYPE) {
308 c = new ByteConstant(f.getByte(null));
309 } else if (type == Character.TYPE) {
310 c = new CharConstant(f.getChar(null));
311 } else if (type == Double.TYPE) {
312 c = new DoubleConstant(f.getDouble(null));
313 } else if (type == Float.TYPE) {
314 c = new FloatConstant(f.getFloat(null));
315 } else if (type == Integer.TYPE) {
316 c = new IntConstant(f.getInt(null));
317 } else if (type == Long.TYPE) {
318 c = new LongConstant(f.getLong(null));
319 } else if (type == Short.TYPE) {
320 c = new ShortConstant(f.getShort(null));
321 } else if (type == String.class) {
322 c = new StringConstant((String)f.get(null));
324 } catch (IllegalAccessException e) {}
327 public Constant getConstant() { return c; }
328 public char[] getTypeName() { return typeName(f.getType()); }
329 public char[] getName() { return f.getName().toCharArray(); }
330 public int getModifiers() { return f.getModifiers(); }
333 final static class LoadedConstructor implements IBinaryMethod {
334 private Constructor c;
338 LoadedConstructor(Constructor c) {
341 Class[] exs = c.getExceptionTypes();
342 ex = new char[exs.length][];
343 for (int i=0; i < ex.length; i++) ex[i] = name(exs[i]);
345 desc = descriptor(c.getParameterTypes(), null);
347 public int getModifiers() { return c.getModifiers(); }
348 public char[] getSelector() { return c.getName().toCharArray(); }
349 public boolean isConstructor() { return true; }
350 public boolean isClinit() { return false; }
351 public char[][] getArgumentNames() { return null; }
352 public char[][] getExceptionTypeNames() { return ex; }
353 public char[] getMethodDescriptor() { return desc; }
356 final static class LoadedMethod implements IBinaryMethod {
361 LoadedMethod(Method m) {
364 Class[] exs = m.getExceptionTypes();
365 ex = new char[exs.length][];
366 for (int i=0; i < ex.length; i++) ex[i] = name(exs[i]);
368 desc = descriptor(m.getParameterTypes(), m.getReturnType());
370 public int getModifiers() { return m.getModifiers(); }
371 public char[] getSelector() { return m.getName().toCharArray(); }
372 public boolean isConstructor() { return false; }
373 public boolean isClinit() { return false; }
374 public char[][] getArgumentNames() { return null; } // FEATURE: does this do anything cool?
375 public char[][] getExceptionTypeNames() { return ex; }
376 public char[] getMethodDescriptor() { return desc; }
379 final static class LoadedClass implements IBinaryType {
381 private IBinaryField[] f;
382 private char[][] inf;
383 private IBinaryNestedType[] nested;
384 private IBinaryMethod[] meth = null;
386 LoadedClass(Class c) {
389 Field[] fields = c.getFields();
390 f = new IBinaryField[fields.length];
391 for (int i=0; i < f.length; i++) f[i] = new LoadedField(fields[i]);
393 Class[] interfaces = c.getInterfaces();
394 inf = new char[interfaces.length][];
395 for (int i=0; i < inf.length; i++) inf[i] = name(interfaces[i]);
397 Class[] classes = c.getClasses();
398 nested = new IBinaryNestedType[classes.length];
399 for (int i=0; i < nested.length; i++)
400 nested[i] = new LoadedNestedType(classes[i]);
402 Constructor[] constructors = c.getDeclaredConstructors();
403 Method[] methods = c.getDeclaredMethods();
404 if (methods.length + constructors.length > 0) {
405 meth = new IBinaryMethod[methods.length + constructors.length];
407 for (int j=0; j < methods.length; j++)
408 meth[i++] = new LoadedMethod(methods[j]);
409 for (int j=0; j < constructors.length; j++)
410 meth[i++] = new LoadedConstructor(constructors[j]);
415 public char[] getName() { return name(c); }
416 public char[] getEnclosingTypeName() { return name(c.getDeclaringClass()); }
417 public char[] getSuperclassName() { return name(c.getSuperclass()); }
418 public IBinaryField[] getFields() { return f; }
419 public char[][] getInterfaceNames() { return inf; }
420 public IBinaryNestedType[] getMemberTypes() { return nested; }
421 public IBinaryMethod[] getMethods() { return meth; }
422 public int getModifiers() { return c.getModifiers(); }
424 public boolean isBinaryType() { return true; }
425 public boolean isClass() { return true; }
426 public boolean isInterface() { return c.isInterface(); }
427 public boolean isAnonymous() { return false; }
428 public boolean isLocal() { return false; } // FIXME
429 public boolean isMember() { return false; } // FIXME
430 public char[] sourceFileName() { return null; }
431 public char[] getFileName() { return null; }
433 public boolean equals(Object o) {
434 return o == this || super.equals(o) ||
435 (o != null && o instanceof LoadedClass &&
436 c.equals(((LoadedClass)o).c));
441 // Compiler Parameters ////////////////////////////////////////////////////
443 /** Used by compiler to resolve classes. */
444 final INameEnvironment env = new INameEnvironment() {
445 public NameEnvironmentAnswer findType(char[][] c) { return findType(name(c), pack(c)); }
446 public NameEnvironmentAnswer findType(char[] n, char[][] p) {
447 if (DEBUG) System.out.println("requesting: "+ str(p, '.') + "."+new String(n));
450 Class c = Class.forName(str(p, '.') + '.' + new String(n));
451 if (DEBUG) System.out.println(" found in classloader: "+ c);
452 IBinaryType b = (IBinaryType)loaded.get(c);
453 if (b == null) loaded.put(c, b = new LoadedClass(c));
454 return new NameEnvironmentAnswer(b);
455 } catch (ClassNotFoundException e) {}
457 // cut out searches for java.* packages in sources list
458 if (p.length > 0 && eq(p[0], "java".toCharArray())) return null;
461 for (int i=0; i < sources.length; i++) {
462 Source s = sources[i];
463 if (eq(n, s.n) && eq(p, s.p)) {
464 if (s.reader != null) {
465 if (DEBUG) System.out.println(" found reader");
466 return new NameEnvironmentAnswer(s.reader);
468 if (s.compiled != null) {
469 if (DEBUG) System.out.println(" found compiled, new reader");
470 s.reader = new ClassFileReader(s.compiled,
471 s.orig.getName().toCharArray(), true);
472 return new NameEnvironmentAnswer(s.reader);
474 if (DEBUG) System.out.println(" found unit");
475 return new NameEnvironmentAnswer(sources[i].unit);
478 } catch (ClassFormatException e) {
479 System.out.println("Unexpected ClassFormatException"); // FIXME
484 public boolean isPackage(char[][] parent, char[] name) {
485 String parentName = str(parent, '/');
486 for (int i=0; i < sources.length; i++)
487 if (eq(name, sources[i].n) && eq(parent, sources[i].p)) return false;
489 loader.getResource(parentName + ".class") == null &&
490 loader.getResource(parentName + '/' + new String(name) + ".class") == null;
492 public void cleanup() {}
495 /** Used by compiler to decide what do with problems.. */
496 private final IErrorHandlingPolicy policy =
497 DefaultErrorHandlingPolicies.proceedWithAllProblems();
499 /** Used by compiler for general options. */
500 private final Map settings = new HashMap();
502 settings.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE);
503 settings.put(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE);
504 settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_3);
505 settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_1);
508 /** Used by compiler for processing compiled classes and their errors. */
509 private final ICompilerRequestor results = new ICompilerRequestor() {
510 public void acceptResult(CompilationResult result) {
511 if (DEBUG) System.out.println("got result: "+result);
512 if (result.hasProblems()) {
514 IProblem[] p = result.getProblems();
516 for (int i=0; i < p.length; i++) {
517 if (p[i].isError()) { o = out; err = true; }
520 o.print(p[i].getOriginatingFileName());
522 o.print(p[i].getSourceLineNumber());
524 o.print(p[i].isError() ? " error: " : " warning: ");
525 o.println(p[i].getMessage());
528 if (err) { hasErrors = true; return; }
531 ClassFile[] c = result.getClassFiles();
532 for (int i=0; i < c.length; i++) {
534 // build package path to new class file
535 File path = builddir;
536 char[][] name = c[i].getCompoundName();
537 path = new File(builddir, str(pack(name), '/'));
538 if (DEBUG) System.out.println("DEBUG: creating path "+path+", out of builddir="+builddir);
539 if (!path.exists()) path.mkdirs();
541 // write new class file
542 path = new File(path, new String(name(name)) + ".class");
543 if (DEBUG) System.out.println("DEBUG: writing file "+path);
544 OutputStream o = new BufferedOutputStream(
545 new FileOutputStream(path));
546 o.write(c[i].getBytes());
548 } catch (IOException e) {
549 System.out.println("IOException writing class"); // FIXME
556 /** Problem creater for compiler. */
557 private final IProblemFactory problems = new DefaultProblemFactory();
560 // Helper Functiosn ///////////////////////////////////////////////////////
562 /** Convert source file path into class name block.
563 * eg. in: java/lang/String.java -> { {java} {lang} {String} } */
564 private char[][] classname(String name) {
565 String delim = name.indexOf('/') == -1 ? "." : "/";
567 if (name.endsWith(".java")) name = name.substring(0, name.length() - 5);
568 if (name.endsWith(".class")) name = name.substring(0, name.length() - 6);
569 if (name.startsWith(delim)) name = name.substring(1);
571 StringTokenizer st = new StringTokenizer(name, delim);
572 char[][] n = new char[st.countTokens()][];
573 for (int i=0; st.hasMoreTokens(); i++) n[i] = st.nextToken().toCharArray();
577 /** Convert class name into a String. */
578 private static String str(char[][] name, char delim) {
579 StringBuffer b = new StringBuffer();
580 for (int i=0; name != null && i < name.length; i++) {
581 if (name[i] == null || name[i].length == 0) continue;
582 if (i > 0) b.append(delim);
588 /** Returns the package component of a class name.
589 * Effectively returns char[length - 1][]. */
590 private static char[][] pack(char[][] c) {
591 char[][] p = new char[c.length - 1][];
592 for (int i=0; i < p.length; i++) p[i] = c[i];
596 /** Returns the direct-name component of a class name.
597 * eg. String from java.lang.String */
598 private static char[] name(char[][] c) { return c[c.length - 1]; }
600 /** Returns true of contents of both char arrays are equal. */
601 private static boolean eq(char[][] c1, char[][] c2) {
602 if (c1.length != c2.length) return false;
603 for (int i=0; i < c1.length; i++) if (!eq(c1[i], c2[i])) return false;
607 /** Returns true of contents of both char arrays are equal. */
608 private static boolean eq(char[] c1, char[] c2) {
609 if (c1.length != c2.length) return false;
610 for (int i=0; i < c1.length; i++) if (c1[i] != c2[i]) return false;
614 /** Returns class name as per VM Spec 4.2. eg. java/lang/String */
615 private static char[] name(Class c) {
616 return c == null ? null : c.getName().replace('.', '/').toCharArray();
619 /** Returns the type name of a class as per VM Spec 4.3.2. */
620 private static char[] typeName(Class p) {
621 StringBuffer sb = new StringBuffer();
623 return sb.toString().toCharArray();
626 /** Returns the type name of a class as per VM Spec 4.3.2.
627 * eg. int -> I, String -> Ljava/lang/String; */
628 private static void typeName(Class p, StringBuffer sb) {
629 String name = p.getName();
630 switch (name.charAt(0)) {
631 case 'B': case 'C': case 'D': case 'F': case 'I':
632 case 'J': case 'S': case 'Z': case 'V': case '[':
633 sb.append(name(p)); break;
635 case 'b': if (name.equals("boolean")) { sb.append('Z'); break; }
636 if (name.equals("byte")) { sb.append('B'); break; }
637 case 'c': if (name.equals("char")) { sb.append('C'); break; }
638 case 'd': if (name.equals("double")) { sb.append('D'); break; }
639 case 'f': if (name.equals("float")) { sb.append('F'); break; }
640 case 'i': if (name.equals("int")) { sb.append('I'); break; }
641 case 'l': if (name.equals("long")) { sb.append('J'); break; }
642 case 's': if (name.equals("short")) { sb.append('S'); break; }
643 case 'v': if (name.equals("void")) { sb.append('V'); break; }
645 sb.append('L'); sb.append(name(p)); sb.append(';');
649 /** Returns the descriptor of a method per VM Spec 4.3.3.
650 * eg. int get(String n, boolean b) -> (Ljava/lang/String;B)I */
651 private static char[] descriptor(Class[] p, Class r) {
652 StringBuffer sb = new StringBuffer();
654 if (p != null) for (int i=0; i < p.length; i++) typeName(p[i], sb);
656 if (r != null) typeName(r, sb);
657 return sb.toString().toCharArray();