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