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