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 = new Preprocessor(null, null, Collections.EMPTY_LIST);
87 private Source[] sources;
89 private File builddir = new File(".");
90 private File sourcedir = new File(".");
94 public void setBuildDir(String dir) { builddir = new File(dir == null ? "." : dir); }
95 public void setSourceDir(String dir) { sourcedir = new File(dir == null ? "." : dir); }
97 /** Pass CompilerOptions.VERSION_1_*. A String of form "1.1", ".2", etc. */
98 public void setSource(String v) { settings.put(CompilerOptions.OPTION_Source, v); }
100 /** Pass CompilerOptions.VERSION_1_*. A String of form "1.1", ".2", etc. */
101 public void setTarget(String v) { settings.put(CompilerOptions.OPTION_TargetPlatform, v); }
103 public void setBuilddir(File f) { builddir = f; }
105 public void compile() {
106 List s = new ArrayList();
107 filterSources(s, sourcedir, new char[0][]);
108 if (DEBUG) System.out.println("working with "+s.size() +" sources");
109 sources = new Source[s.size()]; s.toArray(sources);
110 ICompilationUnit[] units = new ICompilationUnit[s.size()];
111 for (int i=0; i < sources.length; i++) units[i] = sources[i].unit;
113 org.eclipse.jdt.internal.compiler.Compiler jdt =
114 new org.eclipse.jdt.internal.compiler.Compiler(
115 env, policy, settings, results, problems);
119 private final FilenameFilter filterSrcs = new FilenameFilter() {
120 public boolean accept(File dir, String name) { return name.endsWith(".java"); }
122 private final FileFilter filterDirs = new FileFilter() {
123 public boolean accept(File path) { return path.isDirectory(); }
125 private void filterSources(List s, File dir, char[][] pack) {
126 File[] ja = dir.listFiles(filterSrcs);
127 for (int i=0; i < ja.length; i++)
128 s.add(new Source(ja[i], name(classname(ja[i].getName())), pack));
130 File[] d = dir.listFiles(filterDirs);
131 for (int i=0; i < d.length; i++) {
132 char[][] newpack = new char[pack.length + 1][];
133 for (int j=0; j < pack.length; j++) newpack[j] = pack[j];
134 newpack[pack.length] = d[i].getName().toCharArray();
135 filterSources(s, d[i], newpack);
140 /** Represents a file to be compiled. */
143 char[] n; char[][] p;
145 char[] processed = null;
146 byte[] compiled = null;
148 final ICompilationUnit unit = new ICompilationUnit() {
149 public char[] getMainTypeName() { return n; }
150 public char[][] getPackageName() { return p; }
151 public char[] getFileName() { return fileName; }
152 public char[] getContents() {
153 if (processed != null) return processed;
156 Reader r = new InputStreamReader(new BufferedInputStream(
157 new FileInputStream(orig)));
158 StringWriter w = new StringWriter();
161 synchronized (preprocessor) {
162 preprocessor.setReader(r);
163 preprocessor.setWriter(w);
164 err = preprocessor.process();
167 if (err.size() > 0) {
168 System.out.println("Preprocessor Errors, "+err); // FIXME
172 processed = w.toString().toCharArray();
173 } catch (IOException e) {
174 System.out.println("IOException: "+e); // FIXME
182 private Source(File o, char[] n, char[][] p) {
183 orig = o; this.n = n; this.p = p;
184 try { fileName = orig.getCanonicalPath().toCharArray(); } // FIXME: dont use full path
185 catch (IOException e) { fileName = orig.getName().toCharArray(); }
189 // ClassLoader Wrappers ///////////////////////////////////////////////////
191 final static class LoadedNestedType implements IBinaryNestedType {
193 LoadedNestedType(Class c) { this.c = c; }
194 public char[] getName() { return name(c); }
195 public char[] getEnclosingTypeName() { return name(c.getDeclaringClass()); }
196 public int getModifiers() { return c.getModifiers(); }
199 final static class LoadedField implements IBinaryField {
203 LoadedField(Field f) {
205 int m = f.getModifiers();
207 c = Constant.NotAConstant;
208 if (Modifier.isFinal(m) && Modifier.isStatic(m)) {
210 Class type = f.getType();
211 if (type == Boolean.TYPE) {
212 c = new BooleanConstant(f.getBoolean(null));
213 } else if (type == Byte.TYPE) {
214 c = new ByteConstant(f.getByte(null));
215 } else if (type == Character.TYPE) {
216 c = new CharConstant(f.getChar(null));
217 } else if (type == Double.TYPE) {
218 c = new DoubleConstant(f.getDouble(null));
219 } else if (type == Float.TYPE) {
220 c = new FloatConstant(f.getFloat(null));
221 } else if (type == Integer.TYPE) {
222 c = new IntConstant(f.getInt(null));
223 } else if (type == Long.TYPE) {
224 c = new LongConstant(f.getLong(null));
225 } else if (type == Short.TYPE) {
226 c = new ShortConstant(f.getShort(null));
227 } else if (type == String.class) {
228 c = new StringConstant((String)f.get(null));
230 } catch (IllegalAccessException e) {}
233 public Constant getConstant() { return c; }
234 public char[] getTypeName() { return typeName(f.getType()); }
235 public char[] getName() { return f.getName().toCharArray(); }
236 public int getModifiers() { return f.getModifiers(); }
239 final static class LoadedConstructor implements IBinaryMethod {
240 private Constructor c;
244 LoadedConstructor(Constructor c) {
247 Class[] exs = c.getExceptionTypes();
248 ex = new char[exs.length][];
249 for (int i=0; i < ex.length; i++) ex[i] = name(exs[i]);
251 desc = descriptor(c.getParameterTypes(), null);
253 public int getModifiers() { return c.getModifiers(); }
254 public char[] getSelector() { return c.getName().toCharArray(); }
255 public boolean isConstructor() { return true; }
256 public boolean isClinit() { return false; }
257 public char[][] getArgumentNames() { return null; }
258 public char[][] getExceptionTypeNames() { return ex; }
259 public char[] getMethodDescriptor() { return desc; }
262 final static class LoadedMethod implements IBinaryMethod {
267 LoadedMethod(Method m) {
270 Class[] exs = m.getExceptionTypes();
271 ex = new char[exs.length][];
272 for (int i=0; i < ex.length; i++) ex[i] = name(exs[i]);
274 desc = descriptor(m.getParameterTypes(), m.getReturnType());
276 public int getModifiers() { return m.getModifiers(); }
277 public char[] getSelector() { return m.getName().toCharArray(); }
278 public boolean isConstructor() { return false; }
279 public boolean isClinit() { return false; }
280 public char[][] getArgumentNames() { return null; } // FEATURE: does this do anything cool?
281 public char[][] getExceptionTypeNames() { return ex; }
282 public char[] getMethodDescriptor() { return desc; }
285 final static class LoadedClass implements IBinaryType {
287 private IBinaryField[] f;
288 private char[][] inf;
289 private IBinaryNestedType[] nested;
290 private IBinaryMethod[] meth = null;
292 LoadedClass(Class c) {
295 Field[] fields = c.getFields();
296 f = new IBinaryField[fields.length];
297 for (int i=0; i < f.length; i++) f[i] = new LoadedField(fields[i]);
299 Class[] interfaces = c.getInterfaces();
300 inf = new char[interfaces.length][];
301 for (int i=0; i < inf.length; i++) inf[i] = name(interfaces[i]);
303 Class[] classes = c.getClasses();
304 nested = new IBinaryNestedType[classes.length];
305 for (int i=0; i < nested.length; i++)
306 nested[i] = new LoadedNestedType(classes[i]);
308 Constructor[] constructors = c.getConstructors();
309 Method[] methods = c.getDeclaredMethods();
310 if (methods.length + constructors.length > 0) {
311 meth = new IBinaryMethod[methods.length + constructors.length];
313 for (int j=0; j < methods.length; j++)
314 meth[i++] = new LoadedMethod(methods[j]);
315 for (int j=0; j < constructors.length; j++)
316 meth[i++] = new LoadedConstructor(constructors[j]);
321 public char[] getName() { return name(c); }
322 public char[] getEnclosingTypeName() { return name(c.getDeclaringClass()); }
323 public char[] getSuperclassName() { return name(c.getSuperclass()); }
324 public IBinaryField[] getFields() { return f; }
325 public char[][] getInterfaceNames() { return inf; }
326 public IBinaryNestedType[] getMemberTypes() { return nested; }
327 public IBinaryMethod[] getMethods() { return meth; }
328 public int getModifiers() { return c.getModifiers(); }
330 public boolean isBinaryType() { return true; }
331 public boolean isClass() { return true; }
332 public boolean isInterface() { return c.isInterface(); }
333 public boolean isAnonymous() { return false; }
334 public boolean isLocal() { return false; } // FIXME
335 public boolean isMember() { return false; } // FIXME
336 public char[] sourceFileName() { return null; }
337 public char[] getFileName() { return null; }
339 public boolean equals(Object o) {
340 return o == this || super.equals(o) ||
341 (o != null && o instanceof LoadedClass &&
342 c.equals(((LoadedClass)o).c));
347 // Compiler Parameters ////////////////////////////////////////////////////
349 /** Used by compiler to resolve classes. */
350 final INameEnvironment env = new INameEnvironment() {
351 public NameEnvironmentAnswer findType(char[][] c) { return findType(name(c), pack(c)); }
352 public NameEnvironmentAnswer findType(char[] n, char[][] p) {
353 if (DEBUG) System.out.println("requesting: "+ str(p, '.') + "."+new String(n));
356 Class c = Class.forName(str(p, '.') + '.' + new String(n));
357 if (DEBUG) System.out.println("found class: "+ c);
358 IBinaryType b = (IBinaryType)loaded.get(c);
359 if (b == null) loaded.put(c, b = new LoadedClass(c));
360 if (DEBUG) System.out.println("returning "+b+", name="+new String(b.getName()));
361 return new NameEnvironmentAnswer(b);
362 } catch (ClassNotFoundException e) {}
364 // cut out searches for java.* packages in sources list
365 if (p.length > 0 && eq(p[0], "java".toCharArray())) return null;
368 for (int i=0; i < sources.length; i++)
369 if (eq(n, sources[i].n) && eq(p, sources[i].p))
370 return sources[i].compiled == null ?
371 new NameEnvironmentAnswer(sources[i].unit) :
372 new NameEnvironmentAnswer(new ClassFileReader(sources[i].compiled,
373 sources[i].orig.getName().toCharArray(), true));
374 } catch (ClassFormatException e) {
375 System.out.println("Unexpected ClassFormatException"); // FIXME
380 public boolean isPackage(char[][] parent, char[] name) {
381 String parentName = str(parent, '/');
382 for (int i=0; i < sources.length; i++)
383 if (eq(name, sources[i].n) && eq(parent, sources[i].p)) return false;
385 loader.getResource(parentName + ".class") == null &&
386 loader.getResource(parentName + '/' + new String(name) + ".class") == null;
388 public void cleanup() {}
391 /** Used by compiler to decide what do with problems.. */
392 private final IErrorHandlingPolicy policy =
393 DefaultErrorHandlingPolicies.proceedWithAllProblems();
395 /** Used by compiler for general options. */
396 private final Map settings = new HashMap();
398 settings.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE);
399 settings.put(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE);
400 settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_3);
401 settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_1);
404 /** Used by compiler for processing compiled classes and their errors. */
405 private final ICompilerRequestor results = new ICompilerRequestor() {
406 public void acceptResult(CompilationResult result) {
407 if (DEBUG) System.out.println("got result: "+result);
408 if (result.hasProblems()) {
409 boolean hasErrors = false;
410 IProblem[] p = result.getProblems();
411 for (int i=0; i < p.length; i++) {
412 if (p[i].isError()) hasErrors = true;
413 out.print(p[i].getOriginatingFileName());
415 out.print(p[i].getSourceLineNumber());
417 out.println(p[i].getMessage());
420 if (hasErrors) return;
423 ClassFile[] c = result.getClassFiles();
424 for (int i=0; i < c.length; i++) {
426 // build package path to new class file
427 File path = builddir;
428 char[][] name = c[i].getCompoundName();
429 path = new File(builddir, str(pack(name), '/'));
430 if (DEBUG) System.out.println("DEBUG: creating path "+path+", out of builddir="+builddir);
431 if (!path.exists()) path.mkdirs();
433 // write new class file
434 path = new File(path, new String(name(name)) + ".class");
435 if (DEBUG) System.out.println("DEBUG: writing file "+path);
436 OutputStream o = new BufferedOutputStream(
437 new FileOutputStream(path));
438 o.write(c[i].getBytes());
440 } catch (IOException e) {
441 System.out.println("IOException writing class"); // FIXME
448 /** Problem creater for compiler. */
449 private final IProblemFactory problems = new DefaultProblemFactory();
452 // Helper Functiosn ///////////////////////////////////////////////////////
454 /** Convert source file path into class name block.
455 * eg. in: java/lang/String.java -> { {java} {lang} {String} } */
456 private char[][] classname(String name) {
457 String delim = name.indexOf('/') == -1 ? "." : "/";
459 if (name.endsWith(".java")) name = name.substring(0, name.length() - 5);
460 if (name.startsWith(delim)) name = name.substring(1);
462 StringTokenizer st = new StringTokenizer(name, delim);
463 char[][] n = new char[st.countTokens()][];
464 for (int i=0; st.hasMoreTokens(); i++) n[i] = st.nextToken().toCharArray();
468 /** Convert class name into a String. */
469 private static String str(char[][] name, char delim) {
470 StringBuffer b = new StringBuffer();
471 for (int i=0; name != null && i < name.length; i++) {
472 if (name[i] == null || name[i].length == 0) continue;
473 if (i > 0) b.append(delim);
479 /** Returns the package component of a class name.
480 * Effectively returns char[length - 1][]. */
481 private static char[][] pack(char[][] c) {
482 char[][] p = new char[c.length - 1][];
483 for (int i=0; i < p.length; i++) p[i] = c[i];
487 /** Returns the direct-name component of a class name.
488 * eg. String from java.lang.String */
489 private static char[] name(char[][] c) { return c[c.length - 1]; }
491 /** Returns true of contents of both char arrays are equal. */
492 private static boolean eq(char[][] c1, char[][] c2) {
493 if (c1.length != c2.length) return false;
494 for (int i=0; i < c1.length; i++) if (!eq(c1[i], c2[i])) return false;
498 /** Returns true of contents of both char arrays are equal. */
499 private static boolean eq(char[] c1, char[] c2) {
500 if (c1.length != c2.length) return false;
501 for (int i=0; i < c1.length; i++) if (c1[i] != c2[i]) return false;
505 /** Returns class name as per VM Spec 4.2. eg. java/lang/String */
506 private static char[] name(Class c) {
507 return c == null ? null : c.getName().replace('.', '/').toCharArray();
510 /** Returns the type name of a class as per VM Spec 4.3.2. */
511 private static char[] typeName(Class p) {
512 StringBuffer sb = new StringBuffer();
514 return sb.toString().toCharArray();
517 /** Returns the type name of a class as per VM Spec 4.3.2.
518 * eg. int -> I, String -> Ljava/lang/String; */
519 private static void typeName(Class p, StringBuffer sb) {
520 String name = p.getName();
521 switch (name.charAt(0)) {
522 case 'B': case 'C': case 'D': case 'F': case 'I':
523 case 'J': case 'S': case 'Z': case 'V': case '[':
524 sb.append(name(p)); break;
526 case 'b': if (name.equals("boolean")) { sb.append('Z'); break; }
527 if (name.equals("byte")) { sb.append('B'); break; }
528 case 'c': if (name.equals("char")) { sb.append('C'); break; }
529 case 'd': if (name.equals("double")) { sb.append('D'); break; }
530 case 'f': if (name.equals("float")) { sb.append('F'); break; }
531 case 'i': if (name.equals("int")) { sb.append('I'); break; }
532 case 'l': if (name.equals("long")) { sb.append('J'); break; }
533 case 's': if (name.equals("short")) { sb.append('S'); break; }
534 case 'v': if (name.equals("void")) { sb.append('V'); break; }
536 sb.append('L'); sb.append(name(p)); sb.append(';');
540 /** Returns the descriptor of a method per VM Spec 4.3.3.
541 * eg. int get(String n, boolean b) -> (Ljava/lang/String;B)I */
542 private static char[] descriptor(Class[] p, Class r) {
543 StringBuffer sb = new StringBuffer();
545 if (p != null) for (int i=0; i < p.length; i++) typeName(p[i], sb);
547 if (r != null) typeName(r, sb);
548 return sb.toString().toCharArray();