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 for (int i=0; i < sources.length; i++) units[i] = sources[i].unit;
130 StringWriter sw = new StringWriter();
131 StringBuffer w = sw.getBuffer();
132 warn = new PrintWriter(sw);
134 org.eclipse.jdt.internal.compiler.Compiler jdt =
135 new org.eclipse.jdt.internal.compiler.Compiler(
136 env, policy, settings, results, problems);
139 if (!hasErrors) { out.write(w.toString()); out.flush(); }
143 private final FilenameFilter filterSrcs = new FilenameFilter() {
144 public boolean accept(File dir, String name) { return name.endsWith(".java"); }
146 private final FileFilter filterDirs = new FileFilter() {
147 public boolean accept(File path) { return path.isDirectory(); }
149 private void filterSources(List s, File dir, char[][] pack) {
150 File[] ja = dir.listFiles(filterSrcs);
151 for (int i=0; i < ja.length; i++)
152 s.add(new Source(ja[i], name(classname(ja[i].getName())), pack));
154 File[] d = dir.listFiles(filterDirs);
155 for (int i=0; i < d.length; i++) {
156 char[][] newpack = new char[pack.length + 1][];
157 for (int j=0; j < pack.length; j++) newpack[j] = pack[j];
158 newpack[pack.length] = d[i].getName().toCharArray();
159 filterSources(s, d[i], newpack);
164 /** Represents a file to be compiled. */
167 char[] n; char[][] p;
169 char[] processed = null;
170 byte[] compiled = null;
172 final ICompilationUnit unit = new ICompilationUnit() {
173 public char[] getMainTypeName() { return n; }
174 public char[][] getPackageName() { return p; }
175 public char[] getFileName() { return fileName; }
176 public char[] getContents() {
177 if (processed != null) return processed;
180 Reader r = new InputStreamReader(new BufferedInputStream(
181 new FileInputStream(orig)));
182 StringWriter w = new StringWriter();
185 synchronized (preprocessor) {
186 preprocessor.setReader(r);
187 preprocessor.setWriter(w);
188 err = preprocessor.process();
191 if (err.size() > 0) {
192 System.out.println("Preprocessor Errors, "+err); // FIXME
196 processed = w.toString().toCharArray();
197 } catch (IOException e) {
198 System.out.println("IOException: "+e); // FIXME
206 private Source(File o, char[] n, char[][] p) {
207 orig = o; this.n = n; this.p = p;
208 String file = sourcedir;
209 file += File.separatorChar + str(p, File.separatorChar);
210 file += File.separatorChar + new String(n) + ".java";
211 fileName = file.toCharArray();
215 // ClassLoader Wrappers ///////////////////////////////////////////////////
217 final static class LoadedNestedType implements IBinaryNestedType {
219 LoadedNestedType(Class c) { this.c = c; }
220 public char[] getName() { return name(c); }
221 public char[] getEnclosingTypeName() { return name(c.getDeclaringClass()); }
222 public int getModifiers() { return c.getModifiers(); }
225 final static class LoadedField implements IBinaryField {
229 LoadedField(Field f) {
231 int m = f.getModifiers();
233 c = Constant.NotAConstant;
234 if (Modifier.isFinal(m) && Modifier.isStatic(m)) {
236 Class type = f.getType();
237 if (type == Boolean.TYPE) {
238 c = new BooleanConstant(f.getBoolean(null));
239 } else if (type == Byte.TYPE) {
240 c = new ByteConstant(f.getByte(null));
241 } else if (type == Character.TYPE) {
242 c = new CharConstant(f.getChar(null));
243 } else if (type == Double.TYPE) {
244 c = new DoubleConstant(f.getDouble(null));
245 } else if (type == Float.TYPE) {
246 c = new FloatConstant(f.getFloat(null));
247 } else if (type == Integer.TYPE) {
248 c = new IntConstant(f.getInt(null));
249 } else if (type == Long.TYPE) {
250 c = new LongConstant(f.getLong(null));
251 } else if (type == Short.TYPE) {
252 c = new ShortConstant(f.getShort(null));
253 } else if (type == String.class) {
254 c = new StringConstant((String)f.get(null));
256 } catch (IllegalAccessException e) {}
259 public Constant getConstant() { return c; }
260 public char[] getTypeName() { return typeName(f.getType()); }
261 public char[] getName() { return f.getName().toCharArray(); }
262 public int getModifiers() { return f.getModifiers(); }
265 final static class LoadedConstructor implements IBinaryMethod {
266 private Constructor c;
270 LoadedConstructor(Constructor c) {
273 Class[] exs = c.getExceptionTypes();
274 ex = new char[exs.length][];
275 for (int i=0; i < ex.length; i++) ex[i] = name(exs[i]);
277 desc = descriptor(c.getParameterTypes(), null);
279 public int getModifiers() { return c.getModifiers(); }
280 public char[] getSelector() { return c.getName().toCharArray(); }
281 public boolean isConstructor() { return true; }
282 public boolean isClinit() { return false; }
283 public char[][] getArgumentNames() { return null; }
284 public char[][] getExceptionTypeNames() { return ex; }
285 public char[] getMethodDescriptor() { return desc; }
288 final static class LoadedMethod implements IBinaryMethod {
293 LoadedMethod(Method m) {
296 Class[] exs = m.getExceptionTypes();
297 ex = new char[exs.length][];
298 for (int i=0; i < ex.length; i++) ex[i] = name(exs[i]);
300 desc = descriptor(m.getParameterTypes(), m.getReturnType());
302 public int getModifiers() { return m.getModifiers(); }
303 public char[] getSelector() { return m.getName().toCharArray(); }
304 public boolean isConstructor() { return false; }
305 public boolean isClinit() { return false; }
306 public char[][] getArgumentNames() { return null; } // FEATURE: does this do anything cool?
307 public char[][] getExceptionTypeNames() { return ex; }
308 public char[] getMethodDescriptor() { return desc; }
311 final static class LoadedClass implements IBinaryType {
313 private IBinaryField[] f;
314 private char[][] inf;
315 private IBinaryNestedType[] nested;
316 private IBinaryMethod[] meth = null;
318 LoadedClass(Class c) {
321 Field[] fields = c.getFields();
322 f = new IBinaryField[fields.length];
323 for (int i=0; i < f.length; i++) f[i] = new LoadedField(fields[i]);
325 Class[] interfaces = c.getInterfaces();
326 inf = new char[interfaces.length][];
327 for (int i=0; i < inf.length; i++) inf[i] = name(interfaces[i]);
329 Class[] classes = c.getClasses();
330 nested = new IBinaryNestedType[classes.length];
331 for (int i=0; i < nested.length; i++)
332 nested[i] = new LoadedNestedType(classes[i]);
334 Constructor[] constructors = c.getDeclaredConstructors();
335 Method[] methods = c.getDeclaredMethods();
336 if (methods.length + constructors.length > 0) {
337 meth = new IBinaryMethod[methods.length + constructors.length];
339 for (int j=0; j < methods.length; j++)
340 meth[i++] = new LoadedMethod(methods[j]);
341 for (int j=0; j < constructors.length; j++)
342 meth[i++] = new LoadedConstructor(constructors[j]);
347 public char[] getName() { return name(c); }
348 public char[] getEnclosingTypeName() { return name(c.getDeclaringClass()); }
349 public char[] getSuperclassName() { return name(c.getSuperclass()); }
350 public IBinaryField[] getFields() { return f; }
351 public char[][] getInterfaceNames() { return inf; }
352 public IBinaryNestedType[] getMemberTypes() { return nested; }
353 public IBinaryMethod[] getMethods() { return meth; }
354 public int getModifiers() { return c.getModifiers(); }
356 public boolean isBinaryType() { return true; }
357 public boolean isClass() { return true; }
358 public boolean isInterface() { return c.isInterface(); }
359 public boolean isAnonymous() { return false; }
360 public boolean isLocal() { return false; } // FIXME
361 public boolean isMember() { return false; } // FIXME
362 public char[] sourceFileName() { return null; }
363 public char[] getFileName() { return null; }
365 public boolean equals(Object o) {
366 return o == this || super.equals(o) ||
367 (o != null && o instanceof LoadedClass &&
368 c.equals(((LoadedClass)o).c));
373 // Compiler Parameters ////////////////////////////////////////////////////
375 /** Used by compiler to resolve classes. */
376 final INameEnvironment env = new INameEnvironment() {
377 public NameEnvironmentAnswer findType(char[][] c) { return findType(name(c), pack(c)); }
378 public NameEnvironmentAnswer findType(char[] n, char[][] p) {
379 if (DEBUG) System.out.println("requesting: "+ str(p, '.') + "."+new String(n));
382 Class c = Class.forName(str(p, '.') + '.' + new String(n));
383 if (DEBUG) System.out.println("found class: "+ c);
384 IBinaryType b = (IBinaryType)loaded.get(c);
385 if (b == null) loaded.put(c, b = new LoadedClass(c));
386 if (DEBUG) System.out.println("returning "+b+", name="+new String(b.getName()));
387 return new NameEnvironmentAnswer(b);
388 } catch (ClassNotFoundException e) {}
390 // cut out searches for java.* packages in sources list
391 if (p.length > 0 && eq(p[0], "java".toCharArray())) return null;
394 for (int i=0; i < sources.length; i++)
395 if (eq(n, sources[i].n) && eq(p, sources[i].p))
396 return sources[i].compiled == null ?
397 new NameEnvironmentAnswer(sources[i].unit) :
398 new NameEnvironmentAnswer(new ClassFileReader(sources[i].compiled,
399 sources[i].orig.getName().toCharArray(), true));
400 } catch (ClassFormatException e) {
401 System.out.println("Unexpected ClassFormatException"); // FIXME
406 public boolean isPackage(char[][] parent, char[] name) {
407 String parentName = str(parent, '/');
408 for (int i=0; i < sources.length; i++)
409 if (eq(name, sources[i].n) && eq(parent, sources[i].p)) return false;
411 loader.getResource(parentName + ".class") == null &&
412 loader.getResource(parentName + '/' + new String(name) + ".class") == null;
414 public void cleanup() {}
417 /** Used by compiler to decide what do with problems.. */
418 private final IErrorHandlingPolicy policy =
419 DefaultErrorHandlingPolicies.proceedWithAllProblems();
421 /** Used by compiler for general options. */
422 private final Map settings = new HashMap();
424 settings.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE);
425 settings.put(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE);
426 settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_3);
427 settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_1);
430 /** Used by compiler for processing compiled classes and their errors. */
431 private final ICompilerRequestor results = new ICompilerRequestor() {
432 public void acceptResult(CompilationResult result) {
433 if (DEBUG) System.out.println("got result: "+result);
434 if (result.hasProblems()) {
436 IProblem[] p = result.getProblems();
438 for (int i=0; i < p.length; i++) {
439 if (p[i].isError()) { o = out; err = true; }
442 o.print(p[i].getOriginatingFileName());
444 o.print(p[i].getSourceLineNumber());
446 o.print(p[i].isError() ? " error: " : " warning: ");
447 o.println(p[i].getMessage());
450 if (err) { hasErrors = true; return; }
453 ClassFile[] c = result.getClassFiles();
454 for (int i=0; i < c.length; i++) {
456 // build package path to new class file
457 File path = builddir;
458 char[][] name = c[i].getCompoundName();
459 path = new File(builddir, str(pack(name), '/'));
460 if (DEBUG) System.out.println("DEBUG: creating path "+path+", out of builddir="+builddir);
461 if (!path.exists()) path.mkdirs();
463 // write new class file
464 path = new File(path, new String(name(name)) + ".class");
465 if (DEBUG) System.out.println("DEBUG: writing file "+path);
466 OutputStream o = new BufferedOutputStream(
467 new FileOutputStream(path));
468 o.write(c[i].getBytes());
470 } catch (IOException e) {
471 System.out.println("IOException writing class"); // FIXME
478 /** Problem creater for compiler. */
479 private final IProblemFactory problems = new DefaultProblemFactory();
482 // Helper Functiosn ///////////////////////////////////////////////////////
484 /** Convert source file path into class name block.
485 * eg. in: java/lang/String.java -> { {java} {lang} {String} } */
486 private char[][] classname(String name) {
487 String delim = name.indexOf('/') == -1 ? "." : "/";
489 if (name.endsWith(".java")) name = name.substring(0, name.length() - 5);
490 if (name.startsWith(delim)) name = name.substring(1);
492 StringTokenizer st = new StringTokenizer(name, delim);
493 char[][] n = new char[st.countTokens()][];
494 for (int i=0; st.hasMoreTokens(); i++) n[i] = st.nextToken().toCharArray();
498 /** Convert class name into a String. */
499 private static String str(char[][] name, char delim) {
500 StringBuffer b = new StringBuffer();
501 for (int i=0; name != null && i < name.length; i++) {
502 if (name[i] == null || name[i].length == 0) continue;
503 if (i > 0) b.append(delim);
509 /** Returns the package component of a class name.
510 * Effectively returns char[length - 1][]. */
511 private static char[][] pack(char[][] c) {
512 char[][] p = new char[c.length - 1][];
513 for (int i=0; i < p.length; i++) p[i] = c[i];
517 /** Returns the direct-name component of a class name.
518 * eg. String from java.lang.String */
519 private static char[] name(char[][] c) { return c[c.length - 1]; }
521 /** Returns true of contents of both char arrays are equal. */
522 private static boolean eq(char[][] c1, char[][] c2) {
523 if (c1.length != c2.length) return false;
524 for (int i=0; i < c1.length; i++) if (!eq(c1[i], c2[i])) return false;
528 /** Returns true of contents of both char arrays are equal. */
529 private static boolean eq(char[] c1, char[] c2) {
530 if (c1.length != c2.length) return false;
531 for (int i=0; i < c1.length; i++) if (c1[i] != c2[i]) return false;
535 /** Returns class name as per VM Spec 4.2. eg. java/lang/String */
536 private static char[] name(Class c) {
537 return c == null ? null : c.getName().replace('.', '/').toCharArray();
540 /** Returns the type name of a class as per VM Spec 4.3.2. */
541 private static char[] typeName(Class p) {
542 StringBuffer sb = new StringBuffer();
544 return sb.toString().toCharArray();
547 /** Returns the type name of a class as per VM Spec 4.3.2.
548 * eg. int -> I, String -> Ljava/lang/String; */
549 private static void typeName(Class p, StringBuffer sb) {
550 String name = p.getName();
551 switch (name.charAt(0)) {
552 case 'B': case 'C': case 'D': case 'F': case 'I':
553 case 'J': case 'S': case 'Z': case 'V': case '[':
554 sb.append(name(p)); break;
556 case 'b': if (name.equals("boolean")) { sb.append('Z'); break; }
557 if (name.equals("byte")) { sb.append('B'); break; }
558 case 'c': if (name.equals("char")) { sb.append('C'); break; }
559 case 'd': if (name.equals("double")) { sb.append('D'); break; }
560 case 'f': if (name.equals("float")) { sb.append('F'); break; }
561 case 'i': if (name.equals("int")) { sb.append('I'); break; }
562 case 'l': if (name.equals("long")) { sb.append('J'); break; }
563 case 's': if (name.equals("short")) { sb.append('S'); break; }
564 case 'v': if (name.equals("void")) { sb.append('V'); break; }
566 sb.append('L'); sb.append(name(p)); sb.append(';');
570 /** Returns the descriptor of a method per VM Spec 4.3.3.
571 * eg. int get(String n, boolean b) -> (Ljava/lang/String;B)I */
572 private static char[] descriptor(Class[] p, Class r) {
573 StringBuffer sb = new StringBuffer();
575 if (p != null) for (int i=0; i < p.length; i++) typeName(p[i], sb);
577 if (r != null) typeName(r, sb);
578 return sb.toString().toCharArray();