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 // add the java files in this directory
151 File bdir = new File(builddir, str(pack, File.separatorChar));
152 File[] ja = dir.listFiles(filterSrcs);
153 for (int i=0; i < ja.length; i++) {
154 char[] n = name(classname(ja[i].getName()));
156 // skip the file if the build version is newer than the source
157 File bfile = new File(bdir, new String(n) + ".class");
158 if (bfile.lastModified() > ja[i].lastModified()) continue;
160 s.add(new Source(ja[i], n, pack));
163 // add the subdirectories as packages
164 File[] d = dir.listFiles(filterDirs);
165 for (int i=0; i < d.length; i++) {
166 char[][] newpack = new char[pack.length + 1][];
167 for (int j=0; j < pack.length; j++) newpack[j] = pack[j];
168 newpack[pack.length] = d[i].getName().toCharArray();
169 filterSources(s, d[i], newpack);
174 /** Represents a file to be compiled. */
177 char[] n; char[][] p;
179 char[] processed = null;
180 byte[] compiled = null;
182 final ICompilationUnit unit = new ICompilationUnit() {
183 public char[] getMainTypeName() { return n; }
184 public char[][] getPackageName() { return p; }
185 public char[] getFileName() { return fileName; }
186 public char[] getContents() {
187 if (processed != null) return processed;
190 Reader r = new InputStreamReader(new BufferedInputStream(
191 new FileInputStream(orig)));
192 StringWriter w = new StringWriter();
195 synchronized (preprocessor) {
196 preprocessor.setReader(r);
197 preprocessor.setWriter(w);
198 err = preprocessor.process();
201 if (err.size() > 0) {
202 System.out.println("Preprocessor Errors, "+err); // FIXME
206 processed = w.toString().toCharArray();
207 } catch (IOException e) {
208 System.out.println("IOException: "+e); // FIXME
216 private Source(File o, char[] n, char[][] p) {
217 orig = o; this.n = n; this.p = p;
218 String file = sourcedir;
219 file += File.separatorChar + str(p, File.separatorChar);
220 file += File.separatorChar + new String(n) + ".java";
221 fileName = file.toCharArray();
225 // ClassLoader Wrappers ///////////////////////////////////////////////////
227 final static class LoadedNestedType implements IBinaryNestedType {
229 LoadedNestedType(Class c) { this.c = c; }
230 public char[] getName() { return name(c); }
231 public char[] getEnclosingTypeName() { return name(c.getDeclaringClass()); }
232 public int getModifiers() { return c.getModifiers(); }
235 final static class LoadedField implements IBinaryField {
239 LoadedField(Field f) {
241 int m = f.getModifiers();
243 c = Constant.NotAConstant;
244 if (Modifier.isFinal(m) && Modifier.isStatic(m)) {
246 Class type = f.getType();
247 if (type == Boolean.TYPE) {
248 c = new BooleanConstant(f.getBoolean(null));
249 } else if (type == Byte.TYPE) {
250 c = new ByteConstant(f.getByte(null));
251 } else if (type == Character.TYPE) {
252 c = new CharConstant(f.getChar(null));
253 } else if (type == Double.TYPE) {
254 c = new DoubleConstant(f.getDouble(null));
255 } else if (type == Float.TYPE) {
256 c = new FloatConstant(f.getFloat(null));
257 } else if (type == Integer.TYPE) {
258 c = new IntConstant(f.getInt(null));
259 } else if (type == Long.TYPE) {
260 c = new LongConstant(f.getLong(null));
261 } else if (type == Short.TYPE) {
262 c = new ShortConstant(f.getShort(null));
263 } else if (type == String.class) {
264 c = new StringConstant((String)f.get(null));
266 } catch (IllegalAccessException e) {}
269 public Constant getConstant() { return c; }
270 public char[] getTypeName() { return typeName(f.getType()); }
271 public char[] getName() { return f.getName().toCharArray(); }
272 public int getModifiers() { return f.getModifiers(); }
275 final static class LoadedConstructor implements IBinaryMethod {
276 private Constructor c;
280 LoadedConstructor(Constructor c) {
283 Class[] exs = c.getExceptionTypes();
284 ex = new char[exs.length][];
285 for (int i=0; i < ex.length; i++) ex[i] = name(exs[i]);
287 desc = descriptor(c.getParameterTypes(), null);
289 public int getModifiers() { return c.getModifiers(); }
290 public char[] getSelector() { return c.getName().toCharArray(); }
291 public boolean isConstructor() { return true; }
292 public boolean isClinit() { return false; }
293 public char[][] getArgumentNames() { return null; }
294 public char[][] getExceptionTypeNames() { return ex; }
295 public char[] getMethodDescriptor() { return desc; }
298 final static class LoadedMethod implements IBinaryMethod {
303 LoadedMethod(Method m) {
306 Class[] exs = m.getExceptionTypes();
307 ex = new char[exs.length][];
308 for (int i=0; i < ex.length; i++) ex[i] = name(exs[i]);
310 desc = descriptor(m.getParameterTypes(), m.getReturnType());
312 public int getModifiers() { return m.getModifiers(); }
313 public char[] getSelector() { return m.getName().toCharArray(); }
314 public boolean isConstructor() { return false; }
315 public boolean isClinit() { return false; }
316 public char[][] getArgumentNames() { return null; } // FEATURE: does this do anything cool?
317 public char[][] getExceptionTypeNames() { return ex; }
318 public char[] getMethodDescriptor() { return desc; }
321 final static class LoadedClass implements IBinaryType {
323 private IBinaryField[] f;
324 private char[][] inf;
325 private IBinaryNestedType[] nested;
326 private IBinaryMethod[] meth = null;
328 LoadedClass(Class c) {
331 Field[] fields = c.getFields();
332 f = new IBinaryField[fields.length];
333 for (int i=0; i < f.length; i++) f[i] = new LoadedField(fields[i]);
335 Class[] interfaces = c.getInterfaces();
336 inf = new char[interfaces.length][];
337 for (int i=0; i < inf.length; i++) inf[i] = name(interfaces[i]);
339 Class[] classes = c.getClasses();
340 nested = new IBinaryNestedType[classes.length];
341 for (int i=0; i < nested.length; i++)
342 nested[i] = new LoadedNestedType(classes[i]);
344 Constructor[] constructors = c.getDeclaredConstructors();
345 Method[] methods = c.getDeclaredMethods();
346 if (methods.length + constructors.length > 0) {
347 meth = new IBinaryMethod[methods.length + constructors.length];
349 for (int j=0; j < methods.length; j++)
350 meth[i++] = new LoadedMethod(methods[j]);
351 for (int j=0; j < constructors.length; j++)
352 meth[i++] = new LoadedConstructor(constructors[j]);
357 public char[] getName() { return name(c); }
358 public char[] getEnclosingTypeName() { return name(c.getDeclaringClass()); }
359 public char[] getSuperclassName() { return name(c.getSuperclass()); }
360 public IBinaryField[] getFields() { return f; }
361 public char[][] getInterfaceNames() { return inf; }
362 public IBinaryNestedType[] getMemberTypes() { return nested; }
363 public IBinaryMethod[] getMethods() { return meth; }
364 public int getModifiers() { return c.getModifiers(); }
366 public boolean isBinaryType() { return true; }
367 public boolean isClass() { return true; }
368 public boolean isInterface() { return c.isInterface(); }
369 public boolean isAnonymous() { return false; }
370 public boolean isLocal() { return false; } // FIXME
371 public boolean isMember() { return false; } // FIXME
372 public char[] sourceFileName() { return null; }
373 public char[] getFileName() { return null; }
375 public boolean equals(Object o) {
376 return o == this || super.equals(o) ||
377 (o != null && o instanceof LoadedClass &&
378 c.equals(((LoadedClass)o).c));
383 // Compiler Parameters ////////////////////////////////////////////////////
385 /** Used by compiler to resolve classes. */
386 final INameEnvironment env = new INameEnvironment() {
387 public NameEnvironmentAnswer findType(char[][] c) { return findType(name(c), pack(c)); }
388 public NameEnvironmentAnswer findType(char[] n, char[][] p) {
389 if (DEBUG) System.out.println("requesting: "+ str(p, '.') + "."+new String(n));
392 Class c = Class.forName(str(p, '.') + '.' + new String(n));
393 if (DEBUG) System.out.println("found class: "+ c);
394 IBinaryType b = (IBinaryType)loaded.get(c);
395 if (b == null) loaded.put(c, b = new LoadedClass(c));
396 if (DEBUG) System.out.println("returning "+b+", name="+new String(b.getName()));
397 return new NameEnvironmentAnswer(b);
398 } catch (ClassNotFoundException e) {}
400 // cut out searches for java.* packages in sources list
401 if (p.length > 0 && eq(p[0], "java".toCharArray())) return null;
404 for (int i=0; i < sources.length; i++)
405 if (eq(n, sources[i].n) && eq(p, sources[i].p))
406 return sources[i].compiled == null ?
407 new NameEnvironmentAnswer(sources[i].unit) :
408 new NameEnvironmentAnswer(new ClassFileReader(sources[i].compiled,
409 sources[i].orig.getName().toCharArray(), true));
410 } catch (ClassFormatException e) {
411 System.out.println("Unexpected ClassFormatException"); // FIXME
416 public boolean isPackage(char[][] parent, char[] name) {
417 String parentName = str(parent, '/');
418 for (int i=0; i < sources.length; i++)
419 if (eq(name, sources[i].n) && eq(parent, sources[i].p)) return false;
421 loader.getResource(parentName + ".class") == null &&
422 loader.getResource(parentName + '/' + new String(name) + ".class") == null;
424 public void cleanup() {}
427 /** Used by compiler to decide what do with problems.. */
428 private final IErrorHandlingPolicy policy =
429 DefaultErrorHandlingPolicies.proceedWithAllProblems();
431 /** Used by compiler for general options. */
432 private final Map settings = new HashMap();
434 settings.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE);
435 settings.put(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE);
436 settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_3);
437 settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_1);
440 /** Used by compiler for processing compiled classes and their errors. */
441 private final ICompilerRequestor results = new ICompilerRequestor() {
442 public void acceptResult(CompilationResult result) {
443 if (DEBUG) System.out.println("got result: "+result);
444 if (result.hasProblems()) {
446 IProblem[] p = result.getProblems();
448 for (int i=0; i < p.length; i++) {
449 if (p[i].isError()) { o = out; err = true; }
452 o.print(p[i].getOriginatingFileName());
454 o.print(p[i].getSourceLineNumber());
456 o.print(p[i].isError() ? " error: " : " warning: ");
457 o.println(p[i].getMessage());
460 if (err) { hasErrors = true; return; }
463 ClassFile[] c = result.getClassFiles();
464 for (int i=0; i < c.length; i++) {
466 // build package path to new class file
467 File path = builddir;
468 char[][] name = c[i].getCompoundName();
469 path = new File(builddir, str(pack(name), '/'));
470 if (DEBUG) System.out.println("DEBUG: creating path "+path+", out of builddir="+builddir);
471 if (!path.exists()) path.mkdirs();
473 // write new class file
474 path = new File(path, new String(name(name)) + ".class");
475 if (DEBUG) System.out.println("DEBUG: writing file "+path);
476 OutputStream o = new BufferedOutputStream(
477 new FileOutputStream(path));
478 o.write(c[i].getBytes());
480 } catch (IOException e) {
481 System.out.println("IOException writing class"); // FIXME
488 /** Problem creater for compiler. */
489 private final IProblemFactory problems = new DefaultProblemFactory();
492 // Helper Functiosn ///////////////////////////////////////////////////////
494 /** Convert source file path into class name block.
495 * eg. in: java/lang/String.java -> { {java} {lang} {String} } */
496 private char[][] classname(String name) {
497 String delim = name.indexOf('/') == -1 ? "." : "/";
499 if (name.endsWith(".java")) name = name.substring(0, name.length() - 5);
500 if (name.startsWith(delim)) name = name.substring(1);
502 StringTokenizer st = new StringTokenizer(name, delim);
503 char[][] n = new char[st.countTokens()][];
504 for (int i=0; st.hasMoreTokens(); i++) n[i] = st.nextToken().toCharArray();
508 /** Convert class name into a String. */
509 private static String str(char[][] name, char delim) {
510 StringBuffer b = new StringBuffer();
511 for (int i=0; name != null && i < name.length; i++) {
512 if (name[i] == null || name[i].length == 0) continue;
513 if (i > 0) b.append(delim);
519 /** Returns the package component of a class name.
520 * Effectively returns char[length - 1][]. */
521 private static char[][] pack(char[][] c) {
522 char[][] p = new char[c.length - 1][];
523 for (int i=0; i < p.length; i++) p[i] = c[i];
527 /** Returns the direct-name component of a class name.
528 * eg. String from java.lang.String */
529 private static char[] name(char[][] c) { return c[c.length - 1]; }
531 /** Returns true of contents of both char arrays are equal. */
532 private static boolean eq(char[][] c1, char[][] c2) {
533 if (c1.length != c2.length) return false;
534 for (int i=0; i < c1.length; i++) if (!eq(c1[i], c2[i])) return false;
538 /** Returns true of contents of both char arrays are equal. */
539 private static boolean eq(char[] c1, char[] c2) {
540 if (c1.length != c2.length) return false;
541 for (int i=0; i < c1.length; i++) if (c1[i] != c2[i]) return false;
545 /** Returns class name as per VM Spec 4.2. eg. java/lang/String */
546 private static char[] name(Class c) {
547 return c == null ? null : c.getName().replace('.', '/').toCharArray();
550 /** Returns the type name of a class as per VM Spec 4.3.2. */
551 private static char[] typeName(Class p) {
552 StringBuffer sb = new StringBuffer();
554 return sb.toString().toCharArray();
557 /** Returns the type name of a class as per VM Spec 4.3.2.
558 * eg. int -> I, String -> Ljava/lang/String; */
559 private static void typeName(Class p, StringBuffer sb) {
560 String name = p.getName();
561 switch (name.charAt(0)) {
562 case 'B': case 'C': case 'D': case 'F': case 'I':
563 case 'J': case 'S': case 'Z': case 'V': case '[':
564 sb.append(name(p)); break;
566 case 'b': if (name.equals("boolean")) { sb.append('Z'); break; }
567 if (name.equals("byte")) { sb.append('B'); break; }
568 case 'c': if (name.equals("char")) { sb.append('C'); break; }
569 case 'd': if (name.equals("double")) { sb.append('D'); break; }
570 case 'f': if (name.equals("float")) { sb.append('F'); break; }
571 case 'i': if (name.equals("int")) { sb.append('I'); break; }
572 case 'l': if (name.equals("long")) { sb.append('J'); break; }
573 case 's': if (name.equals("short")) { sb.append('S'); break; }
574 case 'v': if (name.equals("void")) { sb.append('V'); break; }
576 sb.append('L'); sb.append(name(p)); sb.append(';');
580 /** Returns the descriptor of a method per VM Spec 4.3.3.
581 * eg. int get(String n, boolean b) -> (Ljava/lang/String;B)I */
582 private static char[] descriptor(Class[] p, Class r) {
583 StringBuffer sb = new StringBuffer();
585 if (p != null) for (int i=0; i < p.length; i++) typeName(p[i], sb);
587 if (r != null) typeName(r, sb);
588 return sb.toString().toCharArray();