removed Makefile; lifted repo/org.ibex.tool/src/ to src/
[org.ibex.tool.git] / src / org / ibex / tool / Compiler.java
1 package org.ibex.tool;
2
3 import java.io.*;
4 import java.util.*;
5 import java.util.zip.*;
6 import java.util.jar.*;
7
8 import java.lang.reflect.*;
9
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;
23
24 // FEATURE: add build dependencies like make (grab some Java dependency-checker code off the net?)
25
26 public class Compiler {
27     // Static Entry Point /////////////////////////////////////////////////////
28
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;
34
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)) {
41                     case '-':
42                         if (args[i].equals("--help")) printHelp();
43                         else System.out.println("Unknown switch: -");
44                         return;
45                     case 'd':
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; }
49                         blddir = args[++i];
50                         break;
51                     case 'j':
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; }
55                         blddir = args[++i];
56                         buildjar = true;
57                         break;
58                     case 'm':
59                         if (i == args.length - 1) {
60                             System.out.println("Missing parameter: "+args[i]); return; }
61                         mainclass = args[++i];
62                         break;
63                     case 'w':
64                         if (i == args.length - 1) {
65                             System.out.println("Missing parameter: "+args[i]); return; }
66                         warnings = false;
67                         break;
68                     case 's':
69                         if (i == args.length - 1) {
70                             System.out.println("Missing parameter: "+args[i]); return; }
71                         source = args[++i];
72                         break;
73                     case 't':
74                         if (i == args.length - 1) {
75                             System.out.println("Missing parameter: "+args[i]); return; }
76                         target = args[++i];
77                         break;
78                     case 'v':
79                         verbose = true;
80                         break;
81                     case 'V':
82                         veryverbose = true;
83                         break;
84                     case 'h':
85                         printHelp(); return;
86
87                 }
88             } else srcdir.add(args[i]);
89         }
90
91         Compiler c = new Compiler();
92         if (blddir != null) {
93             if (buildjar) c.setBuildJar(blddir);
94             else          c.setBuildDir(blddir);
95         }
96         if (source != null) c.setSource(source);
97         if (target != null) c.setTarget(target);
98         if (mainclass != null) c.setMainClass(mainclass);
99
100         String[] s = new String[srcdir.size()];
101         srcdir.toArray(s);
102         c.setSourceDirs(s);
103
104         c.setVerbose(verbose);
105         c.setWarnings(warnings);
106         c.setVeryVerbose(veryverbose);
107         c.compile();
108     }
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("");
121     }
122
123
124     // Compiler Interface /////////////////////////////////////////////////////
125
126     private ClassLoader loader = ClassLoader.getSystemClassLoader();
127     private Map loaded = new HashMap();
128     private PrintWriter out = new PrintWriter(System.out);
129     private Preprocessor preprocessor;
130
131     private Source[] sources;
132
133     private File builddir = null;
134     private boolean buildzip = false;
135     private ZipOutputStream jarfile = null;
136     private String mainclass = null;
137
138     private String[] sourcedirs = new String[0];
139
140     private PrintWriter warn;
141     private boolean hasErrors;
142     private boolean verbose = false;
143     private boolean veryverbose = false;
144     private boolean warnings = true;
145
146     public Compiler() {
147         List defs = Collections.EMPTY_LIST;
148
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());
154         }
155
156         preprocessor = new Preprocessor(null, null, defs);
157     }
158
159     public void setMainClass(String mainclass) { this.mainclass = mainclass; }
160     public void setBuildJar(String dir) throws IOException {
161         builddir = new File(dir == null ? "." : dir);
162         buildzip = true;
163     }
164     public void setBuildDir(String dir) throws IOException {
165         builddir = new File(dir == null ? "." : dir);
166     }
167
168     public void setSourceDirs(String[] dir) { sourcedirs = dir; }
169
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.");
178     }
179
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.");
188     }
189
190     public void setVerbose(boolean v) { verbose = v; }
191     public void setVeryVerbose(boolean v) { veryverbose = v; }
192     public void setWarnings(boolean w) { warnings = w; }
193
194     public void compile() throws IOException {
195         List s = new ArrayList();
196
197         if (buildzip) {
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);
202         }
203         for (int i=0; i < sourcedirs.length; i++) {
204             File src = new File(sourcedirs[i]);
205             if (!src.exists()) {
206                 if (veryverbose) System.out.println("source directory not found: "+sourcedirs[i]);
207                 continue;
208             }
209             filterSources(s, src, new char[0][], sourcedirs[i]);
210         }
211
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);
220             units = newu;
221         }
222
223         hasErrors = false;
224
225         StringWriter sw = new StringWriter();
226         StringBuffer w = sw.getBuffer();
227         warn = new PrintWriter(sw);
228
229         org.eclipse.jdt.internal.compiler.Compiler jdt =
230             new org.eclipse.jdt.internal.compiler.Compiler(
231                 env, policy, settings, results, problems);
232         jdt.compile(units);
233
234         if (warnings && !hasErrors) { out.write(w.toString()); out.flush(); }
235         warn = null;
236         try {
237             if (jarfile != null) jarfile.close();
238         } catch (Exception e) {
239             e.printStackTrace();
240         }
241         if (verbose) System.out.print(clearing + "   \r");
242     }
243
244     private final FilenameFilter filterSrcs = new FilenameFilter() {
245         public boolean accept(File dir, String name) { return name.endsWith(".java"); }
246     };
247     private final FileFilter filterDirs = new FileFilter() {
248         public boolean accept(File path) { return path.isDirectory(); }
249     };
250     private byte[] bytes(File bfile) {
251         byte[] bytes = new byte[2 * 1024];
252         int pos = 0, in = 0;
253         try {
254             InputStream bin = new FileInputStream(bfile);
255             while ((in = bin.read(bytes, pos, bytes.length - pos)) != -1) {
256                 pos += in;
257                 if (pos == bytes.length) {
258                     byte[] newbytes= new byte[pos * 2];
259                     System.arraycopy(bytes, 0, newbytes, 0, pos);
260                     bytes = newbytes;
261                 }
262             }
263             bin.close();
264         } catch (IOException e) {
265             System.out.println("Error reading class file"); // FIXME
266             e.printStackTrace(); return null;
267         }
268
269         if (pos != bytes.length) {
270             byte[] newbytes= new byte[pos * 2];
271             System.arraycopy(bytes, 0, newbytes, 0, pos);
272             bytes = newbytes;
273         }
274
275         return bytes;
276     }
277     private void filterSources(List s, File dir, char[][] pack, String srcdir) {
278         List bclasses = new ArrayList();
279         File bdir = new File(builddir, str(pack, File.separatorChar));
280
281         // add the java files in this directory
282         File[] ja = dir.listFiles(filterSrcs);
283         for (int i=0; i < ja.length; i++) {
284             char[] n = name(classname(ja[i].getName()));
285             Source src = new Source(ja[i], n, pack, srcdir);
286
287             // skip the file if the build version is newer than the source
288             String bclass = new String(n);
289             File bfile = new File(bdir, bclass + ".class");
290             if (bfile.lastModified() > ja[i].lastModified()) {
291                 src.compiled = bytes(bfile);
292                 bclasses.add(bclass);
293             }
294
295             s.add(src);
296         }
297
298         // process the inner classes of any binary files
299         for (int i=0; i < bclasses.size(); i++) {
300             final String bc = (String)bclasses.get(i);
301             final FilenameFilter f = new FilenameFilter() {
302                 public boolean accept(File dir, String name) {
303                     return name.length() > bc.length() && name.startsWith(bc) &&
304                            name.charAt(bc.length()) == '$' && name.endsWith(".class");
305                 }
306             };
307             File[] bfile = bdir.listFiles(f);
308             for (int j=0; j < bfile.length; j++) {
309                 Source src = new Source(bfile[j],
310                     name(classname(bfile[j].getName())), pack, srcdir);
311                 src.compiled = bytes(bfile[j]);
312                 s.add(src);
313             }
314         }
315
316         // add the subdirectories as packages
317         File[] d = dir.listFiles(filterDirs);
318         for (int i=0; i < d.length; i++) {
319             char[][] newpack = new char[pack.length + 1][];
320             for (int j=0; j < pack.length; j++) newpack[j] = pack[j];
321             newpack[pack.length] = d[i].getName().toCharArray();
322             filterSources(s, d[i], newpack, srcdir);
323         }
324     }
325
326
327     /** Represents a file to be compiled. */
328     final class Source {
329         char[] fileName;
330         char[] n; char[][] p;
331         File orig;
332         char[] processed = null;
333         byte[] compiled = null;
334         ClassFileReader reader = null;
335
336         final ICompilationUnit unit = new ICompilationUnit() {
337             public char[] getMainTypeName() { return n; }
338             public char[][] getPackageName() { return p; }
339             public char[] getFileName() { return fileName; }
340             public char[] getContents() {
341                 if (processed != null) return processed;
342
343                 try {
344                     Reader r = new InputStreamReader(new BufferedInputStream(
345                                new FileInputStream(orig)));
346                     StringWriter w = new StringWriter();
347                     Vector err;
348
349                     synchronized (preprocessor) {
350                         preprocessor.setReader(r);
351                         preprocessor.setWriter(w);
352                         err = preprocessor.process();
353                     }
354
355                     if (err.size() > 0) {
356                         for (int i=0; i < err.size(); i++) {
357                             Preprocessor.Warning warn = (Preprocessor.Warning)err.get(i);
358                             out.print(getFileName());
359                             out.print(':');
360                             out.print(warn.getLine());
361                             out.print(':');
362                             out.print(warn instanceof Preprocessor.Error ?
363                                       " error: " : " warning: ");
364                             out.println(warn.getMessage());
365                         }
366                         return null;
367                     }
368
369                     processed  = w.toString().toCharArray();
370                 } catch (IOException e) {
371                     System.out.println("IOException: "+e); // FIXME
372                     return null;
373                 }
374
375                 return processed;
376             }
377         };
378
379         private Source(File o, char[] n, char[][] p, String srcdir) {
380             orig = o; this.n = n; this.p = p;
381             String file = srcdir;
382             file += File.separatorChar +  str(p, File.separatorChar);
383             file += File.separatorChar + new String(n) + ".java";
384             fileName = file.toCharArray();
385         }
386     }
387
388     // ClassLoader Wrappers ///////////////////////////////////////////////////
389
390     final static class LoadedNestedType implements IBinaryNestedType {
391         private Class c;
392         LoadedNestedType(Class c) { this.c = c; }
393         public char[] getName() { return name(c); }
394         public char[] getEnclosingTypeName() { return name(c.getDeclaringClass()); }
395         public int getModifiers() { return c.getModifiers(); }
396     }
397
398     final static class LoadedField implements IBinaryField {
399         private Field f;
400         private Constant c;
401
402         LoadedField(Field f) {
403             this.f = f;
404             int m = f.getModifiers();
405
406             c = Constant.NotAConstant;
407             if (Modifier.isFinal(m) && Modifier.isStatic(m)) {
408                 try {
409                     Class type = f.getType();
410                     if (type == Boolean.TYPE) {
411                         c = new BooleanConstant(f.getBoolean(null));
412                     } else if (type == Byte.TYPE) {
413                         c = new ByteConstant(f.getByte(null));
414                     } else if (type == Character.TYPE) {
415                         c = new CharConstant(f.getChar(null));
416                     } else if (type == Double.TYPE) {
417                         c = new DoubleConstant(f.getDouble(null));
418                     } else if (type == Float.TYPE) {
419                         c = new FloatConstant(f.getFloat(null));
420                     } else if (type == Integer.TYPE) {
421                         c = new IntConstant(f.getInt(null));
422                     } else if (type == Long.TYPE) {
423                         c = new LongConstant(f.getLong(null));
424                     } else if (type == Short.TYPE) {
425                         c = new ShortConstant(f.getShort(null));
426                     } else if (type == String.class) {
427                         c = new StringConstant((String)f.get(null));
428                     }
429                 } catch (IllegalAccessException e) {}
430             }
431         }
432         public Constant getConstant() { return c; }
433         public char[] getTypeName() { return typeName(f.getType()); }
434         public char[] getName() { return f.getName().toCharArray(); }
435         public int getModifiers() { return f.getModifiers(); }
436     }
437
438     final static class LoadedConstructor implements IBinaryMethod {
439         private Constructor c;
440         private char[][] ex;
441         private char[] desc;
442
443         LoadedConstructor(Constructor c) {
444             this.c = c;
445
446             Class[] exs = c.getExceptionTypes();
447             ex = new char[exs.length][];
448             for (int i=0; i < ex.length; i++) ex[i] = name(exs[i]);
449
450             desc = descriptor(c.getParameterTypes(), null);
451         }
452         public int getModifiers() { return c.getModifiers(); }
453         public char[] getSelector() { return c.getName().toCharArray(); }
454         public boolean isConstructor() { return true; }
455         public boolean isClinit() { return false; }
456         public char[][] getArgumentNames() { return null; }
457         public char[][] getExceptionTypeNames() { return ex; }
458         public char[] getMethodDescriptor() { return desc; }
459     }
460
461     final static class LoadedMethod implements IBinaryMethod {
462         private Method m;
463         private char[][] ex;
464         private char[] desc;
465
466         LoadedMethod(Method m) {
467             this.m = m;
468
469             Class[] exs = m.getExceptionTypes();
470             ex = new char[exs.length][];
471             for (int i=0; i < ex.length; i++) ex[i] = name(exs[i]);
472
473             desc = descriptor(m.getParameterTypes(), m.getReturnType());
474         }
475         public int getModifiers() { return m.getModifiers(); }
476         public char[] getSelector() { return m.getName().toCharArray(); }
477         public boolean isConstructor() { return false; }
478         public boolean isClinit() { return false; }
479         public char[][] getArgumentNames() { return null; } // FEATURE: does this do anything cool?
480         public char[][] getExceptionTypeNames() { return ex; }
481         public char[] getMethodDescriptor() { return desc; }
482     }
483
484     final static class LoadedClass implements IBinaryType {
485         private Class c;
486         private IBinaryField[] f;
487         private char[][] inf;
488         private IBinaryNestedType[] nested;
489         private IBinaryMethod[] meth = null;
490
491         LoadedClass(Class c) {
492             this.c = c;
493
494             Field[] fields = c.getDeclaredFields();
495             List flist = new ArrayList(fields.length);
496             for (int i=0; i < fields.length; i++)
497                 if (!Modifier.isPrivate(fields[i].getModifiers()))
498                     flist.add(new LoadedField(fields[i]));
499             f = new IBinaryField[flist.size()];
500             flist.toArray(f);
501
502             Class[] interfaces = c.getInterfaces();
503             inf = new char[interfaces.length][];
504             for (int i=0; i < inf.length; i++) inf[i] = name(interfaces[i]);
505
506             Class[] classes = c.getClasses();
507             nested = new IBinaryNestedType[classes.length];
508             for (int i=0; i < nested.length; i++)
509                 nested[i] = new LoadedNestedType(classes[i]);
510
511             Constructor[] constructors = c.getDeclaredConstructors();
512             Method[] methods = c.getDeclaredMethods();
513             if (methods.length + constructors.length > 0) {
514                 List m = new ArrayList(methods.length + constructors.length);
515                 for (int j=0; j < methods.length; j++)
516                     if (!Modifier.isPrivate(methods[j].getModifiers()))
517                         m.add(new LoadedMethod(methods[j]));
518                 for (int j=0; j < constructors.length; j++)
519                     if (!Modifier.isPrivate(constructors[j].getModifiers()))
520                         m.add(new LoadedConstructor(constructors[j]));
521                 meth = new IBinaryMethod[m.size()]; m.toArray(meth);
522             }
523         }
524
525         public char[] getName() { return name(c); }
526         public char[] getEnclosingTypeName() { return name(c.getDeclaringClass()); }
527         public char[] getSuperclassName() { return name(c.getSuperclass()); }
528         public IBinaryField[] getFields() { return f; }
529         public char[][] getInterfaceNames() { return inf; }
530         public IBinaryNestedType[] getMemberTypes() { return nested; }
531         public IBinaryMethod[] getMethods() { return meth; }
532         public int getModifiers() { return c.getModifiers(); }
533
534         public boolean isBinaryType() { return true; }
535         public boolean isClass() { return true; }
536         public boolean isInterface() { return c.isInterface(); }
537         public boolean isAnonymous() { return false; }
538         public boolean isLocal() { return false; } // FIXME
539         public boolean isMember() { return false; } // FIXME
540         public char[] sourceFileName() { return null; }
541         public char[] getFileName() { return null; }
542
543         public boolean equals(Object o) {
544             return o == this || super.equals(o) ||
545                    (o != null && o instanceof LoadedClass &&
546                     c.equals(((LoadedClass)o).c));
547         }
548     }
549
550
551     // Compiler Parameters ////////////////////////////////////////////////////
552
553     /** Used by compiler to resolve classes. */
554     final INameEnvironment env = new INameEnvironment() {
555         public NameEnvironmentAnswer findType(char[][] c) { return findType(name(c), pack(c)); }
556         public NameEnvironmentAnswer findType(char[] n, char[][] p) {
557             if (veryverbose) System.out.print("findType: "+ str(p, '.') + "."+new String(n));
558
559             try {
560                 Class c = Class.forName(str(p, '.') + '.' + new String(n));
561                 if (veryverbose) System.out.println("  found in classloader: "+ c);
562                 IBinaryType b = (IBinaryType)loaded.get(c);
563                 if (b == null) loaded.put(c, b = new LoadedClass(c));
564                 return new NameEnvironmentAnswer(b);
565             } catch (ClassNotFoundException e) {}
566
567             // cut out searches for java.* packages in sources list
568             if (p.length > 0 && eq(p[0], "java".toCharArray())) {
569                 if (veryverbose) System.out.println("  not found, unknown java.*");
570                 return null;
571             }
572
573             try {
574                 for (int i=0; i < sources.length; i++) {
575                     Source s = sources[i];
576                     if (eq(n, s.n) && eq(p, s.p)) {
577                         if (s.reader != null) {
578                             if (veryverbose) System.out.println("  found reader");
579                             return new NameEnvironmentAnswer(s.reader);
580                         }
581                         if (s.compiled != null) {
582                             if (veryverbose) System.out.println("  found compiled, new reader");
583                             s.reader = new ClassFileReader(s.compiled,
584                                 s.orig.getName().toCharArray(), true);
585                             return new NameEnvironmentAnswer(s.reader);
586                         }
587                         if (veryverbose) System.out.println("  found unit");
588                         return new NameEnvironmentAnswer(sources[i].unit);
589                     }
590                 }
591             } catch (ClassFormatException e) {
592                 System.out.println("Unexpected ClassFormatException"); // FIXME
593                 e.printStackTrace(); return null;
594             }
595             if (veryverbose) System.out.println("  not found");
596             return null;
597         }
598         public boolean isPackage(char[][] parent, char[] name) {
599             if (veryverbose) System.out.println("isPackage: "+ str(parent, '.') + "."+new String(name));
600             String parentName = str(parent, '/');
601             for (int i=0; i < sources.length; i++) {
602                 if (eq(name, sources[i].n) && eq(parent, sources[i].p)) return false;
603                 if (eq(pack(sources[i].p), parent) && eq(name(sources[i].p), name)) return true;
604             }
605             return
606                 loader.getResource(parentName + ".class") == null &&
607                 loader.getResource(parentName + '/' + new String(name) + ".class") == null;
608         }
609         public void cleanup() {}
610     };
611
612     /** Used by compiler to decide what do with problems.. */
613     private final IErrorHandlingPolicy policy =
614         DefaultErrorHandlingPolicies.proceedWithAllProblems();
615
616     /** Used by compiler for general options. */
617     private final Map settings = new HashMap();
618     {
619         settings.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE);
620         settings.put(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE);
621         settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_5);
622         settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_1);
623     };
624
625     /** Used by compiler for processing compiled classes and their errors. */
626     private final ICompilerRequestor results = new ICompilerRequestor() {
627         public void acceptResult(CompilationResult result) {
628             if (veryverbose) System.out.println("got result: "+result);
629             if (result.hasProblems()) {
630                 boolean err = false;
631                 IProblem[] p = result.getProblems();
632                 PrintWriter o;
633                 for (int i=0; i < p.length; i++) {
634                     if (p[i].isError()) { o = out; err = true; }
635                     else o = warn;
636
637                     o.print(p[i].getOriginatingFileName());
638                     o.print(':');
639                     o.print(p[i].getSourceLineNumber());
640                     o.print(':');
641                     o.print(p[i].isError() ? " error: " : " warning: ");
642                     o.println(p[i].getMessage());
643                 }
644                 out.flush();
645                 if (err) { hasErrors = true; return; }
646             }
647
648             ClassFile[] c = result.getClassFiles();
649             for (int i=0; i < c.length; i++) {
650                 try {
651                     char[][] name = c[i].getCompoundName();
652                     if (verbose) {
653                         String pct = "";
654                         /*+ percent;
655                         percent++;
656                         while (pct.length() < 2) pct = " " + pct;
657                         pct = "(" + pct + "%) ";
658                         */
659                         String printme = " writing: " + pct + str(pack(name),'.') + "." + new String(name(name));
660                         if (clearing.length() < printme.length()) clearing = "";
661                         else clearing = clearing.substring(printme.length());
662                         System.out.print(printme + clearing + "\r");
663                         for(clearing = ""; clearing.length() < printme.length() + 5; clearing += " ");
664                     }
665                     if (buildzip) {
666                         try {
667                             jarfile.putNextEntry(new ZipEntry(str(pack(name), '/') + "/" + new String(name(name)) + ".class"));
668                             jarfile.write(c[i].getBytes());
669                         } catch (java.util.zip.ZipException ze) {
670                             // HACK: horrendous hack
671                             if (ze.getMessage().indexOf("duplicate entry") != -1) {
672                                 //System.out.println("compiler emitted class twice: " + new String(name(name)));
673                             } else {
674                                 throw ze;
675                             }
676                         }
677                     } else {
678                         // build package path to new class file
679                         File path = new File(builddir, str(pack(name), '/'));
680                         if (!path.exists()) path.mkdirs();
681                         // write new class file
682                         path = new File(path, new String(name(name)) + ".class");
683                         OutputStream o = new BufferedOutputStream(new FileOutputStream(path));
684                         o.write(c[i].getBytes());
685                         o.close();
686                     }
687                 } catch (IOException e) {
688                     System.out.println("IOException writing class"); // FIXME
689                     e.printStackTrace();
690                 }
691             }
692         }
693     };
694
695     int percent = 0;
696     String clearing = "";
697
698     /** Problem creater for compiler. */
699     private final IProblemFactory problems = new DefaultProblemFactory();
700
701
702     // Helper Functiosn ///////////////////////////////////////////////////////
703
704     /** Convert source file path into class name block.
705      *  eg. in:  java/lang/String.java -> { {java} {lang} {String} } */
706     private char[][] classname(String name) {
707         String delim = name.indexOf('/') == -1 ? "." : "/";
708         name = name.trim();
709         if (name.endsWith(".java")) name = name.substring(0, name.length() - 5);
710         if (name.endsWith(".class")) name = name.substring(0, name.length() - 6);
711         if (name.startsWith(delim)) name = name.substring(1);
712
713         StringTokenizer st = new StringTokenizer(name, delim);
714         char[][] n = new char[st.countTokens()][];
715         for (int i=0; st.hasMoreTokens(); i++) n[i] = st.nextToken().toCharArray();
716         return n;
717     }
718
719     /** Convert class name into a String. */
720     private static String str(char[][] name, char delim) {
721         StringBuffer b = new StringBuffer();
722         for (int i=0; name != null && i < name.length; i++) {
723             if (name[i] == null || name[i].length == 0) continue;
724             if (i > 0) b.append(delim);
725             b.append(name[i]);
726         }
727         return b.toString();
728     }
729
730     /** Returns the package component of a class name.
731      *  Effectively returns char[length - 1][].  */
732     private static char[][] pack(char[][] c) {
733         char[][] p = new char[c.length - 1][];
734         for (int i=0; i < p.length; i++) p[i] = c[i];
735         return p;
736     }
737
738     /** Returns the direct-name component of a class name.
739      *  eg. String from java.lang.String */
740     private static char[] name(char[][] c) { return c[c.length - 1]; }
741
742     /** Returns true of contents of both char arrays are equal. */
743     private static boolean eq(char[][] c1, char[][] c2) {
744         if (c1 == null || c2 == null) return c1 == c2;
745         if (c1.length != c2.length) return false;
746         for (int i=0; i < c1.length; i++) if (!eq(c1[i], c2[i])) return false;
747         return true;
748     }
749
750     /** Returns true of contents of both char arrays are equal. */
751     private static boolean eq(char[] c1, char[] c2) {
752         if (c1 == null || c2 == null) return c1 == c2;
753         if (c1.length != c2.length) return false;
754         for (int i=0; i < c1.length; i++) if (c1[i] != c2[i]) return false;
755         return true;
756     }
757
758     /** Returns class name as per VM Spec 4.2. eg. java/lang/String */
759     private static char[] name(Class c) {
760         return c == null ? null : c.getName().replace('.', '/').toCharArray();
761     }
762
763     /** Returns the type name of a class as per VM Spec 4.3.2. */
764     private static char[] typeName(Class p) {
765         StringBuffer sb = new StringBuffer();
766         typeName(p, sb);
767         return sb.toString().toCharArray();
768     }
769
770     /** Returns the type name of a class as per VM Spec 4.3.2.
771      *  eg. int -> I, String -> Ljava/lang/String; */
772     private static void typeName(Class p, StringBuffer sb) {
773         String name = p.getName();
774         switch (name.charAt(0)) {
775             case 'B': case 'C': case 'D': case 'F': case 'I':
776             case 'J': case 'S': case 'Z': case 'V': case '[':
777                 sb.append(name(p)); break;
778
779             case 'b': if (name.equals("boolean")) { sb.append('Z'); break; }
780                       if (name.equals("byte"))    { sb.append('B'); break; }
781             case 'c': if (name.equals("char"))    { sb.append('C'); break; }
782             case 'd': if (name.equals("double"))  { sb.append('D'); break; }
783             case 'f': if (name.equals("float"))   { sb.append('F'); break; }
784             case 'i': if (name.equals("int"))     { sb.append('I'); break; }
785             case 'l': if (name.equals("long"))    { sb.append('J'); break; }
786             case 's': if (name.equals("short"))   { sb.append('S'); break; }
787             case 'v': if (name.equals("void"))    { sb.append('V'); break; }
788             default:
789                 sb.append('L'); sb.append(name(p)); sb.append(';');
790         }
791     }
792
793     /** Returns the descriptor of a method per VM Spec 4.3.3.
794      *  eg. int get(String n, boolean b) -> (Ljava/lang/String;B)I */
795     private static char[] descriptor(Class[] p, Class r) {
796         StringBuffer sb = new StringBuffer();
797         sb.append('(');
798         if (p != null) for (int i=0; i < p.length; i++) typeName(p[i], sb);
799         sb.append(')');
800         if (r != null) typeName(r, sb);
801         return sb.toString().toCharArray();
802     }
803
804 }