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);
113 private static void printHelp() {
114 System.out.println("Usage java -cp ... org.ibex.tool.Compiler [options] <source dir> ...");
115 System.out.println("Options:");
116 System.out.println(" -d <directory> Directory to put generated class files in");
117 System.out.println(" -j <jarfile> Jar file to put generated class files in");
118 System.out.println(" -m <class> Main-Class for jar file.");
119 System.out.println(" -s <release> Compile with specified source compatibility.");
120 System.out.println(" -t <release> Compile with specified class file compatibility.");
121 System.out.println(" -v Verbose output.");
122 System.out.println(" -V Very Verbose output.");
123 System.out.println(" -h or --help Print this message.");
124 System.out.println("");
128 // Compiler Interface /////////////////////////////////////////////////////
130 private ClassLoader loader = ClassLoader.getSystemClassLoader();
131 private Map loaded = new HashMap();
132 private PrintWriter out = new PrintWriter(System.out);
133 private Preprocessor preprocessor;
135 private Source[] sources;
137 private File builddir = null;
138 private boolean buildzip = false;
139 private ZipOutputStream jarfile = null;
140 private String mainclass = null;
142 private String[] sourcedirs = new String[0];
144 private PrintWriter warn;
145 private boolean hasErrors;
146 private boolean verbose = false;
147 private boolean veryverbose = false;
148 private boolean warnings = true;
151 List defs = Collections.EMPTY_LIST;
153 String define = System.getProperty("org.ibex.tool.preprocessor.define");
154 if (define != null) {
155 defs = new ArrayList();
156 StringTokenizer st = new StringTokenizer(define.toUpperCase(), ",");
157 while (st.hasMoreTokens()) defs.add(st.nextToken().trim());
160 preprocessor = new Preprocessor(null, null, defs);
163 public void setMainClass(String mainclass) { this.mainclass = mainclass; }
164 public void setBuildJar(String dir) throws IOException {
165 builddir = new File(dir == null ? "." : dir);
168 public void setBuildDir(String dir) throws IOException {
169 builddir = new File(dir == null ? "." : dir);
172 public void setSourceDirs(String[] dir) { sourcedirs = dir; }
174 /** Pass CompilerOptions.VERSION_1_*. A String of form "1.1", ".2", etc. */
175 public void setSource(String v) {
176 if (v.equals("1.1")) settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_1);
177 else if (v.equals("1.2")) settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_2);
178 else if (v.equals("1.3")) settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_3);
179 else if (v.equals("1.4")) settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_4);
180 else if (v.equals("1.5")) settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_5);
181 else throw new RuntimeException("I have no idea what Java " + v + " is. Ask David Crawshaw.");
184 /** Pass CompilerOptions.VERSION_1_*. A String of form "1.1", ".2", etc. */
185 public void setTarget(String v) {
186 if (v.equals("1.1")) settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_1);
187 else if (v.equals("1.2")) settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_2);
188 else if (v.equals("1.3")) settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_3);
189 else if (v.equals("1.4")) settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_4);
190 else if (v.equals("1.5")) settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_5);
191 else throw new RuntimeException("I have no idea what Java " + v + " is. Ask David Crawshaw.");
194 public void setVerbose(boolean v) { verbose = v; }
195 public void setVeryVerbose(boolean v) { veryverbose = v; }
196 public void setWarnings(boolean w) { warnings = w; }
198 public void compile() throws IOException {
199 List s = new ArrayList();
202 Manifest m = new Manifest();
203 m.getMainAttributes().putValue("Manifest-Version", "1.0");
204 if (mainclass != null) m.getMainAttributes().putValue("Main-Class", mainclass);
205 jarfile = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(builddir)), m);
207 for (int i=0; i < sourcedirs.length; i++) {
208 File src = new File(sourcedirs[i]);
210 if (veryverbose) System.out.println("source directory not found: "+sourcedirs[i]);
213 filterSources(s, src, new char[0][], sourcedirs[i]);
216 if (veryverbose) System.out.println("working with "+s.size() +" sources");
217 sources = new Source[s.size()]; s.toArray(sources);
218 ICompilationUnit[] units = new ICompilationUnit[s.size()];
219 int u = 0; for (int i=0; i < sources.length; i++)
220 if (sources[i].compiled == null) units[u++] = sources[i].unit;
221 if (u != units.length) {
222 ICompilationUnit[] newu = new ICompilationUnit[u];
223 System.arraycopy(units, 0, newu, 0, u);
229 StringWriter sw = new StringWriter();
230 StringBuffer w = sw.getBuffer();
231 warn = new PrintWriter(sw);
233 org.eclipse.jdt.internal.compiler.Compiler jdt =
234 new org.eclipse.jdt.internal.compiler.Compiler(
235 env, policy, settings, results, problems);
238 if (warnings && !hasErrors) { out.write(w.toString()); out.flush(); }
241 if (jarfile != null) jarfile.close();
242 } catch (Exception e) {
245 if (verbose) System.out.print(clearing + " \r");
248 private final FilenameFilter filterSrcs = new FilenameFilter() {
249 public boolean accept(File dir, String name) { return name.endsWith(".java"); }
251 private final FileFilter filterDirs = new FileFilter() {
252 public boolean accept(File path) { return path.isDirectory(); }
255 private void filterSources(List s, File dir, char[][] pack, String srcdir) {
256 List bclasses = new ArrayList();
257 File bdir = new File(builddir, str(pack, File.separatorChar));
259 // add the java files in this directory
260 File[] ja = dir.listFiles(filterSrcs);
261 for (int i=0; i < ja.length; i++) {
262 char[] n = name(classname(ja[i].getName()));
263 Source src = new Source(ja[i], n, pack, srcdir);
265 // skip the file if the build version is newer than the source
266 String bclass = new String(n);
267 File bfile = new File(bdir, bclass + ".class");
268 if (bfile.lastModified() > ja[i].lastModified()) {
269 src.compiled = bytes(bfile);
270 bclasses.add(bclass);
276 // process the inner classes of any binary files
277 for (int i=0; i < bclasses.size(); i++) {
278 final String bc = (String)bclasses.get(i);
279 final FilenameFilter f = new FilenameFilter() {
280 public boolean accept(File dir, String name) {
281 return name.length() > bc.length() && name.startsWith(bc) &&
282 name.charAt(bc.length()) == '$' && name.endsWith(".class");
285 File[] bfile = bdir.listFiles(f);
286 for (int j=0; j < bfile.length; j++) {
287 Source src = new Source(bfile[j],
288 name(classname(bfile[j].getName())), pack, srcdir);
289 src.compiled = bytes(bfile[j]);
294 // add the subdirectories as packages
295 File[] d = dir.listFiles(filterDirs);
296 for (int i=0; i < d.length; i++) {
297 char[][] newpack = new char[pack.length + 1][];
298 for (int j=0; j < pack.length; j++) newpack[j] = pack[j];
299 newpack[pack.length] = d[i].getName().toCharArray();
300 filterSources(s, d[i], newpack, srcdir);
305 /** Represents a file to be compiled. */
308 char[] n; char[][] p;
310 char[] processed = null;
311 byte[] compiled = null;
312 ClassFileReader reader = null;
314 final ICompilationUnit unit = new ICompilationUnit() {
315 public char[] getMainTypeName() { return n; }
316 public char[][] getPackageName() { return p; }
317 public char[] getFileName() { return fileName; }
318 public char[] getContents() {
319 if (processed != null) return processed;
322 Reader r = new InputStreamReader(new BufferedInputStream(
323 new FileInputStream(orig)));
324 StringWriter w = new StringWriter();
327 synchronized (preprocessor) {
328 preprocessor.setReader(r);
329 preprocessor.setWriter(w);
330 err = preprocessor.process();
333 if (err.size() > 0) {
334 for (int i=0; i < err.size(); i++) {
335 Preprocessor.Warning warn = (Preprocessor.Warning)err.get(i);
336 out.print(getFileName());
338 out.print(warn.getLine());
340 out.print(warn instanceof Preprocessor.Error ?
341 " error: " : " warning: ");
342 out.println(warn.getMessage());
347 processed = w.toString().toCharArray();
348 } catch (IOException e) {
349 System.out.println("IOException: "+e); // FIXME
357 private Source(File o, char[] n, char[][] p, String srcdir) {
358 orig = o; this.n = n; this.p = p;
359 String file = srcdir;
360 file += File.separatorChar + str(p, File.separatorChar);
361 file += File.separatorChar + new String(n) + ".java";
362 fileName = file.toCharArray();
366 // Compiler Parameters ////////////////////////////////////////////////////
368 // FEATURE: may be able to use this to block access to APIs generated for stack objects
369 final AccessRestriction access = null;
371 /** Used by compiler to resolve classes. */
372 final INameEnvironment env = new INameEnvironment() {
373 public NameEnvironmentAnswer findType(char[][] c) { return findType(name(c), pack(c)); }
374 public NameEnvironmentAnswer findType(char[] n, char[][] p) {
375 if (veryverbose) System.out.print("findType: "+ str(p, '.') + "."+new String(n));
378 String classname = new String(n);
379 Class c = Class.forName(str(p, '.') + '.' + classname);
380 if (veryverbose) System.out.println(" found in classloader: "+ c);
381 IBinaryType b = (IBinaryType)loaded.get(c);
382 if (b == null) loaded.put(c, b = new ClassFileReader(
383 bytes(c), (str(p, '/') + '/' + classname).toCharArray()));
384 return new NameEnvironmentAnswer(b, access);
385 } catch (ClassNotFoundException e) {
386 } catch (LinkageError e) {
387 } catch (ClassFormatException e) {
389 throw new Error("ClassFormatException reading system class: " +
390 str(p, '.')+new String(n));
393 // cut out searches for java.* packages in sources list
394 if (p.length > 0 && eq(p[0], "java".toCharArray())) {
395 if (veryverbose) System.out.println(" not found, unknown java.*");
400 for (int i=0; i < sources.length; i++) {
401 Source s = sources[i];
402 if (eq(n, s.n) && eq(p, s.p)) {
403 if (s.reader != null) {
404 if (veryverbose) System.out.println(" found reader");
405 return new NameEnvironmentAnswer(s.reader, access);
407 if (s.compiled != null) {
408 if (veryverbose) System.out.println(" found compiled, new reader");
409 s.reader = new ClassFileReader(s.compiled,
410 s.orig.getName().toCharArray());
411 return new NameEnvironmentAnswer(s.reader, access);
413 if (veryverbose) System.out.println(" found unit");
414 return new NameEnvironmentAnswer(sources[i].unit, access);
417 } catch (ClassFormatException e) {
419 throw new Error("unexpected ClassFormatException resolving compiled class: "+e);
421 if (veryverbose) System.out.println(" not found");
424 public boolean isPackage(char[][] parent, char[] name) {
425 if (veryverbose) System.out.println("isPackage: "+ str(parent, '.') + "."+new String(name));
426 String parentName = str(parent, '/');
427 for (int i=0; i < sources.length; i++) {
428 if (eq(name, sources[i].n) && eq(parent, sources[i].p)) return false;
429 if (eq(pack(sources[i].p), parent) && eq(name(sources[i].p), name)) return true;
432 loader.getResource(parentName + ".class") == null &&
433 loader.getResource(parentName + '/' + new String(name) + ".class") == null;
435 public void cleanup() {}
438 /** Used by compiler to decide what do with problems.. */
439 private final IErrorHandlingPolicy policy =
440 DefaultErrorHandlingPolicies.proceedWithAllProblems();
442 /** Used by compiler for general options. */
443 private final Map settings = new HashMap();
445 settings.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE);
446 settings.put(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE);
447 settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_5);
448 settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_1);
451 /** Used by compiler for processing compiled classes and their errors. */
452 private final ICompilerRequestor results = new ICompilerRequestor() {
453 public void acceptResult(CompilationResult result) {
454 if (veryverbose) System.out.println("got result: "+result);
455 if (result.hasProblems()) {
457 IProblem[] p = result.getProblems();
459 for (int i=0; i < p.length; i++) {
460 if (p[i].isError()) { o = out; err = true; }
463 o.print(p[i].getOriginatingFileName());
465 o.print(p[i].getSourceLineNumber());
467 o.print(p[i].isError() ? " error: " : " warning: ");
468 o.println(p[i].getMessage());
471 if (err) { hasErrors = true; return; }
474 ClassFile[] c = result.getClassFiles();
475 for (int i=0; i < c.length; i++) {
477 char[][] name = c[i].getCompoundName();
482 while (pct.length() < 2) pct = " " + pct;
483 pct = "(" + pct + "%) ";
485 String printme = " writing: " + pct + str(pack(name),'.') + "." + new String(name(name));
486 if (clearing.length() < printme.length()) clearing = "";
487 else clearing = clearing.substring(printme.length());
488 System.out.print(printme + clearing + "\r");
489 for(clearing = ""; clearing.length() < printme.length() + 5; clearing += " ");
493 jarfile.putNextEntry(new ZipEntry(str(pack(name), '/') + "/" + new String(name(name)) + ".class"));
494 jarfile.write(c[i].getBytes());
495 } catch (java.util.zip.ZipException ze) {
496 // HACK: horrendous hack
497 if (ze.getMessage().indexOf("duplicate entry") != -1) {
498 //System.out.println("compiler emitted class twice: " + new String(name(name)));
504 // build package path to new class file
505 File path = new File(builddir, str(pack(name), '/'));
506 if (!path.exists()) path.mkdirs();
507 // write new class file
508 path = new File(path, new String(name(name)) + ".class");
509 OutputStream o = new BufferedOutputStream(new FileOutputStream(path));
510 o.write(c[i].getBytes());
513 } catch (IOException e) {
514 System.out.println("IOException writing class"); // FIXME
522 String clearing = "";
524 /** Problem creater for compiler. */
525 private final IProblemFactory problems = new DefaultProblemFactory();
528 // Helper Functiosn ///////////////////////////////////////////////////////
530 /** Convert source file path into class name block.
531 * eg. in: java/lang/String.java -> { {java} {lang} {String} } */
532 private static char[][] classname(String name) {
533 String delim = name.indexOf('/') == -1 ? "." : "/";
535 if (name.endsWith(".java")) name = name.substring(0, name.length() - 5);
536 if (name.endsWith(".class")) name = name.substring(0, name.length() - 6);
537 if (name.startsWith(delim)) name = name.substring(1);
539 StringTokenizer st = new StringTokenizer(name, delim);
540 char[][] n = new char[st.countTokens()][];
541 for (int i=0; st.hasMoreTokens(); i++) n[i] = st.nextToken().toCharArray();
545 /** Convert class name into a String. */
546 private static String str(char[][] name, char delim) {
547 StringBuffer b = new StringBuffer();
548 for (int i=0; name != null && i < name.length; i++) {
549 if (name[i] == null || name[i].length == 0) continue;
550 if (i > 0) b.append(delim);
556 /** Returns the package component of a class name.
557 * Effectively returns char[length - 1][]. */
558 private static char[][] pack(char[][] c) {
559 char[][] p = new char[c.length - 1][];
560 for (int i=0; i < p.length; i++) p[i] = c[i];
564 /** Returns the direct-name component of a class name.
565 * eg. String from java.lang.String */
566 private static char[] name(char[][] c) { return c[c.length - 1]; }
568 /** Returns true of contents of both char arrays are equal. */
569 private static boolean eq(char[][] c1, char[][] c2) {
570 if (c1 == null || c2 == null) return c1 == c2;
571 if (c1.length != c2.length) return false;
572 for (int i=0; i < c1.length; i++) if (!eq(c1[i], c2[i])) return false;
576 /** Returns true of contents of both char arrays are equal. */
577 private static boolean eq(char[] c1, char[] c2) {
578 if (c1 == null || c2 == null) return c1 == c2;
579 if (c1.length != c2.length) return false;
580 for (int i=0; i < c1.length; i++) if (c1[i] != c2[i]) return false;
584 /** Returns class name as per VM Spec 4.2. eg. java/lang/String */
585 private static char[] name(Class c) {
586 return c == null ? null : c.getName().replace('.', '/').toCharArray();
589 /** Returns the type name of a class as per VM Spec 4.3.2. */
590 private static char[] typeName(Class p) {
591 StringBuffer sb = new StringBuffer();
593 return sb.toString().toCharArray();
596 /** Returns the type name of a class as per VM Spec 4.3.2.
597 * eg. int -> I, String -> Ljava/lang/String; */
598 private static void typeName(Class p, StringBuffer sb) {
599 String name = p.getName();
600 switch (name.charAt(0)) {
601 case 'B': case 'C': case 'D': case 'F': case 'I':
602 case 'J': case 'S': case 'Z': case 'V': case '[':
603 sb.append(name(p)); break;
605 case 'b': if (name.equals("boolean")) { sb.append('Z'); break; }
606 if (name.equals("byte")) { sb.append('B'); break; }
607 case 'c': if (name.equals("char")) { sb.append('C'); break; }
608 case 'd': if (name.equals("double")) { sb.append('D'); break; }
609 case 'f': if (name.equals("float")) { sb.append('F'); break; }
610 case 'i': if (name.equals("int")) { sb.append('I'); break; }
611 case 'l': if (name.equals("long")) { sb.append('J'); break; }
612 case 's': if (name.equals("short")) { sb.append('S'); break; }
613 case 'v': if (name.equals("void")) { sb.append('V'); break; }
615 sb.append('L'); sb.append(name(p)); sb.append(';');
619 /** Returns the descriptor of a method per VM Spec 4.3.3.
620 * eg. int get(String n, boolean b) -> (Ljava/lang/String;B)I */
621 private static char[] descriptor(Class[] p, Class r) {
622 StringBuffer sb = new StringBuffer();
624 if (p != null) for (int i=0; i < p.length; i++) typeName(p[i], sb);
626 if (r != null) typeName(r, sb);
627 return sb.toString().toCharArray();
630 private static byte[] bytes(Class c) {
631 return bytes(c.getResourceAsStream('/' + c.getName().replace('.', '/') + ".class"));
633 private static byte[] bytes(File bfile) {
634 try { return bytes(new FileInputStream(bfile)); }
635 catch (FileNotFoundException e) { throw new Error("FileNotFoundException reading bytes: "+e); }
637 private static byte[] bytes(InputStream bin) {
638 byte[] bytes = new byte[2 * 1024];
641 while ((in = bin.read(bytes, pos, bytes.length - pos)) != -1) {
643 if (pos == bytes.length) {
644 byte[] newbytes= new byte[pos * 2];
645 System.arraycopy(bytes, 0, newbytes, 0, pos);
650 } catch (IOException e) {
652 throw new Error("IOException reading class file: "+e);
655 if (pos != bytes.length) {
656 byte[] newbytes= new byte[pos * 2];
657 System.arraycopy(bytes, 0, newbytes, 0, pos);