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