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 File sourcedir = new File(".");
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 = new File(dir == null ? "." : 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, 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 try { fileName = orig.getCanonicalPath().toCharArray(); } // FIXME: dont use full path
197 catch (IOException e) { fileName = orig.getName().toCharArray(); }
201 // ClassLoader Wrappers ///////////////////////////////////////////////////
203 final static class LoadedNestedType implements IBinaryNestedType {
205 LoadedNestedType(Class c) { this.c = c; }
206 public char[] getName() { return name(c); }
207 public char[] getEnclosingTypeName() { return name(c.getDeclaringClass()); }
208 public int getModifiers() { return c.getModifiers(); }
211 final static class LoadedField implements IBinaryField {
215 LoadedField(Field f) {
217 int m = f.getModifiers();
219 c = Constant.NotAConstant;
220 if (Modifier.isFinal(m) && Modifier.isStatic(m)) {
222 Class type = f.getType();
223 if (type == Boolean.TYPE) {
224 c = new BooleanConstant(f.getBoolean(null));
225 } else if (type == Byte.TYPE) {
226 c = new ByteConstant(f.getByte(null));
227 } else if (type == Character.TYPE) {
228 c = new CharConstant(f.getChar(null));
229 } else if (type == Double.TYPE) {
230 c = new DoubleConstant(f.getDouble(null));
231 } else if (type == Float.TYPE) {
232 c = new FloatConstant(f.getFloat(null));
233 } else if (type == Integer.TYPE) {
234 c = new IntConstant(f.getInt(null));
235 } else if (type == Long.TYPE) {
236 c = new LongConstant(f.getLong(null));
237 } else if (type == Short.TYPE) {
238 c = new ShortConstant(f.getShort(null));
239 } else if (type == String.class) {
240 c = new StringConstant((String)f.get(null));
242 } catch (IllegalAccessException e) {}
245 public Constant getConstant() { return c; }
246 public char[] getTypeName() { return typeName(f.getType()); }
247 public char[] getName() { return f.getName().toCharArray(); }
248 public int getModifiers() { return f.getModifiers(); }
251 final static class LoadedConstructor implements IBinaryMethod {
252 private Constructor c;
256 LoadedConstructor(Constructor c) {
259 Class[] exs = c.getExceptionTypes();
260 ex = new char[exs.length][];
261 for (int i=0; i < ex.length; i++) ex[i] = name(exs[i]);
263 desc = descriptor(c.getParameterTypes(), null);
265 public int getModifiers() { return c.getModifiers(); }
266 public char[] getSelector() { return c.getName().toCharArray(); }
267 public boolean isConstructor() { return true; }
268 public boolean isClinit() { return false; }
269 public char[][] getArgumentNames() { return null; }
270 public char[][] getExceptionTypeNames() { return ex; }
271 public char[] getMethodDescriptor() { return desc; }
274 final static class LoadedMethod implements IBinaryMethod {
279 LoadedMethod(Method m) {
282 Class[] exs = m.getExceptionTypes();
283 ex = new char[exs.length][];
284 for (int i=0; i < ex.length; i++) ex[i] = name(exs[i]);
286 desc = descriptor(m.getParameterTypes(), m.getReturnType());
288 public int getModifiers() { return m.getModifiers(); }
289 public char[] getSelector() { return m.getName().toCharArray(); }
290 public boolean isConstructor() { return false; }
291 public boolean isClinit() { return false; }
292 public char[][] getArgumentNames() { return null; } // FEATURE: does this do anything cool?
293 public char[][] getExceptionTypeNames() { return ex; }
294 public char[] getMethodDescriptor() { return desc; }
297 final static class LoadedClass implements IBinaryType {
299 private IBinaryField[] f;
300 private char[][] inf;
301 private IBinaryNestedType[] nested;
302 private IBinaryMethod[] meth = null;
304 LoadedClass(Class c) {
307 Field[] fields = c.getFields();
308 f = new IBinaryField[fields.length];
309 for (int i=0; i < f.length; i++) f[i] = new LoadedField(fields[i]);
311 Class[] interfaces = c.getInterfaces();
312 inf = new char[interfaces.length][];
313 for (int i=0; i < inf.length; i++) inf[i] = name(interfaces[i]);
315 Class[] classes = c.getClasses();
316 nested = new IBinaryNestedType[classes.length];
317 for (int i=0; i < nested.length; i++)
318 nested[i] = new LoadedNestedType(classes[i]);
320 Constructor[] constructors = c.getConstructors();
321 Method[] methods = c.getDeclaredMethods();
322 if (methods.length + constructors.length > 0) {
323 meth = new IBinaryMethod[methods.length + constructors.length];
325 for (int j=0; j < methods.length; j++)
326 meth[i++] = new LoadedMethod(methods[j]);
327 for (int j=0; j < constructors.length; j++)
328 meth[i++] = new LoadedConstructor(constructors[j]);
333 public char[] getName() { return name(c); }
334 public char[] getEnclosingTypeName() { return name(c.getDeclaringClass()); }
335 public char[] getSuperclassName() { return name(c.getSuperclass()); }
336 public IBinaryField[] getFields() { return f; }
337 public char[][] getInterfaceNames() { return inf; }
338 public IBinaryNestedType[] getMemberTypes() { return nested; }
339 public IBinaryMethod[] getMethods() { return meth; }
340 public int getModifiers() { return c.getModifiers(); }
342 public boolean isBinaryType() { return true; }
343 public boolean isClass() { return true; }
344 public boolean isInterface() { return c.isInterface(); }
345 public boolean isAnonymous() { return false; }
346 public boolean isLocal() { return false; } // FIXME
347 public boolean isMember() { return false; } // FIXME
348 public char[] sourceFileName() { return null; }
349 public char[] getFileName() { return null; }
351 public boolean equals(Object o) {
352 return o == this || super.equals(o) ||
353 (o != null && o instanceof LoadedClass &&
354 c.equals(((LoadedClass)o).c));
359 // Compiler Parameters ////////////////////////////////////////////////////
361 /** Used by compiler to resolve classes. */
362 final INameEnvironment env = new INameEnvironment() {
363 public NameEnvironmentAnswer findType(char[][] c) { return findType(name(c), pack(c)); }
364 public NameEnvironmentAnswer findType(char[] n, char[][] p) {
365 if (DEBUG) System.out.println("requesting: "+ str(p, '.') + "."+new String(n));
368 Class c = Class.forName(str(p, '.') + '.' + new String(n));
369 if (DEBUG) System.out.println("found class: "+ c);
370 IBinaryType b = (IBinaryType)loaded.get(c);
371 if (b == null) loaded.put(c, b = new LoadedClass(c));
372 if (DEBUG) System.out.println("returning "+b+", name="+new String(b.getName()));
373 return new NameEnvironmentAnswer(b);
374 } catch (ClassNotFoundException e) {}
376 // cut out searches for java.* packages in sources list
377 if (p.length > 0 && eq(p[0], "java".toCharArray())) return null;
380 for (int i=0; i < sources.length; i++)
381 if (eq(n, sources[i].n) && eq(p, sources[i].p))
382 return sources[i].compiled == null ?
383 new NameEnvironmentAnswer(sources[i].unit) :
384 new NameEnvironmentAnswer(new ClassFileReader(sources[i].compiled,
385 sources[i].orig.getName().toCharArray(), true));
386 } catch (ClassFormatException e) {
387 System.out.println("Unexpected ClassFormatException"); // FIXME
392 public boolean isPackage(char[][] parent, char[] name) {
393 String parentName = str(parent, '/');
394 for (int i=0; i < sources.length; i++)
395 if (eq(name, sources[i].n) && eq(parent, sources[i].p)) return false;
397 loader.getResource(parentName + ".class") == null &&
398 loader.getResource(parentName + '/' + new String(name) + ".class") == null;
400 public void cleanup() {}
403 /** Used by compiler to decide what do with problems.. */
404 private final IErrorHandlingPolicy policy =
405 DefaultErrorHandlingPolicies.proceedWithAllProblems();
407 /** Used by compiler for general options. */
408 private final Map settings = new HashMap();
410 settings.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE);
411 settings.put(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE);
412 settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_3);
413 settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_1);
416 /** Used by compiler for processing compiled classes and their errors. */
417 private final ICompilerRequestor results = new ICompilerRequestor() {
418 public void acceptResult(CompilationResult result) {
419 if (DEBUG) System.out.println("got result: "+result);
420 if (result.hasProblems()) {
421 boolean hasErrors = false;
422 IProblem[] p = result.getProblems();
423 for (int i=0; i < p.length; i++) {
424 if (p[i].isError()) hasErrors = true;
425 out.print(p[i].getOriginatingFileName());
427 out.print(p[i].getSourceLineNumber());
429 out.println(p[i].getMessage());
432 if (hasErrors) return;
435 ClassFile[] c = result.getClassFiles();
436 for (int i=0; i < c.length; i++) {
438 // build package path to new class file
439 File path = builddir;
440 char[][] name = c[i].getCompoundName();
441 path = new File(builddir, str(pack(name), '/'));
442 if (DEBUG) System.out.println("DEBUG: creating path "+path+", out of builddir="+builddir);
443 if (!path.exists()) path.mkdirs();
445 // write new class file
446 path = new File(path, new String(name(name)) + ".class");
447 if (DEBUG) System.out.println("DEBUG: writing file "+path);
448 OutputStream o = new BufferedOutputStream(
449 new FileOutputStream(path));
450 o.write(c[i].getBytes());
452 } catch (IOException e) {
453 System.out.println("IOException writing class"); // FIXME
460 /** Problem creater for compiler. */
461 private final IProblemFactory problems = new DefaultProblemFactory();
464 // Helper Functiosn ///////////////////////////////////////////////////////
466 /** Convert source file path into class name block.
467 * eg. in: java/lang/String.java -> { {java} {lang} {String} } */
468 private char[][] classname(String name) {
469 String delim = name.indexOf('/') == -1 ? "." : "/";
471 if (name.endsWith(".java")) name = name.substring(0, name.length() - 5);
472 if (name.startsWith(delim)) name = name.substring(1);
474 StringTokenizer st = new StringTokenizer(name, delim);
475 char[][] n = new char[st.countTokens()][];
476 for (int i=0; st.hasMoreTokens(); i++) n[i] = st.nextToken().toCharArray();
480 /** Convert class name into a String. */
481 private static String str(char[][] name, char delim) {
482 StringBuffer b = new StringBuffer();
483 for (int i=0; name != null && i < name.length; i++) {
484 if (name[i] == null || name[i].length == 0) continue;
485 if (i > 0) b.append(delim);
491 /** Returns the package component of a class name.
492 * Effectively returns char[length - 1][]. */
493 private static char[][] pack(char[][] c) {
494 char[][] p = new char[c.length - 1][];
495 for (int i=0; i < p.length; i++) p[i] = c[i];
499 /** Returns the direct-name component of a class name.
500 * eg. String from java.lang.String */
501 private static char[] name(char[][] c) { return c[c.length - 1]; }
503 /** Returns true of contents of both char arrays are equal. */
504 private static boolean eq(char[][] c1, char[][] c2) {
505 if (c1.length != c2.length) return false;
506 for (int i=0; i < c1.length; i++) if (!eq(c1[i], c2[i])) return false;
510 /** Returns true of contents of both char arrays are equal. */
511 private static boolean eq(char[] c1, char[] c2) {
512 if (c1.length != c2.length) return false;
513 for (int i=0; i < c1.length; i++) if (c1[i] != c2[i]) return false;
517 /** Returns class name as per VM Spec 4.2. eg. java/lang/String */
518 private static char[] name(Class c) {
519 return c == null ? null : c.getName().replace('.', '/').toCharArray();
522 /** Returns the type name of a class as per VM Spec 4.3.2. */
523 private static char[] typeName(Class p) {
524 StringBuffer sb = new StringBuffer();
526 return sb.toString().toCharArray();
529 /** Returns the type name of a class as per VM Spec 4.3.2.
530 * eg. int -> I, String -> Ljava/lang/String; */
531 private static void typeName(Class p, StringBuffer sb) {
532 String name = p.getName();
533 switch (name.charAt(0)) {
534 case 'B': case 'C': case 'D': case 'F': case 'I':
535 case 'J': case 'S': case 'Z': case 'V': case '[':
536 sb.append(name(p)); break;
538 case 'b': if (name.equals("boolean")) { sb.append('Z'); break; }
539 if (name.equals("byte")) { sb.append('B'); break; }
540 case 'c': if (name.equals("char")) { sb.append('C'); break; }
541 case 'd': if (name.equals("double")) { sb.append('D'); break; }
542 case 'f': if (name.equals("float")) { sb.append('F'); break; }
543 case 'i': if (name.equals("int")) { sb.append('I'); break; }
544 case 'l': if (name.equals("long")) { sb.append('J'); break; }
545 case 's': if (name.equals("short")) { sb.append('S'); break; }
546 case 'v': if (name.equals("void")) { sb.append('V'); break; }
548 sb.append('L'); sb.append(name(p)); sb.append(';');
552 /** Returns the descriptor of a method per VM Spec 4.3.3.
553 * eg. int get(String n, boolean b) -> (Ljava/lang/String;B)I */
554 private static char[] descriptor(Class[] p, Class r) {
555 StringBuffer sb = new StringBuffer();
557 if (p != null) for (int i=0; i < p.length; i++) typeName(p[i], sb);
559 if (r != null) typeName(r, sb);
560 return sb.toString().toCharArray();