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;
93 List defs = Collections.EMPTY_LIST;
95 String define = System.getProperty("org.ibex.tool.preprocessor.define");
97 defs = new ArrayList();
98 StringTokenizer st = new StringTokenizer(define.toUpperCase(), ",");
99 while (st.hasMoreTokens()) defs.add(st.nextToken().trim());
102 preprocessor = new Preprocessor(null, null, defs);
106 public void setBuildDir(String dir) { builddir = new File(dir == null ? "." : dir); }
107 public void setSourceDir(String dir) { sourcedir = dir; }
109 /** Pass CompilerOptions.VERSION_1_*. A String of form "1.1", ".2", etc. */
110 public void setSource(String v) { settings.put(CompilerOptions.OPTION_Source, v); }
112 /** Pass CompilerOptions.VERSION_1_*. A String of form "1.1", ".2", etc. */
113 public void setTarget(String v) { settings.put(CompilerOptions.OPTION_TargetPlatform, v); }
115 public void setBuilddir(File f) { builddir = f; }
117 public void compile() {
118 List s = new ArrayList();
119 filterSources(s, new File(sourcedir), new char[0][]);
120 if (DEBUG) System.out.println("working with "+s.size() +" sources");
121 sources = new Source[s.size()]; s.toArray(sources);
122 ICompilationUnit[] units = new ICompilationUnit[s.size()];
123 for (int i=0; i < sources.length; i++) units[i] = sources[i].unit;
125 org.eclipse.jdt.internal.compiler.Compiler jdt =
126 new org.eclipse.jdt.internal.compiler.Compiler(
127 env, policy, settings, results, problems);
131 private final FilenameFilter filterSrcs = new FilenameFilter() {
132 public boolean accept(File dir, String name) { return name.endsWith(".java"); }
134 private final FileFilter filterDirs = new FileFilter() {
135 public boolean accept(File path) { return path.isDirectory(); }
137 private void filterSources(List s, File dir, char[][] pack) {
138 File[] ja = dir.listFiles(filterSrcs);
139 for (int i=0; i < ja.length; i++)
140 s.add(new Source(ja[i], name(classname(ja[i].getName())), pack));
142 File[] d = dir.listFiles(filterDirs);
143 for (int i=0; i < d.length; i++) {
144 char[][] newpack = new char[pack.length + 1][];
145 for (int j=0; j < pack.length; j++) newpack[j] = pack[j];
146 newpack[pack.length] = d[i].getName().toCharArray();
147 filterSources(s, d[i], newpack);
152 /** Represents a file to be compiled. */
155 char[] n; char[][] p;
157 char[] processed = null;
158 byte[] compiled = null;
160 final ICompilationUnit unit = new ICompilationUnit() {
161 public char[] getMainTypeName() { return n; }
162 public char[][] getPackageName() { return p; }
163 public char[] getFileName() { return fileName; }
164 public char[] getContents() {
165 if (processed != null) return processed;
168 Reader r = new InputStreamReader(new BufferedInputStream(
169 new FileInputStream(orig)));
170 StringWriter w = new StringWriter();
173 synchronized (preprocessor) {
174 preprocessor.setReader(r);
175 preprocessor.setWriter(w);
176 err = preprocessor.process();
179 if (err.size() > 0) {
180 System.out.println("Preprocessor Errors, "+err); // FIXME
184 processed = w.toString().toCharArray();
185 } catch (IOException e) {
186 System.out.println("IOException: "+e); // FIXME
194 private Source(File o, char[] n, char[][] p) {
195 orig = o; this.n = n; this.p = p;
196 String file = sourcedir;
197 file += File.separatorChar + str(p, File.separatorChar);
198 file += File.separatorChar + new String(n) + ".java";
199 fileName = file.toCharArray();
203 // ClassLoader Wrappers ///////////////////////////////////////////////////
205 final static class LoadedNestedType implements IBinaryNestedType {
207 LoadedNestedType(Class c) { this.c = c; }
208 public char[] getName() { return name(c); }
209 public char[] getEnclosingTypeName() { return name(c.getDeclaringClass()); }
210 public int getModifiers() { return c.getModifiers(); }
213 final static class LoadedField implements IBinaryField {
217 LoadedField(Field f) {
219 int m = f.getModifiers();
221 c = Constant.NotAConstant;
222 if (Modifier.isFinal(m) && Modifier.isStatic(m)) {
224 Class type = f.getType();
225 if (type == Boolean.TYPE) {
226 c = new BooleanConstant(f.getBoolean(null));
227 } else if (type == Byte.TYPE) {
228 c = new ByteConstant(f.getByte(null));
229 } else if (type == Character.TYPE) {
230 c = new CharConstant(f.getChar(null));
231 } else if (type == Double.TYPE) {
232 c = new DoubleConstant(f.getDouble(null));
233 } else if (type == Float.TYPE) {
234 c = new FloatConstant(f.getFloat(null));
235 } else if (type == Integer.TYPE) {
236 c = new IntConstant(f.getInt(null));
237 } else if (type == Long.TYPE) {
238 c = new LongConstant(f.getLong(null));
239 } else if (type == Short.TYPE) {
240 c = new ShortConstant(f.getShort(null));
241 } else if (type == String.class) {
242 c = new StringConstant((String)f.get(null));
244 } catch (IllegalAccessException e) {}
247 public Constant getConstant() { return c; }
248 public char[] getTypeName() { return typeName(f.getType()); }
249 public char[] getName() { return f.getName().toCharArray(); }
250 public int getModifiers() { return f.getModifiers(); }
253 final static class LoadedConstructor implements IBinaryMethod {
254 private Constructor c;
258 LoadedConstructor(Constructor c) {
261 Class[] exs = c.getExceptionTypes();
262 ex = new char[exs.length][];
263 for (int i=0; i < ex.length; i++) ex[i] = name(exs[i]);
265 desc = descriptor(c.getParameterTypes(), null);
267 public int getModifiers() { return c.getModifiers(); }
268 public char[] getSelector() { return c.getName().toCharArray(); }
269 public boolean isConstructor() { return true; }
270 public boolean isClinit() { return false; }
271 public char[][] getArgumentNames() { return null; }
272 public char[][] getExceptionTypeNames() { return ex; }
273 public char[] getMethodDescriptor() { return desc; }
276 final static class LoadedMethod implements IBinaryMethod {
281 LoadedMethod(Method m) {
284 Class[] exs = m.getExceptionTypes();
285 ex = new char[exs.length][];
286 for (int i=0; i < ex.length; i++) ex[i] = name(exs[i]);
288 desc = descriptor(m.getParameterTypes(), m.getReturnType());
290 public int getModifiers() { return m.getModifiers(); }
291 public char[] getSelector() { return m.getName().toCharArray(); }
292 public boolean isConstructor() { return false; }
293 public boolean isClinit() { return false; }
294 public char[][] getArgumentNames() { return null; } // FEATURE: does this do anything cool?
295 public char[][] getExceptionTypeNames() { return ex; }
296 public char[] getMethodDescriptor() { return desc; }
299 final static class LoadedClass implements IBinaryType {
301 private IBinaryField[] f;
302 private char[][] inf;
303 private IBinaryNestedType[] nested;
304 private IBinaryMethod[] meth = null;
306 LoadedClass(Class c) {
309 Field[] fields = c.getFields();
310 f = new IBinaryField[fields.length];
311 for (int i=0; i < f.length; i++) f[i] = new LoadedField(fields[i]);
313 Class[] interfaces = c.getInterfaces();
314 inf = new char[interfaces.length][];
315 for (int i=0; i < inf.length; i++) inf[i] = name(interfaces[i]);
317 Class[] classes = c.getClasses();
318 nested = new IBinaryNestedType[classes.length];
319 for (int i=0; i < nested.length; i++)
320 nested[i] = new LoadedNestedType(classes[i]);
322 Constructor[] constructors = c.getDeclaredConstructors();
323 Method[] methods = c.getDeclaredMethods();
324 if (methods.length + constructors.length > 0) {
325 meth = new IBinaryMethod[methods.length + constructors.length];
327 for (int j=0; j < methods.length; j++)
328 meth[i++] = new LoadedMethod(methods[j]);
329 for (int j=0; j < constructors.length; j++)
330 meth[i++] = new LoadedConstructor(constructors[j]);
335 public char[] getName() { return name(c); }
336 public char[] getEnclosingTypeName() { return name(c.getDeclaringClass()); }
337 public char[] getSuperclassName() { return name(c.getSuperclass()); }
338 public IBinaryField[] getFields() { return f; }
339 public char[][] getInterfaceNames() { return inf; }
340 public IBinaryNestedType[] getMemberTypes() { return nested; }
341 public IBinaryMethod[] getMethods() { return meth; }
342 public int getModifiers() { return c.getModifiers(); }
344 public boolean isBinaryType() { return true; }
345 public boolean isClass() { return true; }
346 public boolean isInterface() { return c.isInterface(); }
347 public boolean isAnonymous() { return false; }
348 public boolean isLocal() { return false; } // FIXME
349 public boolean isMember() { return false; } // FIXME
350 public char[] sourceFileName() { return null; }
351 public char[] getFileName() { return null; }
353 public boolean equals(Object o) {
354 return o == this || super.equals(o) ||
355 (o != null && o instanceof LoadedClass &&
356 c.equals(((LoadedClass)o).c));
361 // Compiler Parameters ////////////////////////////////////////////////////
363 /** Used by compiler to resolve classes. */
364 final INameEnvironment env = new INameEnvironment() {
365 public NameEnvironmentAnswer findType(char[][] c) { return findType(name(c), pack(c)); }
366 public NameEnvironmentAnswer findType(char[] n, char[][] p) {
367 if (DEBUG) System.out.println("requesting: "+ str(p, '.') + "."+new String(n));
370 Class c = Class.forName(str(p, '.') + '.' + new String(n));
371 if (DEBUG) System.out.println("found class: "+ c);
372 IBinaryType b = (IBinaryType)loaded.get(c);
373 if (b == null) loaded.put(c, b = new LoadedClass(c));
374 if (DEBUG) System.out.println("returning "+b+", name="+new String(b.getName()));
375 return new NameEnvironmentAnswer(b);
376 } catch (ClassNotFoundException e) {}
378 // cut out searches for java.* packages in sources list
379 if (p.length > 0 && eq(p[0], "java".toCharArray())) return null;
382 for (int i=0; i < sources.length; i++)
383 if (eq(n, sources[i].n) && eq(p, sources[i].p))
384 return sources[i].compiled == null ?
385 new NameEnvironmentAnswer(sources[i].unit) :
386 new NameEnvironmentAnswer(new ClassFileReader(sources[i].compiled,
387 sources[i].orig.getName().toCharArray(), true));
388 } catch (ClassFormatException e) {
389 System.out.println("Unexpected ClassFormatException"); // FIXME
394 public boolean isPackage(char[][] parent, char[] name) {
395 String parentName = str(parent, '/');
396 for (int i=0; i < sources.length; i++)
397 if (eq(name, sources[i].n) && eq(parent, sources[i].p)) return false;
399 loader.getResource(parentName + ".class") == null &&
400 loader.getResource(parentName + '/' + new String(name) + ".class") == null;
402 public void cleanup() {}
405 /** Used by compiler to decide what do with problems.. */
406 private final IErrorHandlingPolicy policy =
407 DefaultErrorHandlingPolicies.proceedWithAllProblems();
409 /** Used by compiler for general options. */
410 private final Map settings = new HashMap();
412 settings.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE);
413 settings.put(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE);
414 settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_3);
415 settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_1);
418 /** Used by compiler for processing compiled classes and their errors. */
419 private final ICompilerRequestor results = new ICompilerRequestor() {
420 public void acceptResult(CompilationResult result) {
421 if (DEBUG) System.out.println("got result: "+result);
422 if (result.hasProblems()) {
423 boolean hasErrors = false;
424 IProblem[] p = result.getProblems();
425 for (int i=0; i < p.length; i++) {
426 out.print(p[i].getOriginatingFileName());
428 out.print(p[i].getSourceLineNumber());
430 if (p[i].isError()) { out.print(" error: "); hasErrors = true; }
431 else out.print(" warning: ");
432 out.println(p[i].getMessage());
435 if (hasErrors) return;
438 ClassFile[] c = result.getClassFiles();
439 for (int i=0; i < c.length; i++) {
441 // build package path to new class file
442 File path = builddir;
443 char[][] name = c[i].getCompoundName();
444 path = new File(builddir, str(pack(name), '/'));
445 if (DEBUG) System.out.println("DEBUG: creating path "+path+", out of builddir="+builddir);
446 if (!path.exists()) path.mkdirs();
448 // write new class file
449 path = new File(path, new String(name(name)) + ".class");
450 if (DEBUG) System.out.println("DEBUG: writing file "+path);
451 OutputStream o = new BufferedOutputStream(
452 new FileOutputStream(path));
453 o.write(c[i].getBytes());
455 } catch (IOException e) {
456 System.out.println("IOException writing class"); // FIXME
463 /** Problem creater for compiler. */
464 private final IProblemFactory problems = new DefaultProblemFactory();
467 // Helper Functiosn ///////////////////////////////////////////////////////
469 /** Convert source file path into class name block.
470 * eg. in: java/lang/String.java -> { {java} {lang} {String} } */
471 private char[][] classname(String name) {
472 String delim = name.indexOf('/') == -1 ? "." : "/";
474 if (name.endsWith(".java")) name = name.substring(0, name.length() - 5);
475 if (name.startsWith(delim)) name = name.substring(1);
477 StringTokenizer st = new StringTokenizer(name, delim);
478 char[][] n = new char[st.countTokens()][];
479 for (int i=0; st.hasMoreTokens(); i++) n[i] = st.nextToken().toCharArray();
483 /** Convert class name into a String. */
484 private static String str(char[][] name, char delim) {
485 StringBuffer b = new StringBuffer();
486 for (int i=0; name != null && i < name.length; i++) {
487 if (name[i] == null || name[i].length == 0) continue;
488 if (i > 0) b.append(delim);
494 /** Returns the package component of a class name.
495 * Effectively returns char[length - 1][]. */
496 private static char[][] pack(char[][] c) {
497 char[][] p = new char[c.length - 1][];
498 for (int i=0; i < p.length; i++) p[i] = c[i];
502 /** Returns the direct-name component of a class name.
503 * eg. String from java.lang.String */
504 private static char[] name(char[][] c) { return c[c.length - 1]; }
506 /** Returns true of contents of both char arrays are equal. */
507 private static boolean eq(char[][] c1, char[][] c2) {
508 if (c1.length != c2.length) return false;
509 for (int i=0; i < c1.length; i++) if (!eq(c1[i], c2[i])) return false;
513 /** Returns true of contents of both char arrays are equal. */
514 private static boolean eq(char[] c1, char[] c2) {
515 if (c1.length != c2.length) return false;
516 for (int i=0; i < c1.length; i++) if (c1[i] != c2[i]) return false;
520 /** Returns class name as per VM Spec 4.2. eg. java/lang/String */
521 private static char[] name(Class c) {
522 return c == null ? null : c.getName().replace('.', '/').toCharArray();
525 /** Returns the type name of a class as per VM Spec 4.3.2. */
526 private static char[] typeName(Class p) {
527 StringBuffer sb = new StringBuffer();
529 return sb.toString().toCharArray();
532 /** Returns the type name of a class as per VM Spec 4.3.2.
533 * eg. int -> I, String -> Ljava/lang/String; */
534 private static void typeName(Class p, StringBuffer sb) {
535 String name = p.getName();
536 switch (name.charAt(0)) {
537 case 'B': case 'C': case 'D': case 'F': case 'I':
538 case 'J': case 'S': case 'Z': case 'V': case '[':
539 sb.append(name(p)); break;
541 case 'b': if (name.equals("boolean")) { sb.append('Z'); break; }
542 if (name.equals("byte")) { sb.append('B'); break; }
543 case 'c': if (name.equals("char")) { sb.append('C'); break; }
544 case 'd': if (name.equals("double")) { sb.append('D'); break; }
545 case 'f': if (name.equals("float")) { sb.append('F'); break; }
546 case 'i': if (name.equals("int")) { sb.append('I'); break; }
547 case 'l': if (name.equals("long")) { sb.append('J'); break; }
548 case 's': if (name.equals("short")) { sb.append('S'); break; }
549 case 'v': if (name.equals("void")) { sb.append('V'); break; }
551 sb.append('L'); sb.append(name(p)); sb.append(';');
555 /** Returns the descriptor of a method per VM Spec 4.3.3.
556 * eg. int get(String n, boolean b) -> (Ljava/lang/String;B)I */
557 private static char[] descriptor(Class[] p, Class r) {
558 StringBuffer sb = new StringBuffer();
560 if (p != null) for (int i=0; i < p.length; i++) typeName(p[i], sb);
562 if (r != null) typeName(r, sb);
563 return sb.toString().toCharArray();