5 import java.util.zip.*;
6 import java.util.jar.*;
8 import java.lang.reflect.*;
10 import org.eclipse.jdt.core.compiler.IProblem;
11 import org.eclipse.jdt.internal.compiler.ClassFile;
12 import org.eclipse.jdt.internal.compiler.CompilationResult;
13 //import org.eclipse.jdt.internal.compiler.Compiler;
14 import org.eclipse.jdt.internal.compiler.DefaultErrorHandlingPolicies;
15 import org.eclipse.jdt.internal.compiler.ICompilerRequestor;
16 import org.eclipse.jdt.internal.compiler.IErrorHandlingPolicy;
17 import org.eclipse.jdt.internal.compiler.IProblemFactory;
18 import org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader;
19 import org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException;
20 import org.eclipse.jdt.internal.compiler.env.*;
21 import org.eclipse.jdt.internal.compiler.impl.*;
22 import org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory;
24 // FEATURE: add build dependencies like make (grab some Java dependency-checker code off the net?)
26 public class Compiler {
27 // Static Entry Point /////////////////////////////////////////////////////
29 public static void main(String[] args) throws IOException {
30 boolean verbose = false, veryverbose = false, warnings = true;
31 List srcdir = new ArrayList();
32 String source = null, target = null, blddir = null, mainclass = null;
33 boolean buildjar = false;
35 if (args.length == 0) args = new String[] { "--help" };
36 for (int i=0; i < args.length; i++) {
37 if (args[i].charAt(0) == '-') {
38 if (args[i].length() == 1) {
39 System.out.println("Illegal switch: -"); return; }
40 switch (args[i].charAt(1)) {
42 if (args[i].equals("--help")) printHelp();
43 else System.out.println("Unknown switch: -");
46 if (i == args.length - 1) {
47 System.out.println("Missing parameter: "+args[i]); return; }
48 if (blddir != null) { System.out.println("cannot specify both -d and -j"); return; }
52 if (i == args.length - 1) {
53 System.out.println("Missing parameter: "+args[i]); return; }
54 if (blddir != null) { System.out.println("cannot specify both -d and -j"); return; }
59 if (i == args.length - 1) {
60 System.out.println("Missing parameter: "+args[i]); return; }
61 mainclass = args[++i];
64 if (i == args.length - 1) {
65 System.out.println("Missing parameter: "+args[i]); return; }
69 if (i == args.length - 1) {
70 System.out.println("Missing parameter: "+args[i]); return; }
74 if (i == args.length - 1) {
75 System.out.println("Missing parameter: "+args[i]); return; }
88 } else srcdir.add(args[i]);
91 Compiler c = new Compiler();
93 if (buildjar) c.setBuildJar(blddir);
94 else c.setBuildDir(blddir);
96 if (source != null) c.setSource(source);
97 if (target != null) c.setTarget(target);
98 if (mainclass != null) c.setMainClass(mainclass);
100 String[] s = new String[srcdir.size()];
104 c.setVerbose(verbose);
105 c.setWarnings(warnings);
106 c.setVeryVerbose(veryverbose);
109 private static void printHelp() {
110 System.out.println("Usage java -cp ... org.ibex.tool.Compiler [options] <source dir> ...");
111 System.out.println("Options:");
112 System.out.println(" -d <directory> Directory to put generated class files in");
113 System.out.println(" -j <jarfile> Jar file to put generated class files in");
114 System.out.println(" -m <class> Main-Class for jar file.");
115 System.out.println(" -s <release> Compile with specified source compatibility.");
116 System.out.println(" -t <release> Compile with specified class file compatibility.");
117 System.out.println(" -v Verbose output.");
118 System.out.println(" -V Very Verbose output.");
119 System.out.println(" -h or --help Print this message.");
120 System.out.println("");
124 // Compiler Interface /////////////////////////////////////////////////////
126 private ClassLoader loader = ClassLoader.getSystemClassLoader();
127 private Map loaded = new HashMap();
128 private PrintWriter out = new PrintWriter(System.out);
129 private Preprocessor preprocessor;
131 private Source[] sources;
133 private File builddir = null;
134 private boolean buildzip = false;
135 private ZipOutputStream jarfile = null;
136 private String mainclass = null;
138 private String[] sourcedirs = new String[0];
140 private PrintWriter warn;
141 private boolean hasErrors;
142 private boolean verbose = false;
143 private boolean veryverbose = false;
144 private boolean warnings = true;
147 List defs = Collections.EMPTY_LIST;
149 String define = System.getProperty("org.ibex.tool.preprocessor.define");
150 if (define != null) {
151 defs = new ArrayList();
152 StringTokenizer st = new StringTokenizer(define.toUpperCase(), ",");
153 while (st.hasMoreTokens()) defs.add(st.nextToken().trim());
156 preprocessor = new Preprocessor(null, null, defs);
159 public void setMainClass(String mainclass) { this.mainclass = mainclass; }
160 public void setBuildJar(String dir) throws IOException {
161 builddir = new File(dir == null ? "." : dir);
164 public void setBuildDir(String dir) throws IOException {
165 builddir = new File(dir == null ? "." : dir);
168 public void setSourceDirs(String[] dir) { sourcedirs = dir; }
170 /** Pass CompilerOptions.VERSION_1_*. A String of form "1.1", ".2", etc. */
171 public void setSource(String v) {
172 if (v.equals("1.1")) settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_1);
173 else if (v.equals("1.2")) settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_2);
174 else if (v.equals("1.3")) settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_3);
175 else if (v.equals("1.4")) settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_4);
176 else if (v.equals("1.5")) settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_5);
177 else throw new RuntimeException("I have no idea what Java " + v + " is. Ask David Crawshaw.");
180 /** Pass CompilerOptions.VERSION_1_*. A String of form "1.1", ".2", etc. */
181 public void setTarget(String v) {
182 if (v.equals("1.1")) settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_1);
183 else if (v.equals("1.2")) settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_2);
184 else if (v.equals("1.3")) settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_3);
185 else if (v.equals("1.4")) settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_4);
186 else if (v.equals("1.5")) settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_5);
187 else throw new RuntimeException("I have no idea what Java " + v + " is. Ask David Crawshaw.");
190 public void setVerbose(boolean v) { verbose = v; }
191 public void setVeryVerbose(boolean v) { veryverbose = v; }
192 public void setWarnings(boolean w) { warnings = w; }
194 public void compile() throws IOException {
195 List s = new ArrayList();
198 Manifest m = new Manifest();
199 m.getMainAttributes().putValue("Manifest-Version", "1.0");
200 if (mainclass != null) m.getMainAttributes().putValue("Main-Class", mainclass);
201 jarfile = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(builddir)), m);
203 for (int i=0; i < sourcedirs.length; i++) {
204 File src = new File(sourcedirs[i]);
206 if (veryverbose) System.out.println("source directory not found: "+sourcedirs[i]);
209 filterSources(s, src, new char[0][], sourcedirs[i]);
212 if (veryverbose) System.out.println("working with "+s.size() +" sources");
213 sources = new Source[s.size()]; s.toArray(sources);
214 ICompilationUnit[] units = new ICompilationUnit[s.size()];
215 int u = 0; for (int i=0; i < sources.length; i++)
216 if (sources[i].compiled == null) units[u++] = sources[i].unit;
217 if (u != units.length) {
218 ICompilationUnit[] newu = new ICompilationUnit[u];
219 System.arraycopy(units, 0, newu, 0, u);
225 StringWriter sw = new StringWriter();
226 StringBuffer w = sw.getBuffer();
227 warn = new PrintWriter(sw);
229 org.eclipse.jdt.internal.compiler.Compiler jdt =
230 new org.eclipse.jdt.internal.compiler.Compiler(
231 env, policy, settings, results, problems);
234 if (warnings && !hasErrors) { out.write(w.toString()); out.flush(); }
237 if (jarfile != null) jarfile.close();
238 } catch (Exception e) {
241 if (verbose) System.out.print(clearing + " \r");
244 private final FilenameFilter filterSrcs = new FilenameFilter() {
245 public boolean accept(File dir, String name) { return name.endsWith(".java"); }
247 private final FileFilter filterDirs = new FileFilter() {
248 public boolean accept(File path) { return path.isDirectory(); }
251 private void filterSources(List s, File dir, char[][] pack, String srcdir) {
252 List bclasses = new ArrayList();
253 File bdir = new File(builddir, str(pack, File.separatorChar));
255 // add the java files in this directory
256 File[] ja = dir.listFiles(filterSrcs);
257 for (int i=0; i < ja.length; i++) {
258 char[] n = name(classname(ja[i].getName()));
259 Source src = new Source(ja[i], n, pack, srcdir);
261 // skip the file if the build version is newer than the source
262 String bclass = new String(n);
263 File bfile = new File(bdir, bclass + ".class");
264 if (bfile.lastModified() > ja[i].lastModified()) {
265 src.compiled = bytes(bfile);
266 bclasses.add(bclass);
272 // process the inner classes of any binary files
273 for (int i=0; i < bclasses.size(); i++) {
274 final String bc = (String)bclasses.get(i);
275 final FilenameFilter f = new FilenameFilter() {
276 public boolean accept(File dir, String name) {
277 return name.length() > bc.length() && name.startsWith(bc) &&
278 name.charAt(bc.length()) == '$' && name.endsWith(".class");
281 File[] bfile = bdir.listFiles(f);
282 for (int j=0; j < bfile.length; j++) {
283 Source src = new Source(bfile[j],
284 name(classname(bfile[j].getName())), pack, srcdir);
285 src.compiled = bytes(bfile[j]);
290 // add the subdirectories as packages
291 File[] d = dir.listFiles(filterDirs);
292 for (int i=0; i < d.length; i++) {
293 char[][] newpack = new char[pack.length + 1][];
294 for (int j=0; j < pack.length; j++) newpack[j] = pack[j];
295 newpack[pack.length] = d[i].getName().toCharArray();
296 filterSources(s, d[i], newpack, srcdir);
301 /** Represents a file to be compiled. */
304 char[] n; char[][] p;
306 char[] processed = null;
307 byte[] compiled = null;
308 ClassFileReader reader = null;
310 final ICompilationUnit unit = new ICompilationUnit() {
311 public char[] getMainTypeName() { return n; }
312 public char[][] getPackageName() { return p; }
313 public char[] getFileName() { return fileName; }
314 public char[] getContents() {
315 if (processed != null) return processed;
318 Reader r = new InputStreamReader(new BufferedInputStream(
319 new FileInputStream(orig)));
320 StringWriter w = new StringWriter();
323 synchronized (preprocessor) {
324 preprocessor.setReader(r);
325 preprocessor.setWriter(w);
326 err = preprocessor.process();
329 if (err.size() > 0) {
330 for (int i=0; i < err.size(); i++) {
331 Preprocessor.Warning warn = (Preprocessor.Warning)err.get(i);
332 out.print(getFileName());
334 out.print(warn.getLine());
336 out.print(warn instanceof Preprocessor.Error ?
337 " error: " : " warning: ");
338 out.println(warn.getMessage());
343 processed = w.toString().toCharArray();
344 } catch (IOException e) {
345 System.out.println("IOException: "+e); // FIXME
353 private Source(File o, char[] n, char[][] p, String srcdir) {
354 orig = o; this.n = n; this.p = p;
355 String file = srcdir;
356 file += File.separatorChar + str(p, File.separatorChar);
357 file += File.separatorChar + new String(n) + ".java";
358 fileName = file.toCharArray();
362 // Compiler Parameters ////////////////////////////////////////////////////
364 // FEATURE: may be able to use this to block access to APIs generated for stack objects
365 final AccessRestriction access = new AccessRestriction(null, null, null, null);
367 /** Used by compiler to resolve classes. */
368 final INameEnvironment env = new INameEnvironment() {
369 public NameEnvironmentAnswer findType(char[][] c) { return findType(name(c), pack(c)); }
370 public NameEnvironmentAnswer findType(char[] n, char[][] p) {
371 if (veryverbose) System.out.print("findType: "+ str(p, '.') + "."+new String(n));
374 String classname = new String(n);
375 Class c = Class.forName(str(p, '.') + '.' + classname);
376 if (veryverbose) System.out.println(" found in classloader: "+ c);
377 IBinaryType b = (IBinaryType)loaded.get(c);
378 if (b == null) loaded.put(c, b = new ClassFileReader(
379 bytes(c), (str(p, '/') + '/' + classname).toCharArray()));
380 return new NameEnvironmentAnswer(b, access);
381 } catch (ClassNotFoundException e) {
382 } catch (ClassFormatException e) {
384 throw new Error("ClassFormatException reading system class: " +
385 str(p, '.')+new String(n));
388 // cut out searches for java.* packages in sources list
389 if (p.length > 0 && eq(p[0], "java".toCharArray())) {
390 if (veryverbose) System.out.println(" not found, unknown java.*");
395 for (int i=0; i < sources.length; i++) {
396 Source s = sources[i];
397 if (eq(n, s.n) && eq(p, s.p)) {
398 if (s.reader != null) {
399 if (veryverbose) System.out.println(" found reader");
400 return new NameEnvironmentAnswer(s.reader, access);
402 if (s.compiled != null) {
403 if (veryverbose) System.out.println(" found compiled, new reader");
404 s.reader = new ClassFileReader(s.compiled,
405 s.orig.getName().toCharArray());
406 return new NameEnvironmentAnswer(s.reader, access);
408 if (veryverbose) System.out.println(" found unit");
409 return new NameEnvironmentAnswer(sources[i].unit, access);
412 } catch (ClassFormatException e) {
413 System.out.println("Unexpected ClassFormatException"); // FIXME
414 e.printStackTrace(); return null;
416 if (veryverbose) System.out.println(" not found");
419 public boolean isPackage(char[][] parent, char[] name) {
420 if (veryverbose) System.out.println("isPackage: "+ str(parent, '.') + "."+new String(name));
421 String parentName = str(parent, '/');
422 for (int i=0; i < sources.length; i++) {
423 if (eq(name, sources[i].n) && eq(parent, sources[i].p)) return false;
424 if (eq(pack(sources[i].p), parent) && eq(name(sources[i].p), name)) return true;
427 loader.getResource(parentName + ".class") == null &&
428 loader.getResource(parentName + '/' + new String(name) + ".class") == null;
430 public void cleanup() {}
433 /** Used by compiler to decide what do with problems.. */
434 private final IErrorHandlingPolicy policy =
435 DefaultErrorHandlingPolicies.proceedWithAllProblems();
437 /** Used by compiler for general options. */
438 private final Map settings = new HashMap();
440 settings.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE);
441 settings.put(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE);
442 settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_5);
443 settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_1);
446 /** Used by compiler for processing compiled classes and their errors. */
447 private final ICompilerRequestor results = new ICompilerRequestor() {
448 public void acceptResult(CompilationResult result) {
449 if (veryverbose) System.out.println("got result: "+result);
450 if (result.hasProblems()) {
452 IProblem[] p = result.getProblems();
454 for (int i=0; i < p.length; i++) {
455 if (p[i].isError()) { o = out; err = true; }
458 o.print(p[i].getOriginatingFileName());
460 o.print(p[i].getSourceLineNumber());
462 o.print(p[i].isError() ? " error: " : " warning: ");
463 o.println(p[i].getMessage());
466 if (err) { hasErrors = true; return; }
469 ClassFile[] c = result.getClassFiles();
470 for (int i=0; i < c.length; i++) {
472 char[][] name = c[i].getCompoundName();
477 while (pct.length() < 2) pct = " " + pct;
478 pct = "(" + pct + "%) ";
480 String printme = " writing: " + pct + str(pack(name),'.') + "." + new String(name(name));
481 if (clearing.length() < printme.length()) clearing = "";
482 else clearing = clearing.substring(printme.length());
483 System.out.print(printme + clearing + "\r");
484 for(clearing = ""; clearing.length() < printme.length() + 5; clearing += " ");
488 jarfile.putNextEntry(new ZipEntry(str(pack(name), '/') + "/" + new String(name(name)) + ".class"));
489 jarfile.write(c[i].getBytes());
490 } catch (java.util.zip.ZipException ze) {
491 // HACK: horrendous hack
492 if (ze.getMessage().indexOf("duplicate entry") != -1) {
493 //System.out.println("compiler emitted class twice: " + new String(name(name)));
499 // build package path to new class file
500 File path = new File(builddir, str(pack(name), '/'));
501 if (!path.exists()) path.mkdirs();
502 // write new class file
503 path = new File(path, new String(name(name)) + ".class");
504 OutputStream o = new BufferedOutputStream(new FileOutputStream(path));
505 o.write(c[i].getBytes());
508 } catch (IOException e) {
509 System.out.println("IOException writing class"); // FIXME
517 String clearing = "";
519 /** Problem creater for compiler. */
520 private final IProblemFactory problems = new DefaultProblemFactory();
523 // Helper Functiosn ///////////////////////////////////////////////////////
525 /** Convert source file path into class name block.
526 * eg. in: java/lang/String.java -> { {java} {lang} {String} } */
527 private static char[][] classname(String name) {
528 String delim = name.indexOf('/') == -1 ? "." : "/";
530 if (name.endsWith(".java")) name = name.substring(0, name.length() - 5);
531 if (name.endsWith(".class")) name = name.substring(0, name.length() - 6);
532 if (name.startsWith(delim)) name = name.substring(1);
534 StringTokenizer st = new StringTokenizer(name, delim);
535 char[][] n = new char[st.countTokens()][];
536 for (int i=0; st.hasMoreTokens(); i++) n[i] = st.nextToken().toCharArray();
540 /** Convert class name into a String. */
541 private static String str(char[][] name, char delim) {
542 StringBuffer b = new StringBuffer();
543 for (int i=0; name != null && i < name.length; i++) {
544 if (name[i] == null || name[i].length == 0) continue;
545 if (i > 0) b.append(delim);
551 /** Returns the package component of a class name.
552 * Effectively returns char[length - 1][]. */
553 private static char[][] pack(char[][] c) {
554 char[][] p = new char[c.length - 1][];
555 for (int i=0; i < p.length; i++) p[i] = c[i];
559 /** Returns the direct-name component of a class name.
560 * eg. String from java.lang.String */
561 private static char[] name(char[][] c) { return c[c.length - 1]; }
563 /** Returns true of contents of both char arrays are equal. */
564 private static boolean eq(char[][] c1, char[][] c2) {
565 if (c1 == null || c2 == null) return c1 == c2;
566 if (c1.length != c2.length) return false;
567 for (int i=0; i < c1.length; i++) if (!eq(c1[i], c2[i])) return false;
571 /** Returns true of contents of both char arrays are equal. */
572 private static boolean eq(char[] c1, char[] c2) {
573 if (c1 == null || c2 == null) return c1 == c2;
574 if (c1.length != c2.length) return false;
575 for (int i=0; i < c1.length; i++) if (c1[i] != c2[i]) return false;
579 /** Returns class name as per VM Spec 4.2. eg. java/lang/String */
580 private static char[] name(Class c) {
581 return c == null ? null : c.getName().replace('.', '/').toCharArray();
584 /** Returns the type name of a class as per VM Spec 4.3.2. */
585 private static char[] typeName(Class p) {
586 StringBuffer sb = new StringBuffer();
588 return sb.toString().toCharArray();
591 /** Returns the type name of a class as per VM Spec 4.3.2.
592 * eg. int -> I, String -> Ljava/lang/String; */
593 private static void typeName(Class p, StringBuffer sb) {
594 String name = p.getName();
595 switch (name.charAt(0)) {
596 case 'B': case 'C': case 'D': case 'F': case 'I':
597 case 'J': case 'S': case 'Z': case 'V': case '[':
598 sb.append(name(p)); break;
600 case 'b': if (name.equals("boolean")) { sb.append('Z'); break; }
601 if (name.equals("byte")) { sb.append('B'); break; }
602 case 'c': if (name.equals("char")) { sb.append('C'); break; }
603 case 'd': if (name.equals("double")) { sb.append('D'); break; }
604 case 'f': if (name.equals("float")) { sb.append('F'); break; }
605 case 'i': if (name.equals("int")) { sb.append('I'); break; }
606 case 'l': if (name.equals("long")) { sb.append('J'); break; }
607 case 's': if (name.equals("short")) { sb.append('S'); break; }
608 case 'v': if (name.equals("void")) { sb.append('V'); break; }
610 sb.append('L'); sb.append(name(p)); sb.append(';');
614 /** Returns the descriptor of a method per VM Spec 4.3.3.
615 * eg. int get(String n, boolean b) -> (Ljava/lang/String;B)I */
616 private static char[] descriptor(Class[] p, Class r) {
617 StringBuffer sb = new StringBuffer();
619 if (p != null) for (int i=0; i < p.length; i++) typeName(p[i], sb);
621 if (r != null) typeName(r, sb);
622 return sb.toString().toCharArray();
625 private static byte[] bytes(Class c) {
626 return bytes(c.getResourceAsStream('/' + c.getName().replace('.', '/') + ".class"));
628 private static byte[] bytes(File bfile) {
629 try { return bytes(new FileInputStream(bfile)); }
630 catch (FileNotFoundException e) { throw new Error("FileNotFoundException reading bytes: "+e); }
632 private static byte[] bytes(InputStream bin) {
633 byte[] bytes = new byte[2 * 1024];
636 while ((in = bin.read(bytes, pos, bytes.length - pos)) != -1) {
638 if (pos == bytes.length) {
639 byte[] newbytes= new byte[pos * 2];
640 System.arraycopy(bytes, 0, newbytes, 0, pos);
645 } catch (IOException e) {
647 throw new Error("IOException reading class file: "+e);
650 if (pos != bytes.length) {
651 byte[] newbytes= new byte[pos * 2];
652 System.arraycopy(bytes, 0, newbytes, 0, pos);