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;
38 boolean keepjar = false;
40 if (args.length == 0) args = new String[] { "--help" };
41 for (int i=0; i < args.length; i++) {
42 if (args[i].charAt(0) == '-') {
43 if (args[i].length() == 1) {
44 System.out.println("Illegal switch: -"); return; }
45 switch (args[i].charAt(1)) {
47 if (args[i].equals("--help")) printHelp();
48 else System.out.println("Unknown switch: -");
51 if (i == args.length - 1) {
52 System.out.println("Missing parameter: "+args[i]); return; }
53 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 if (blddir != null) { System.out.println("cannot specify both -d and -j"); return; }
66 if (i == args.length - 1) {
67 System.out.println("Missing parameter: "+args[i]); return; }
68 mainclass = args[++i];
71 if (i == args.length - 1) {
72 System.out.println("Missing parameter: "+args[i]); return; }
76 if (i == args.length - 1) {
77 System.out.println("Missing parameter: "+args[i]); return; }
81 if (i == args.length - 1) {
82 System.out.println("Missing parameter: "+args[i]); return; }
95 } else srcdir.add(args[i]);
98 Compiler c = new Compiler();
100 if (buildjar) c.setBuildJar(blddir, keepjar);
101 else c.setBuildDir(blddir);
103 if (source != null) c.setSource(source);
104 if (target != null) c.setTarget(target);
105 if (mainclass != null) c.setMainClass(mainclass);
107 String[] s = new String[srcdir.size()];
111 c.setVerbose(verbose);
112 c.setWarnings(warnings);
113 c.setVeryVerbose(veryverbose);
114 boolean hasErrors = c.compile();
115 if (hasErrors) Runtime.getRuntime().exit(-1);
116 Runtime.getRuntime().exit(0);
118 private static void printHelp() {
119 System.out.println("Usage java -cp ... org.ibex.tool.Compiler [options] <source dir> ...");
120 System.out.println("Options:");
121 System.out.println(" -d <directory> Directory to put generated class files in");
122 System.out.println(" -j <jarfile> Jar file to put generated class files in");
123 System.out.println(" -m <class> Main-Class for jar file.");
124 System.out.println(" -s <release> Compile with specified source compatibility.");
125 System.out.println(" -t <release> Compile with specified class file compatibility.");
126 System.out.println(" -v Verbose output.");
127 System.out.println(" -V Very Verbose output.");
128 System.out.println(" -h or --help Print this message.");
129 System.out.println("");
133 // Compiler Interface /////////////////////////////////////////////////////
135 private ClassLoader loader = ClassLoader.getSystemClassLoader();
136 private Map loaded = new HashMap();
137 private PrintWriter out = new PrintWriter(System.out);
138 private Preprocessor preprocessor;
140 private Source[] sources;
142 private File builddir = null;
143 private boolean buildzip = false;
144 private boolean keepzip = false;
145 private ZipOutputStream jarfile = null;
146 private String mainclass = null;
148 private String[] sourcedirs = new String[0];
150 private PrintWriter warn;
151 private boolean hasErrors;
152 private boolean verbose = false;
153 private boolean veryverbose = false;
154 private boolean warnings = true;
157 List defs = Collections.EMPTY_LIST;
159 String define = System.getProperty("org.ibex.tool.preprocessor.define");
160 if (define != null) {
161 defs = new ArrayList();
162 StringTokenizer st = new StringTokenizer(define.toUpperCase(), ",");
163 while (st.hasMoreTokens()) defs.add(st.nextToken().trim());
166 preprocessor = new Preprocessor(null, null, defs);
169 public void setMainClass(String mainclass) { this.mainclass = mainclass; }
170 public void setBuildJar(String dir, boolean keepjar) throws IOException {
171 builddir = new File(dir == null ? "." : dir);
173 if (keepjar) keepzip = true;
175 public void setBuildDir(String dir) throws IOException {
176 builddir = new File(dir == null ? "." : dir);
179 public void setSourceDirs(String[] dir) { sourcedirs = dir; }
181 /** Pass CompilerOptions.VERSION_1_*. A String of form "1.1", ".2", etc. */
182 public void setSource(String v) {
183 if (v.equals("1.1")) settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_1);
184 else if (v.equals("1.2")) settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_2);
185 else if (v.equals("1.3")) settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_3);
186 else if (v.equals("1.4")) settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_4);
187 else if (v.equals("1.5")) settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_5);
188 else throw new RuntimeException("I have no idea what Java " + v + " is. Ask David Crawshaw.");
191 /** Pass CompilerOptions.VERSION_1_*. A String of form "1.1", ".2", etc. */
192 public void setTarget(String v) {
193 if (v.equals("1.1")) settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_1);
194 else if (v.equals("1.2")) settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_2);
195 else if (v.equals("1.3")) settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_3);
196 else if (v.equals("1.4")) settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_4);
197 else if (v.equals("1.5")) settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_5);
198 else throw new RuntimeException("I have no idea what Java " + v + " is. Ask David Crawshaw.");
201 public void setVerbose(boolean v) { verbose = v; }
202 public void setVeryVerbose(boolean v) { veryverbose = v; }
203 public void setWarnings(boolean w) { warnings = w; }
205 ZipInputStream keptzip = null;
207 public boolean compile() throws IOException {
208 List s = new ArrayList();
214 keptzip = new ZipInputStream(new FileInputStream(f));
218 Manifest m = new Manifest();
219 m.getMainAttributes().putValue("Manifest-Version", "1.0");
220 if (mainclass != null) m.getMainAttributes().putValue("Main-Class", mainclass);
221 jarfile = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(builddir)), m);
222 entries.add("META-INF/MANIFEST.MF");
224 for (int i=0; i < sourcedirs.length; i++) {
225 File src = new File(sourcedirs[i]);
227 if (veryverbose) System.out.println("source directory not found: "+sourcedirs[i]);
230 filterSources(s, src, new char[0][], sourcedirs[i]);
233 if (veryverbose) System.out.println("working with "+s.size() +" sources");
234 sources = new Source[s.size()]; s.toArray(sources);
235 ICompilationUnit[] units = new ICompilationUnit[s.size()];
236 int u = 0; for (int i=0; i < sources.length; i++)
237 if (sources[i].compiled == null) units[u++] = sources[i].unit;
238 if (u != units.length) {
239 ICompilationUnit[] newu = new ICompilationUnit[u];
240 System.arraycopy(units, 0, newu, 0, u);
246 StringWriter sw = new StringWriter();
247 StringBuffer w = sw.getBuffer();
248 warn = new PrintWriter(sw);
250 org.eclipse.jdt.internal.compiler.Compiler jdt =
251 new org.eclipse.jdt.internal.compiler.Compiler(
252 env, policy, settings, results, problems);
255 if (warnings && !hasErrors) { out.write(w.toString()); out.flush(); }
258 if (jarfile != null) {
259 if (keptzip != null) {
260 byte[] buf = new byte[1024 * 16];
261 for(ZipEntry ze = keptzip.getNextEntry(); ze != null; ze = keptzip.getNextEntry()) {
262 if (entries.contains(ze.getName())) continue;
263 message(" preserving: " + ze.getName());
264 jarfile.putNextEntry(ze);
266 int numread = keptzip.read(buf, 0, buf.length);
267 if (numread == -1) break;
268 jarfile.write(buf, 0, numread);
274 } catch (Exception e) {
277 if (verbose) System.out.print(clearing + " \r");
280 List entries = new ArrayList();
282 private final FilenameFilter filterSrcs = new FilenameFilter() {
283 public boolean accept(File dir, String name) { return name.endsWith(".java"); }
285 private final FileFilter filterDirs = new FileFilter() {
286 public boolean accept(File path) { return path.isDirectory(); }
289 private void filterSources(List s, File dir, char[][] pack, String srcdir) {
290 List bclasses = new ArrayList();
291 File bdir = new File(builddir, str(pack, File.separatorChar));
293 // add the java files in this directory
294 File[] ja = dir.listFiles(filterSrcs);
295 for (int i=0; i < ja.length; i++) {
296 char[] n = name(classname(ja[i].getName()));
297 Source src = new Source(ja[i], n, pack, srcdir);
299 // skip the file if the build version is newer than the source
300 String bclass = new String(n);
301 File bfile = new File(bdir, bclass + ".class");
302 if (bfile.lastModified() > ja[i].lastModified()) {
303 src.compiled = bytes(bfile);
304 bclasses.add(bclass);
310 // process the inner classes of any binary files
311 for (int i=0; i < bclasses.size(); i++) {
312 final String bc = (String)bclasses.get(i);
313 final FilenameFilter f = new FilenameFilter() {
314 public boolean accept(File dir, String name) {
315 return name.length() > bc.length() && name.startsWith(bc) &&
316 name.charAt(bc.length()) == '$' && name.endsWith(".class");
319 File[] bfile = bdir.listFiles(f);
320 for (int j=0; j < bfile.length; j++) {
321 Source src = new Source(bfile[j],
322 name(classname(bfile[j].getName())), pack, srcdir);
323 src.compiled = bytes(bfile[j]);
328 // add the subdirectories as packages
329 File[] d = dir.listFiles(filterDirs);
330 for (int i=0; i < d.length; i++) {
331 char[][] newpack = new char[pack.length + 1][];
332 for (int j=0; j < pack.length; j++) newpack[j] = pack[j];
333 newpack[pack.length] = d[i].getName().toCharArray();
334 filterSources(s, d[i], newpack, srcdir);
339 /** Represents a file to be compiled. */
342 char[] n; char[][] p;
344 char[] processed = null;
345 byte[] compiled = null;
346 ClassFileReader reader = null;
348 final ICompilationUnit unit = new ICompilationUnit() {
349 public char[] getMainTypeName() { return n; }
350 public char[][] getPackageName() { return p; }
351 public char[] getFileName() { return fileName; }
352 public char[] getContents() {
353 if (processed != null) return processed;
356 Reader r = new InputStreamReader(new BufferedInputStream(
357 new FileInputStream(orig)));
358 StringWriter w = new StringWriter();
361 synchronized (preprocessor) {
362 preprocessor.setReader(r);
363 preprocessor.setWriter(w);
364 err = preprocessor.process();
367 if (err.size() > 0) {
368 for (int i=0; i < err.size(); i++) {
369 Preprocessor.Warning warn = (Preprocessor.Warning)err.get(i);
370 out.print(getFileName());
372 out.print(warn.getLine());
374 out.print(warn instanceof Preprocessor.Error ?
375 " error: " : " warning: ");
376 out.println(warn.getMessage());
381 processed = w.toString().toCharArray();
382 } catch (IOException e) {
383 System.out.println("IOException: "+e); // FIXME
391 private Source(File o, char[] n, char[][] p, String srcdir) {
392 orig = o; this.n = n; this.p = p;
393 String file = srcdir;
394 file += File.separatorChar + str(p, File.separatorChar);
395 file += File.separatorChar + new String(n) + ".java";
396 fileName = file.toCharArray();
400 // Compiler Parameters ////////////////////////////////////////////////////
402 // FEATURE: may be able to use this to block access to APIs generated for stack objects
403 final AccessRestriction access = null;
405 /** Used by compiler to resolve classes. */
406 final INameEnvironment env = new INameEnvironment() {
407 public NameEnvironmentAnswer findType(char[][] c) { return findType(name(c), pack(c)); }
408 public NameEnvironmentAnswer findType(char[] n, char[][] p) {
409 if (veryverbose) System.out.print("findType: "+ str(p, '.') + "."+new String(n));
412 String classname = new String(n);
413 Class c = Class.forName(str(p, '.') + '.' + classname);
414 if (veryverbose) System.out.println(" found in classloader: "+ c);
415 IBinaryType b = (IBinaryType)loaded.get(c);
416 if (b == null) loaded.put(c, b = new ClassFileReader(
417 bytes(c), (str(p, '/') + '/' + classname).toCharArray()));
418 return new NameEnvironmentAnswer(b, access);
419 } catch (ClassNotFoundException e) {
420 } catch (LinkageError e) {
421 } catch (ClassFormatException e) {
423 throw new Error("ClassFormatException reading system class: " +
424 str(p, '.')+new String(n));
427 // cut out searches for java.* packages in sources list
428 if (p.length > 0 && eq(p[0], "java".toCharArray())) {
429 if (veryverbose) System.out.println(" not found, unknown java.*");
434 for (int i=0; i < sources.length; i++) {
435 Source s = sources[i];
436 if (eq(n, s.n) && eq(p, s.p)) {
437 if (s.reader != null) {
438 if (veryverbose) System.out.println(" found reader");
439 return new NameEnvironmentAnswer(s.reader, access);
441 if (s.compiled != null) {
442 if (veryverbose) System.out.println(" found compiled, new reader");
443 s.reader = new ClassFileReader(s.compiled,
444 s.orig.getName().toCharArray());
445 return new NameEnvironmentAnswer(s.reader, access);
447 if (veryverbose) System.out.println(" found unit");
448 return new NameEnvironmentAnswer(sources[i].unit, access);
451 } catch (ClassFormatException e) {
453 throw new Error("unexpected ClassFormatException resolving compiled class: "+e);
455 if (veryverbose) System.out.println(" not found");
458 public boolean isPackage(char[][] parent, char[] name) {
459 if (veryverbose) System.out.println("isPackage: "+ str(parent, '.') + "."+new String(name));
460 String parentName = str(parent, '/');
461 for (int i=0; i < sources.length; i++) {
462 if (eq(name, sources[i].n) && eq(parent, sources[i].p)) return false;
463 if (eq(pack(sources[i].p), parent) && eq(name(sources[i].p), name)) return true;
466 loader.getResource(parentName + ".class") == null &&
467 loader.getResource(parentName + '/' + new String(name) + ".class") == null;
469 public void cleanup() {}
472 /** Used by compiler to decide what do with problems.. */
473 private final IErrorHandlingPolicy policy =
474 DefaultErrorHandlingPolicies.proceedWithAllProblems();
476 /** Used by compiler for general options. */
477 private final Map settings = new HashMap();
479 settings.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE);
480 settings.put(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE);
481 settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_5);
482 settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_1);
485 /** Used by compiler for processing compiled classes and their errors. */
486 private final ICompilerRequestor results = new ICompilerRequestor() {
487 public void acceptResult(CompilationResult result) {
488 if (veryverbose) System.out.println("got result: "+result);
489 if (result.hasProblems()) {
491 IProblem[] p = result.getProblems();
493 for (int i=0; i < p.length; i++) {
494 if (p[i].isError()) { o = out; err = true; }
497 o.print(p[i].getOriginatingFileName());
499 o.print(p[i].getSourceLineNumber());
501 o.print(p[i].isError() ? " error: " : " warning: ");
502 o.println(p[i].getMessage());
505 if (err) { hasErrors = true; return; }
508 ClassFile[] c = result.getClassFiles();
509 for (int i=0; i < c.length; i++) {
511 char[][] name = c[i].getCompoundName();
516 while (pct.length() < 2) pct = " " + pct;
517 pct = "(" + pct + "%) ";
519 String printme = " writing: " + pct + str(pack(name),'.') + "." + new String(name(name));
524 jarfile.putNextEntry(new ZipEntry(str(pack(name), '/') + "/" + new String(name(name)) + ".class"));
525 jarfile.write(c[i].getBytes());
526 entries.add(str(pack(name), '/') + "/" + new String(name(name)) + ".class");
527 } catch (java.util.zip.ZipException ze) {
528 // HACK: horrendous hack
529 if (ze.getMessage().indexOf("duplicate entry") != -1) {
530 //System.out.println("compiler emitted class twice: " + new String(name(name)));
536 // build package path to new class file
537 File path = new File(builddir, str(pack(name), '/'));
538 if (!path.exists()) path.mkdirs();
539 // write new class file
540 path = new File(path, new String(name(name)) + ".class");
541 OutputStream o = new BufferedOutputStream(new FileOutputStream(path));
542 o.write(c[i].getBytes());
545 } catch (IOException e) {
546 System.out.println("IOException writing class"); // FIXME
553 public static void message(String printme) {
554 if (clearing.length() < printme.length()) clearing = "";
555 else clearing = clearing.substring(printme.length());
556 System.out.print(printme + clearing + "\r");
557 for(clearing = ""; clearing.length() < printme.length() + 5; clearing += " ");
561 static String clearing = "";
563 /** Problem creater for compiler. */
564 private final IProblemFactory problems = new DefaultProblemFactory();
567 // Helper Functiosn ///////////////////////////////////////////////////////
569 /** Convert source file path into class name block.
570 * eg. in: java/lang/String.java -> { {java} {lang} {String} } */
571 private static char[][] classname(String name) {
572 String delim = name.indexOf('/') == -1 ? "." : "/";
574 if (name.endsWith(".java")) name = name.substring(0, name.length() - 5);
575 if (name.endsWith(".class")) name = name.substring(0, name.length() - 6);
576 if (name.startsWith(delim)) name = name.substring(1);
578 StringTokenizer st = new StringTokenizer(name, delim);
579 char[][] n = new char[st.countTokens()][];
580 for (int i=0; st.hasMoreTokens(); i++) n[i] = st.nextToken().toCharArray();
584 /** Convert class name into a String. */
585 private static String str(char[][] name, char delim) {
586 StringBuffer b = new StringBuffer();
587 for (int i=0; name != null && i < name.length; i++) {
588 if (name[i] == null || name[i].length == 0) continue;
589 if (i > 0) b.append(delim);
595 /** Returns the package component of a class name.
596 * Effectively returns char[length - 1][]. */
597 private static char[][] pack(char[][] c) {
598 char[][] p = new char[c.length - 1][];
599 for (int i=0; i < p.length; i++) p[i] = c[i];
603 /** Returns the direct-name component of a class name.
604 * eg. String from java.lang.String */
605 private static char[] name(char[][] c) { return c[c.length - 1]; }
607 /** Returns true of contents of both char arrays are equal. */
608 private static boolean eq(char[][] c1, char[][] c2) {
609 if (c1 == null || c2 == null) return c1 == c2;
610 if (c1.length != c2.length) return false;
611 for (int i=0; i < c1.length; i++) if (!eq(c1[i], c2[i])) return false;
615 /** Returns true of contents of both char arrays are equal. */
616 private static boolean eq(char[] c1, char[] c2) {
617 if (c1 == null || c2 == null) return c1 == c2;
618 if (c1.length != c2.length) return false;
619 for (int i=0; i < c1.length; i++) if (c1[i] != c2[i]) return false;
623 /** Returns class name as per VM Spec 4.2. eg. java/lang/String */
624 private static char[] name(Class c) {
625 return c == null ? null : c.getName().replace('.', '/').toCharArray();
628 /** Returns the type name of a class as per VM Spec 4.3.2. */
629 private static char[] typeName(Class p) {
630 StringBuffer sb = new StringBuffer();
632 return sb.toString().toCharArray();
635 /** Returns the type name of a class as per VM Spec 4.3.2.
636 * eg. int -> I, String -> Ljava/lang/String; */
637 private static void typeName(Class p, StringBuffer sb) {
638 String name = p.getName();
639 switch (name.charAt(0)) {
640 case 'B': case 'C': case 'D': case 'F': case 'I':
641 case 'J': case 'S': case 'Z': case 'V': case '[':
642 sb.append(name(p)); break;
644 case 'b': if (name.equals("boolean")) { sb.append('Z'); break; }
645 if (name.equals("byte")) { sb.append('B'); break; }
646 case 'c': if (name.equals("char")) { sb.append('C'); break; }
647 case 'd': if (name.equals("double")) { sb.append('D'); break; }
648 case 'f': if (name.equals("float")) { sb.append('F'); break; }
649 case 'i': if (name.equals("int")) { sb.append('I'); break; }
650 case 'l': if (name.equals("long")) { sb.append('J'); break; }
651 case 's': if (name.equals("short")) { sb.append('S'); break; }
652 case 'v': if (name.equals("void")) { sb.append('V'); break; }
654 sb.append('L'); sb.append(name(p)); sb.append(';');
658 /** Returns the descriptor of a method per VM Spec 4.3.3.
659 * eg. int get(String n, boolean b) -> (Ljava/lang/String;B)I */
660 private static char[] descriptor(Class[] p, Class r) {
661 StringBuffer sb = new StringBuffer();
663 if (p != null) for (int i=0; i < p.length; i++) typeName(p[i], sb);
665 if (r != null) typeName(r, sb);
666 return sb.toString().toCharArray();
669 private static byte[] bytes(Class c) {
670 return bytes(c.getResourceAsStream('/' + c.getName().replace('.', '/') + ".class"));
672 private static byte[] bytes(File bfile) {
673 try { return bytes(new FileInputStream(bfile)); }
674 catch (FileNotFoundException e) { throw new Error("FileNotFoundException reading bytes: "+e); }
676 private static byte[] bytes(InputStream bin) {
677 byte[] bytes = new byte[2 * 1024];
680 while ((in = bin.read(bytes, pos, bytes.length - pos)) != -1) {
682 if (pos == bytes.length) {
683 byte[] newbytes= new byte[pos * 2];
684 System.arraycopy(bytes, 0, newbytes, 0, pos);
689 } catch (IOException e) {
691 throw new Error("IOException reading class file: "+e);
694 if (pos != bytes.length) {
695 byte[] newbytes= new byte[pos * 2];
696 System.arraycopy(bytes, 0, newbytes, 0, pos);