1 // Copyright 2000-2005 the Contributors, as shown in the revision logs.
2 // Licensed under the Apache Public Source License 2.0 ("the License").
3 // You may not use this file except in compliance with the License.
9 import java.util.zip.*;
10 import java.util.jar.*;
12 import java.lang.reflect.*;
14 import org.eclipse.jdt.core.compiler.IProblem;
15 import org.eclipse.jdt.internal.compiler.ClassFile;
16 import org.eclipse.jdt.internal.compiler.CompilationResult;
17 //import org.eclipse.jdt.internal.compiler.Compiler;
18 import org.eclipse.jdt.internal.compiler.DefaultErrorHandlingPolicies;
19 import org.eclipse.jdt.internal.compiler.ICompilerRequestor;
20 import org.eclipse.jdt.internal.compiler.IErrorHandlingPolicy;
21 import org.eclipse.jdt.internal.compiler.IProblemFactory;
22 import org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader;
23 import org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException;
24 import org.eclipse.jdt.internal.compiler.env.*;
25 import org.eclipse.jdt.internal.compiler.impl.*;
26 import org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory;
28 // FEATURE: add build dependencies like make (grab some Java dependency-checker code off the net?)
30 public class Compiler {
31 // Static Entry Point /////////////////////////////////////////////////////
33 public static void main(String[] args) throws IOException {
34 boolean verbose = false, veryverbose = false, warnings = true;
35 List srcdir = new ArrayList();
36 String source = null, target = null, blddir = null, mainclass = null;
37 boolean buildjar = false;
39 if (args.length == 0) args = new String[] { "--help" };
40 for (int i=0; i < args.length; i++) {
41 if (args[i].charAt(0) == '-') {
42 if (args[i].length() == 1) {
43 System.out.println("Illegal switch: -"); return; }
44 switch (args[i].charAt(1)) {
46 if (args[i].equals("--help")) printHelp();
47 else System.out.println("Unknown switch: -");
50 if (i == args.length - 1) {
51 System.out.println("Missing parameter: "+args[i]); return; }
52 if (blddir != null) { System.out.println("cannot specify both -d and -j"); return; }
56 if (i == args.length - 1) {
57 System.out.println("Missing parameter: "+args[i]); return; }
58 if (blddir != null) { System.out.println("cannot specify both -d and -j"); return; }
63 if (i == args.length - 1) {
64 System.out.println("Missing parameter: "+args[i]); return; }
65 mainclass = args[++i];
68 if (i == args.length - 1) {
69 System.out.println("Missing parameter: "+args[i]); return; }
73 if (i == args.length - 1) {
74 System.out.println("Missing parameter: "+args[i]); return; }
78 if (i == args.length - 1) {
79 System.out.println("Missing parameter: "+args[i]); return; }
92 } else srcdir.add(args[i]);
95 Compiler c = new Compiler();
97 if (buildjar) c.setBuildJar(blddir);
98 else c.setBuildDir(blddir);
100 if (source != null) c.setSource(source);
101 if (target != null) c.setTarget(target);
102 if (mainclass != null) c.setMainClass(mainclass);
104 String[] s = new String[srcdir.size()];
108 c.setVerbose(verbose);
109 c.setWarnings(warnings);
110 c.setVeryVerbose(veryverbose);
111 boolean hasErrors = c.compile();
112 if (hasErrors) Runtime.getRuntime().exit(-1);
113 Runtime.getRuntime().exit(0);
115 private static void printHelp() {
116 System.out.println("Usage java -cp ... org.ibex.tool.Compiler [options] <source dir> ...");
117 System.out.println("Options:");
118 System.out.println(" -d <directory> Directory to put generated class files in");
119 System.out.println(" -j <jarfile> Jar file to put generated class files in");
120 System.out.println(" -m <class> Main-Class for jar file.");
121 System.out.println(" -s <release> Compile with specified source compatibility.");
122 System.out.println(" -t <release> Compile with specified class file compatibility.");
123 System.out.println(" -v Verbose output.");
124 System.out.println(" -V Very Verbose output.");
125 System.out.println(" -h or --help Print this message.");
126 System.out.println("");
130 // Compiler Interface /////////////////////////////////////////////////////
132 private ClassLoader loader = ClassLoader.getSystemClassLoader();
133 private Map loaded = new HashMap();
134 private PrintWriter out = new PrintWriter(System.out);
135 private Preprocessor preprocessor;
137 private Source[] sources;
139 private File builddir = null;
140 private boolean buildzip = false;
141 private ZipOutputStream jarfile = null;
142 private String mainclass = null;
144 private String[] sourcedirs = new String[0];
146 private PrintWriter warn;
147 private boolean hasErrors;
148 private boolean verbose = false;
149 private boolean veryverbose = false;
150 private boolean warnings = true;
153 List defs = Collections.EMPTY_LIST;
155 String define = System.getProperty("org.ibex.tool.preprocessor.define");
156 if (define != null) {
157 defs = new ArrayList();
158 StringTokenizer st = new StringTokenizer(define.toUpperCase(), ",");
159 while (st.hasMoreTokens()) defs.add(st.nextToken().trim());
162 preprocessor = new Preprocessor(null, null, defs);
165 public void setMainClass(String mainclass) { this.mainclass = mainclass; }
166 public void setBuildJar(String dir) throws IOException {
167 builddir = new File(dir == null ? "." : dir);
170 public void setBuildDir(String dir) throws IOException {
171 builddir = new File(dir == null ? "." : dir);
174 public void setSourceDirs(String[] dir) { sourcedirs = dir; }
176 /** Pass CompilerOptions.VERSION_1_*. A String of form "1.1", ".2", etc. */
177 public void setSource(String v) {
178 if (v.equals("1.1")) settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_1);
179 else if (v.equals("1.2")) settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_2);
180 else if (v.equals("1.3")) settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_3);
181 else if (v.equals("1.4")) settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_4);
182 else if (v.equals("1.5")) settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_5);
183 else throw new RuntimeException("I have no idea what Java " + v + " is. Ask David Crawshaw.");
186 /** Pass CompilerOptions.VERSION_1_*. A String of form "1.1", ".2", etc. */
187 public void setTarget(String v) {
188 if (v.equals("1.1")) settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_1);
189 else if (v.equals("1.2")) settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_2);
190 else if (v.equals("1.3")) settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_3);
191 else if (v.equals("1.4")) settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_4);
192 else if (v.equals("1.5")) settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_5);
193 else throw new RuntimeException("I have no idea what Java " + v + " is. Ask David Crawshaw.");
196 public void setVerbose(boolean v) { verbose = v; }
197 public void setVeryVerbose(boolean v) { veryverbose = v; }
198 public void setWarnings(boolean w) { warnings = w; }
200 public boolean compile() throws IOException {
201 List s = new ArrayList();
204 Manifest m = new Manifest();
205 m.getMainAttributes().putValue("Manifest-Version", "1.0");
206 if (mainclass != null) m.getMainAttributes().putValue("Main-Class", mainclass);
207 jarfile = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(builddir)), m);
209 for (int i=0; i < sourcedirs.length; i++) {
210 File src = new File(sourcedirs[i]);
212 if (veryverbose) System.out.println("source directory not found: "+sourcedirs[i]);
215 filterSources(s, src, new char[0][], sourcedirs[i]);
218 if (veryverbose) System.out.println("working with "+s.size() +" sources");
219 sources = new Source[s.size()]; s.toArray(sources);
220 ICompilationUnit[] units = new ICompilationUnit[s.size()];
221 int u = 0; for (int i=0; i < sources.length; i++)
222 if (sources[i].compiled == null) units[u++] = sources[i].unit;
223 if (u != units.length) {
224 ICompilationUnit[] newu = new ICompilationUnit[u];
225 System.arraycopy(units, 0, newu, 0, u);
231 StringWriter sw = new StringWriter();
232 StringBuffer w = sw.getBuffer();
233 warn = new PrintWriter(sw);
235 org.eclipse.jdt.internal.compiler.Compiler jdt =
236 new org.eclipse.jdt.internal.compiler.Compiler(
237 env, policy, settings, results, problems);
240 if (warnings && !hasErrors) { out.write(w.toString()); out.flush(); }
243 if (jarfile != null) jarfile.close();
244 } catch (Exception e) {
247 if (verbose) System.out.print(clearing + " \r");
251 private final FilenameFilter filterSrcs = new FilenameFilter() {
252 public boolean accept(File dir, String name) { return name.endsWith(".java"); }
254 private final FileFilter filterDirs = new FileFilter() {
255 public boolean accept(File path) { return path.isDirectory(); }
258 private void filterSources(List s, File dir, char[][] pack, String srcdir) {
259 List bclasses = new ArrayList();
260 File bdir = new File(builddir, str(pack, File.separatorChar));
262 // add the java files in this directory
263 File[] ja = dir.listFiles(filterSrcs);
264 for (int i=0; i < ja.length; i++) {
265 char[] n = name(classname(ja[i].getName()));
266 Source src = new Source(ja[i], n, pack, srcdir);
268 // skip the file if the build version is newer than the source
269 String bclass = new String(n);
270 File bfile = new File(bdir, bclass + ".class");
271 if (bfile.lastModified() > ja[i].lastModified()) {
272 src.compiled = bytes(bfile);
273 bclasses.add(bclass);
279 // process the inner classes of any binary files
280 for (int i=0; i < bclasses.size(); i++) {
281 final String bc = (String)bclasses.get(i);
282 final FilenameFilter f = new FilenameFilter() {
283 public boolean accept(File dir, String name) {
284 return name.length() > bc.length() && name.startsWith(bc) &&
285 name.charAt(bc.length()) == '$' && name.endsWith(".class");
288 File[] bfile = bdir.listFiles(f);
289 for (int j=0; j < bfile.length; j++) {
290 Source src = new Source(bfile[j],
291 name(classname(bfile[j].getName())), pack, srcdir);
292 src.compiled = bytes(bfile[j]);
297 // add the subdirectories as packages
298 File[] d = dir.listFiles(filterDirs);
299 for (int i=0; i < d.length; i++) {
300 char[][] newpack = new char[pack.length + 1][];
301 for (int j=0; j < pack.length; j++) newpack[j] = pack[j];
302 newpack[pack.length] = d[i].getName().toCharArray();
303 filterSources(s, d[i], newpack, srcdir);
308 /** Represents a file to be compiled. */
311 char[] n; char[][] p;
313 char[] processed = null;
314 byte[] compiled = null;
315 ClassFileReader reader = null;
317 final ICompilationUnit unit = new ICompilationUnit() {
318 public char[] getMainTypeName() { return n; }
319 public char[][] getPackageName() { return p; }
320 public char[] getFileName() { return fileName; }
321 public char[] getContents() {
322 if (processed != null) return processed;
325 Reader r = new InputStreamReader(new BufferedInputStream(
326 new FileInputStream(orig)));
327 StringWriter w = new StringWriter();
330 synchronized (preprocessor) {
331 preprocessor.setReader(r);
332 preprocessor.setWriter(w);
333 err = preprocessor.process();
336 if (err.size() > 0) {
337 for (int i=0; i < err.size(); i++) {
338 Preprocessor.Warning warn = (Preprocessor.Warning)err.get(i);
339 out.print(getFileName());
341 out.print(warn.getLine());
343 out.print(warn instanceof Preprocessor.Error ?
344 " error: " : " warning: ");
345 out.println(warn.getMessage());
350 processed = w.toString().toCharArray();
351 } catch (IOException e) {
352 System.out.println("IOException: "+e); // FIXME
360 private Source(File o, char[] n, char[][] p, String srcdir) {
361 orig = o; this.n = n; this.p = p;
362 String file = srcdir;
363 file += File.separatorChar + str(p, File.separatorChar);
364 file += File.separatorChar + new String(n) + ".java";
365 fileName = file.toCharArray();
369 // Compiler Parameters ////////////////////////////////////////////////////
371 // FEATURE: may be able to use this to block access to APIs generated for stack objects
372 final AccessRestriction access = null;
374 /** Used by compiler to resolve classes. */
375 final INameEnvironment env = new INameEnvironment() {
376 public NameEnvironmentAnswer findType(char[][] c) { return findType(name(c), pack(c)); }
377 public NameEnvironmentAnswer findType(char[] n, char[][] p) {
378 if (veryverbose) System.out.print("findType: "+ str(p, '.') + "."+new String(n));
381 String classname = new String(n);
382 Class c = Class.forName(str(p, '.') + '.' + classname);
383 if (veryverbose) System.out.println(" found in classloader: "+ c);
384 IBinaryType b = (IBinaryType)loaded.get(c);
385 if (b == null) loaded.put(c, b = new ClassFileReader(
386 bytes(c), (str(p, '/') + '/' + classname).toCharArray()));
387 return new NameEnvironmentAnswer(b, access);
388 } catch (ClassNotFoundException e) {
389 } catch (LinkageError e) {
390 } catch (ClassFormatException e) {
392 throw new Error("ClassFormatException reading system class: " +
393 str(p, '.')+new String(n));
396 // cut out searches for java.* packages in sources list
397 if (p.length > 0 && eq(p[0], "java".toCharArray())) {
398 if (veryverbose) System.out.println(" not found, unknown java.*");
403 for (int i=0; i < sources.length; i++) {
404 Source s = sources[i];
405 if (eq(n, s.n) && eq(p, s.p)) {
406 if (s.reader != null) {
407 if (veryverbose) System.out.println(" found reader");
408 return new NameEnvironmentAnswer(s.reader, access);
410 if (s.compiled != null) {
411 if (veryverbose) System.out.println(" found compiled, new reader");
412 s.reader = new ClassFileReader(s.compiled,
413 s.orig.getName().toCharArray());
414 return new NameEnvironmentAnswer(s.reader, access);
416 if (veryverbose) System.out.println(" found unit");
417 return new NameEnvironmentAnswer(sources[i].unit, access);
420 } catch (ClassFormatException e) {
422 throw new Error("unexpected ClassFormatException resolving compiled class: "+e);
424 if (veryverbose) System.out.println(" not found");
427 public boolean isPackage(char[][] parent, char[] name) {
428 if (veryverbose) System.out.println("isPackage: "+ str(parent, '.') + "."+new String(name));
429 String parentName = str(parent, '/');
430 for (int i=0; i < sources.length; i++) {
431 if (eq(name, sources[i].n) && eq(parent, sources[i].p)) return false;
432 if (eq(pack(sources[i].p), parent) && eq(name(sources[i].p), name)) return true;
435 loader.getResource(parentName + ".class") == null &&
436 loader.getResource(parentName + '/' + new String(name) + ".class") == null;
438 public void cleanup() {}
441 /** Used by compiler to decide what do with problems.. */
442 private final IErrorHandlingPolicy policy =
443 DefaultErrorHandlingPolicies.proceedWithAllProblems();
445 /** Used by compiler for general options. */
446 private final Map settings = new HashMap();
448 settings.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE);
449 settings.put(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE);
450 settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_5);
451 settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_1);
454 /** Used by compiler for processing compiled classes and their errors. */
455 private final ICompilerRequestor results = new ICompilerRequestor() {
456 public void acceptResult(CompilationResult result) {
457 if (veryverbose) System.out.println("got result: "+result);
458 if (result.hasProblems()) {
460 IProblem[] p = result.getProblems();
462 for (int i=0; i < p.length; i++) {
463 if (p[i].isError()) { o = out; err = true; }
466 o.print(p[i].getOriginatingFileName());
468 o.print(p[i].getSourceLineNumber());
470 o.print(p[i].isError() ? " error: " : " warning: ");
471 o.println(p[i].getMessage());
474 if (err) { hasErrors = true; return; }
477 ClassFile[] c = result.getClassFiles();
478 for (int i=0; i < c.length; i++) {
480 char[][] name = c[i].getCompoundName();
485 while (pct.length() < 2) pct = " " + pct;
486 pct = "(" + pct + "%) ";
488 String printme = " writing: " + pct + str(pack(name),'.') + "." + new String(name(name));
489 if (clearing.length() < printme.length()) clearing = "";
490 else clearing = clearing.substring(printme.length());
491 System.out.print(printme + clearing + "\r");
492 for(clearing = ""; clearing.length() < printme.length() + 5; clearing += " ");
496 jarfile.putNextEntry(new ZipEntry(str(pack(name), '/') + "/" + new String(name(name)) + ".class"));
497 jarfile.write(c[i].getBytes());
498 } catch (java.util.zip.ZipException ze) {
499 // HACK: horrendous hack
500 if (ze.getMessage().indexOf("duplicate entry") != -1) {
501 //System.out.println("compiler emitted class twice: " + new String(name(name)));
507 // build package path to new class file
508 File path = new File(builddir, str(pack(name), '/'));
509 if (!path.exists()) path.mkdirs();
510 // write new class file
511 path = new File(path, new String(name(name)) + ".class");
512 OutputStream o = new BufferedOutputStream(new FileOutputStream(path));
513 o.write(c[i].getBytes());
516 } catch (IOException e) {
517 System.out.println("IOException writing class"); // FIXME
525 String clearing = "";
527 /** Problem creater for compiler. */
528 private final IProblemFactory problems = new DefaultProblemFactory();
531 // Helper Functiosn ///////////////////////////////////////////////////////
533 /** Convert source file path into class name block.
534 * eg. in: java/lang/String.java -> { {java} {lang} {String} } */
535 private static char[][] classname(String name) {
536 String delim = name.indexOf('/') == -1 ? "." : "/";
538 if (name.endsWith(".java")) name = name.substring(0, name.length() - 5);
539 if (name.endsWith(".class")) name = name.substring(0, name.length() - 6);
540 if (name.startsWith(delim)) name = name.substring(1);
542 StringTokenizer st = new StringTokenizer(name, delim);
543 char[][] n = new char[st.countTokens()][];
544 for (int i=0; st.hasMoreTokens(); i++) n[i] = st.nextToken().toCharArray();
548 /** Convert class name into a String. */
549 private static String str(char[][] name, char delim) {
550 StringBuffer b = new StringBuffer();
551 for (int i=0; name != null && i < name.length; i++) {
552 if (name[i] == null || name[i].length == 0) continue;
553 if (i > 0) b.append(delim);
559 /** Returns the package component of a class name.
560 * Effectively returns char[length - 1][]. */
561 private static char[][] pack(char[][] c) {
562 char[][] p = new char[c.length - 1][];
563 for (int i=0; i < p.length; i++) p[i] = c[i];
567 /** Returns the direct-name component of a class name.
568 * eg. String from java.lang.String */
569 private static char[] name(char[][] c) { return c[c.length - 1]; }
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 (!eq(c1[i], c2[i])) return false;
579 /** Returns true of contents of both char arrays are equal. */
580 private static boolean eq(char[] c1, char[] c2) {
581 if (c1 == null || c2 == null) return c1 == c2;
582 if (c1.length != c2.length) return false;
583 for (int i=0; i < c1.length; i++) if (c1[i] != c2[i]) return false;
587 /** Returns class name as per VM Spec 4.2. eg. java/lang/String */
588 private static char[] name(Class c) {
589 return c == null ? null : c.getName().replace('.', '/').toCharArray();
592 /** Returns the type name of a class as per VM Spec 4.3.2. */
593 private static char[] typeName(Class p) {
594 StringBuffer sb = new StringBuffer();
596 return sb.toString().toCharArray();
599 /** Returns the type name of a class as per VM Spec 4.3.2.
600 * eg. int -> I, String -> Ljava/lang/String; */
601 private static void typeName(Class p, StringBuffer sb) {
602 String name = p.getName();
603 switch (name.charAt(0)) {
604 case 'B': case 'C': case 'D': case 'F': case 'I':
605 case 'J': case 'S': case 'Z': case 'V': case '[':
606 sb.append(name(p)); break;
608 case 'b': if (name.equals("boolean")) { sb.append('Z'); break; }
609 if (name.equals("byte")) { sb.append('B'); break; }
610 case 'c': if (name.equals("char")) { sb.append('C'); break; }
611 case 'd': if (name.equals("double")) { sb.append('D'); break; }
612 case 'f': if (name.equals("float")) { sb.append('F'); break; }
613 case 'i': if (name.equals("int")) { sb.append('I'); break; }
614 case 'l': if (name.equals("long")) { sb.append('J'); break; }
615 case 's': if (name.equals("short")) { sb.append('S'); break; }
616 case 'v': if (name.equals("void")) { sb.append('V'); break; }
618 sb.append('L'); sb.append(name(p)); sb.append(';');
622 /** Returns the descriptor of a method per VM Spec 4.3.3.
623 * eg. int get(String n, boolean b) -> (Ljava/lang/String;B)I */
624 private static char[] descriptor(Class[] p, Class r) {
625 StringBuffer sb = new StringBuffer();
627 if (p != null) for (int i=0; i < p.length; i++) typeName(p[i], sb);
629 if (r != null) typeName(r, sb);
630 return sb.toString().toCharArray();
633 private static byte[] bytes(Class c) {
634 return bytes(c.getResourceAsStream('/' + c.getName().replace('.', '/') + ".class"));
636 private static byte[] bytes(File bfile) {
637 try { return bytes(new FileInputStream(bfile)); }
638 catch (FileNotFoundException e) { throw new Error("FileNotFoundException reading bytes: "+e); }
640 private static byte[] bytes(InputStream bin) {
641 byte[] bytes = new byte[2 * 1024];
644 while ((in = bin.read(bytes, pos, bytes.length - pos)) != -1) {
646 if (pos == bytes.length) {
647 byte[] newbytes= new byte[pos * 2];
648 System.arraycopy(bytes, 0, newbytes, 0, pos);
653 } catch (IOException e) {
655 throw new Error("IOException reading class file: "+e);
658 if (pos != bytes.length) {
659 byte[] newbytes= new byte[pos * 2];
660 System.arraycopy(bytes, 0, newbytes, 0, pos);