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