import eclipse 3.1 M4 compiler
[org.ibex.tool.git] / src / org / ibex / tool / Compiler.java
1 package org.ibex.tool;
2
3 import java.io.*;
4 import java.util.*;
5 import java.util.zip.*;
6 import java.util.jar.*;
7
8 import java.lang.reflect.*;
9
10 import org.eclipse.jdt.core.compiler.IProblem;
11 import org.eclipse.jdt.internal.compiler.ClassFile;
12 import org.eclipse.jdt.internal.compiler.CompilationResult;
13 //import org.eclipse.jdt.internal.compiler.Compiler;
14 import org.eclipse.jdt.internal.compiler.DefaultErrorHandlingPolicies;
15 import org.eclipse.jdt.internal.compiler.ICompilerRequestor;
16 import org.eclipse.jdt.internal.compiler.IErrorHandlingPolicy;
17 import org.eclipse.jdt.internal.compiler.IProblemFactory;
18 import org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader;
19 import org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException;
20 import org.eclipse.jdt.internal.compiler.env.*;
21 import org.eclipse.jdt.internal.compiler.impl.*;
22 import org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory;
23
24 // FEATURE: add build dependencies like make (grab some Java dependency-checker code off the net?)
25
26 public class Compiler {
27     // Static Entry Point /////////////////////////////////////////////////////
28
29     public static void main(String[] args) throws IOException {
30         boolean verbose = false, veryverbose = false, warnings = true;
31         List srcdir = new ArrayList();
32         String source = null, target = null, blddir = null, mainclass = null;
33         boolean buildjar = false;
34
35         if (args.length == 0) args = new String[] { "--help" };
36         for (int i=0; i < args.length; i++) {
37             if (args[i].charAt(0) == '-') {
38                 if (args[i].length() == 1) {
39                     System.out.println("Illegal switch: -"); return; }
40                 switch (args[i].charAt(1)) {
41                     case '-':
42                         if (args[i].equals("--help")) printHelp();
43                         else System.out.println("Unknown switch: -");
44                         return;
45                     case 'd':
46                         if (i == args.length - 1) {
47                             System.out.println("Missing parameter: "+args[i]); return; }
48                         if (blddir != null) { System.out.println("cannot specify both -d and -j"); return; }
49                         blddir = args[++i];
50                         break;
51                     case 'j':
52                         if (i == args.length - 1) {
53                             System.out.println("Missing parameter: "+args[i]); return; }
54                         if (blddir != null) { System.out.println("cannot specify both -d and -j"); return; }
55                         blddir = args[++i];
56                         buildjar = true;
57                         break;
58                     case 'm':
59                         if (i == args.length - 1) {
60                             System.out.println("Missing parameter: "+args[i]); return; }
61                         mainclass = args[++i];
62                         break;
63                     case 'w':
64                         if (i == args.length - 1) {
65                             System.out.println("Missing parameter: "+args[i]); return; }
66                         warnings = false;
67                         break;
68                     case 's':
69                         if (i == args.length - 1) {
70                             System.out.println("Missing parameter: "+args[i]); return; }
71                         source = args[++i];
72                         break;
73                     case 't':
74                         if (i == args.length - 1) {
75                             System.out.println("Missing parameter: "+args[i]); return; }
76                         target = args[++i];
77                         break;
78                     case 'v':
79                         verbose = true;
80                         break;
81                     case 'V':
82                         veryverbose = true;
83                         break;
84                     case 'h':
85                         printHelp(); return;
86
87                 }
88             } else srcdir.add(args[i]);
89         }
90
91         Compiler c = new Compiler();
92         if (blddir != null) {
93             if (buildjar) c.setBuildJar(blddir);
94             else          c.setBuildDir(blddir);
95         }
96         if (source != null) c.setSource(source);
97         if (target != null) c.setTarget(target);
98         if (mainclass != null) c.setMainClass(mainclass);
99
100         String[] s = new String[srcdir.size()];
101         srcdir.toArray(s);
102         c.setSourceDirs(s);
103
104         c.setVerbose(verbose);
105         c.setWarnings(warnings);
106         c.setVeryVerbose(veryverbose);
107         c.compile();
108     }
109     private static void printHelp() {
110         System.out.println("Usage java -cp ... org.ibex.tool.Compiler [options] <source dir> ...");
111         System.out.println("Options:");
112         System.out.println("  -d <directory>   Directory to put generated class files in");
113         System.out.println("  -j <jarfile>     Jar file to put generated class files in");
114         System.out.println("     -m <class>    Main-Class for jar file.");
115         System.out.println("  -s <release>     Compile with specified source compatibility.");
116         System.out.println("  -t <release>     Compile with specified class file compatibility.");
117         System.out.println("  -v               Verbose output.");
118         System.out.println("  -V               Very Verbose output.");
119         System.out.println("  -h or --help     Print this message.");
120         System.out.println("");
121     }
122
123
124     // Compiler Interface /////////////////////////////////////////////////////
125
126     private ClassLoader loader = ClassLoader.getSystemClassLoader();
127     private Map loaded = new HashMap();
128     private PrintWriter out = new PrintWriter(System.out);
129     private Preprocessor preprocessor;
130
131     private Source[] sources;
132
133     private File builddir = null;
134     private boolean buildzip = false;
135     private ZipOutputStream jarfile = null;
136     private String mainclass = null;
137
138     private String[] sourcedirs = new String[0];
139
140     private PrintWriter warn;
141     private boolean hasErrors;
142     private boolean verbose = false;
143     private boolean veryverbose = false;
144     private boolean warnings = true;
145
146     public Compiler() {
147         List defs = Collections.EMPTY_LIST;
148
149         String define = System.getProperty("org.ibex.tool.preprocessor.define");
150         if (define != null) {
151             defs = new ArrayList();
152             StringTokenizer st = new StringTokenizer(define.toUpperCase(), ",");
153             while (st.hasMoreTokens()) defs.add(st.nextToken().trim());
154         }
155
156         preprocessor = new Preprocessor(null, null, defs);
157     }
158
159     public void setMainClass(String mainclass) { this.mainclass = mainclass; }
160     public void setBuildJar(String dir) throws IOException {
161         builddir = new File(dir == null ? "." : dir);
162         buildzip = true;
163     }
164     public void setBuildDir(String dir) throws IOException {
165         builddir = new File(dir == null ? "." : dir);
166     }
167
168     public void setSourceDirs(String[] dir) { sourcedirs = dir; }
169
170     /** Pass CompilerOptions.VERSION_1_*. A String of form "1.1", ".2", etc. */
171     public void setSource(String v) {
172         if (v.equals("1.1")) settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_1);
173         else if (v.equals("1.2")) settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_2);
174         else if (v.equals("1.3")) settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_3);
175         else if (v.equals("1.4")) settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_4);
176         else if (v.equals("1.5")) settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_5);
177         else throw new RuntimeException("I have no idea what Java " + v + " is.  Ask David Crawshaw.");
178     }
179
180     /** Pass CompilerOptions.VERSION_1_*. A String of form "1.1", ".2", etc. */
181     public void setTarget(String v) {
182         if (v.equals("1.1")) settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_1);
183         else if (v.equals("1.2")) settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_2);
184         else if (v.equals("1.3")) settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_3);
185         else if (v.equals("1.4")) settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_4);
186         else if (v.equals("1.5")) settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_5);
187         else throw new RuntimeException("I have no idea what Java " + v + " is.  Ask David Crawshaw.");
188     }
189
190     public void setVerbose(boolean v) { verbose = v; }
191     public void setVeryVerbose(boolean v) { veryverbose = v; }
192     public void setWarnings(boolean w) { warnings = w; }
193
194     public void compile() throws IOException {
195         List s = new ArrayList();
196
197         if (buildzip) {
198             Manifest m = new Manifest();
199             m.getMainAttributes().putValue("Manifest-Version", "1.0");
200             if (mainclass != null) m.getMainAttributes().putValue("Main-Class", mainclass);
201             jarfile = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(builddir)), m);
202         }
203         for (int i=0; i < sourcedirs.length; i++) {
204             File src = new File(sourcedirs[i]);
205             if (!src.exists()) {
206                 if (veryverbose) System.out.println("source directory not found: "+sourcedirs[i]);
207                 continue;
208             }
209             filterSources(s, src, new char[0][], sourcedirs[i]);
210         }
211
212         if (veryverbose) System.out.println("working with "+s.size() +" sources");
213         sources = new Source[s.size()]; s.toArray(sources);
214         ICompilationUnit[] units = new ICompilationUnit[s.size()];
215         int u = 0; for (int i=0; i < sources.length; i++)
216             if (sources[i].compiled == null) units[u++] = sources[i].unit;
217         if (u != units.length) {
218             ICompilationUnit[] newu = new ICompilationUnit[u];
219             System.arraycopy(units, 0, newu, 0, u);
220             units = newu;
221         }
222
223         hasErrors = false;
224
225         StringWriter sw = new StringWriter();
226         StringBuffer w = sw.getBuffer();
227         warn = new PrintWriter(sw);
228
229         org.eclipse.jdt.internal.compiler.Compiler jdt =
230             new org.eclipse.jdt.internal.compiler.Compiler(
231                 env, policy, settings, results, problems);
232         jdt.compile(units);
233
234         if (warnings && !hasErrors) { out.write(w.toString()); out.flush(); }
235         warn = null;
236         try {
237             if (jarfile != null) jarfile.close();
238         } catch (Exception e) {
239             e.printStackTrace();
240         }
241         if (verbose) System.out.print(clearing + "   \r");
242     }
243
244     private final FilenameFilter filterSrcs = new FilenameFilter() {
245         public boolean accept(File dir, String name) { return name.endsWith(".java"); }
246     };
247     private final FileFilter filterDirs = new FileFilter() {
248         public boolean accept(File path) { return path.isDirectory(); }
249     };
250     private byte[] bytes(File bfile) {
251         byte[] bytes = new byte[2 * 1024];
252         int pos = 0, in = 0;
253         try {
254             InputStream bin = new FileInputStream(bfile);
255             while ((in = bin.read(bytes, pos, bytes.length - pos)) != -1) {
256                 pos += in;
257                 if (pos == bytes.length) {
258                     byte[] newbytes= new byte[pos * 2];
259                     System.arraycopy(bytes, 0, newbytes, 0, pos);
260                     bytes = newbytes;
261                 }
262             }
263             bin.close();
264         } catch (IOException e) {
265             System.out.println("Error reading class file"); // FIXME
266             e.printStackTrace(); return null;
267         }
268
269         if (pos != bytes.length) {
270             byte[] newbytes= new byte[pos * 2];
271             System.arraycopy(bytes, 0, newbytes, 0, pos);
272             bytes = newbytes;
273         }
274
275         return bytes;
276     }
277     private void filterSources(List s, File dir, char[][] pack, String srcdir) {
278         List bclasses = new ArrayList();
279         File bdir = new File(builddir, str(pack, File.separatorChar));
280
281         // add the java files in this directory
282         File[] ja = dir.listFiles(filterSrcs);
283         for (int i=0; i < ja.length; i++) {
284             char[] n = name(classname(ja[i].getName()));
285             Source src = new Source(ja[i], n, pack, srcdir);
286
287             // skip the file if the build version is newer than the source
288             String bclass = new String(n);
289             File bfile = new File(bdir, bclass + ".class");
290             if (bfile.lastModified() > ja[i].lastModified()) {
291                 src.compiled = bytes(bfile);
292                 bclasses.add(bclass);
293             }
294
295             s.add(src);
296         }
297
298         // process the inner classes of any binary files
299         for (int i=0; i < bclasses.size(); i++) {
300             final String bc = (String)bclasses.get(i);
301             final FilenameFilter f = new FilenameFilter() {
302                 public boolean accept(File dir, String name) {
303                     return name.length() > bc.length() && name.startsWith(bc) &&
304                            name.charAt(bc.length()) == '$' && name.endsWith(".class");
305                 }
306             };
307             File[] bfile = bdir.listFiles(f);
308             for (int j=0; j < bfile.length; j++) {
309                 Source src = new Source(bfile[j],
310                     name(classname(bfile[j].getName())), pack, srcdir);
311                 src.compiled = bytes(bfile[j]);
312                 s.add(src);
313             }
314         }
315
316         // add the subdirectories as packages
317         File[] d = dir.listFiles(filterDirs);
318         for (int i=0; i < d.length; i++) {
319             char[][] newpack = new char[pack.length + 1][];
320             for (int j=0; j < pack.length; j++) newpack[j] = pack[j];
321             newpack[pack.length] = d[i].getName().toCharArray();
322             filterSources(s, d[i], newpack, srcdir);
323         }
324     }
325
326
327     /** Represents a file to be compiled. */
328     final class Source {
329         char[] fileName;
330         char[] n; char[][] p;
331         File orig;
332         char[] processed = null;
333         byte[] compiled = null;
334         ClassFileReader reader = null;
335
336         final ICompilationUnit unit = new ICompilationUnit() {
337             public char[] getMainTypeName() { return n; }
338             public char[][] getPackageName() { return p; }
339             public char[] getFileName() { return fileName; }
340             public char[] getContents() {
341                 if (processed != null) return processed;
342
343                 try {
344                     Reader r = new InputStreamReader(new BufferedInputStream(
345                                new FileInputStream(orig)));
346                     StringWriter w = new StringWriter();
347                     Vector err;
348
349                     synchronized (preprocessor) {
350                         preprocessor.setReader(r);
351                         preprocessor.setWriter(w);
352                         err = preprocessor.process();
353                     }
354
355                     if (err.size() > 0) {
356                         for (int i=0; i < err.size(); i++) {
357                             Preprocessor.Warning warn = (Preprocessor.Warning)err.get(i);
358                             out.print(getFileName());
359                             out.print(':');
360                             out.print(warn.getLine());
361                             out.print(':');
362                             out.print(warn instanceof Preprocessor.Error ?
363                                       " error: " : " warning: ");
364                             out.println(warn.getMessage());
365                         }
366                         return null;
367                     }
368
369                     processed  = w.toString().toCharArray();
370                 } catch (IOException e) {
371                     System.out.println("IOException: "+e); // FIXME
372                     return null;
373                 }
374
375                 return processed;
376             }
377         };
378
379         private Source(File o, char[] n, char[][] p, String srcdir) {
380             orig = o; this.n = n; this.p = p;
381             String file = srcdir;
382             file += File.separatorChar +  str(p, File.separatorChar);
383             file += File.separatorChar + new String(n) + ".java";
384             fileName = file.toCharArray();
385         }
386     }
387
388     // Compiler Parameters ////////////////////////////////////////////////////
389
390     // FEATURE: may be able to use this to block access to APIs generated for stack objects
391     final AccessRestriction access = new AccessRestriction(null, null, null, null);
392
393     /** Used by compiler to resolve classes. */
394     final INameEnvironment env = new INameEnvironment() {
395         public NameEnvironmentAnswer findType(char[][] c) { return findType(name(c), pack(c)); }
396         public NameEnvironmentAnswer findType(char[] n, char[][] p) {
397             if (veryverbose) System.out.print("findType: "+ str(p, '.') + "."+new String(n));
398
399             try {
400                 String classname = new String(n);
401                 Class c = Class.forName(str(p, '.') + '.' + classname);
402                 if (veryverbose) System.out.println("  found in classloader: "+ c);
403                 IBinaryType b = (IBinaryType)loaded.get(c);
404                 if (b == null) loaded.put(c, b = new ClassFileReader(
405                     read(c.getResourceAsStream(classname)),
406                     (str(p, '/') + '/' + classname).toCharArray()));
407                 return new NameEnvironmentAnswer(b, access);
408             } catch (ClassNotFoundException e) {
409             } catch (ClassFormatException e) {
410                 e.printStackTrace();
411                 throw new Error("ClassFormatException reading system class: " +
412                     str(p, '.')+new String(n));
413             } catch (IOException e) {
414                 e.printStackTrace();
415                 throw new Error("IOException reading system class: "+str(p, '.')+new String(n));
416             }
417
418             // cut out searches for java.* packages in sources list
419             if (p.length > 0 && eq(p[0], "java".toCharArray())) {
420                 if (veryverbose) System.out.println("  not found, unknown java.*");
421                 return null;
422             }
423
424             try {
425                 for (int i=0; i < sources.length; i++) {
426                     Source s = sources[i];
427                     if (eq(n, s.n) && eq(p, s.p)) {
428                         if (s.reader != null) {
429                             if (veryverbose) System.out.println("  found reader");
430                             return new NameEnvironmentAnswer(s.reader, access);
431                         }
432                         if (s.compiled != null) {
433                             if (veryverbose) System.out.println("  found compiled, new reader");
434                             s.reader = new ClassFileReader(s.compiled,
435                                 s.orig.getName().toCharArray());
436                             return new NameEnvironmentAnswer(s.reader, access);
437                         }
438                         if (veryverbose) System.out.println("  found unit");
439                         return new NameEnvironmentAnswer(sources[i].unit, access);
440                     }
441                 }
442             } catch (ClassFormatException e) {
443                 System.out.println("Unexpected ClassFormatException"); // FIXME
444                 e.printStackTrace(); return null;
445             }
446             if (veryverbose) System.out.println("  not found");
447             return null;
448         }
449         public boolean isPackage(char[][] parent, char[] name) {
450             if (veryverbose) System.out.println("isPackage: "+ str(parent, '.') + "."+new String(name));
451             String parentName = str(parent, '/');
452             for (int i=0; i < sources.length; i++) {
453                 if (eq(name, sources[i].n) && eq(parent, sources[i].p)) return false;
454                 if (eq(pack(sources[i].p), parent) && eq(name(sources[i].p), name)) return true;
455             }
456             return
457                 loader.getResource(parentName + ".class") == null &&
458                 loader.getResource(parentName + '/' + new String(name) + ".class") == null;
459         }
460         public void cleanup() {}
461     };
462
463     /** Used by compiler to decide what do with problems.. */
464     private final IErrorHandlingPolicy policy =
465         DefaultErrorHandlingPolicies.proceedWithAllProblems();
466
467     /** Used by compiler for general options. */
468     private final Map settings = new HashMap();
469     {
470         settings.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE);
471         settings.put(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE);
472         settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_5);
473         settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_1);
474     };
475
476     /** Used by compiler for processing compiled classes and their errors. */
477     private final ICompilerRequestor results = new ICompilerRequestor() {
478         public void acceptResult(CompilationResult result) {
479             if (veryverbose) System.out.println("got result: "+result);
480             if (result.hasProblems()) {
481                 boolean err = false;
482                 IProblem[] p = result.getProblems();
483                 PrintWriter o;
484                 for (int i=0; i < p.length; i++) {
485                     if (p[i].isError()) { o = out; err = true; }
486                     else o = warn;
487
488                     o.print(p[i].getOriginatingFileName());
489                     o.print(':');
490                     o.print(p[i].getSourceLineNumber());
491                     o.print(':');
492                     o.print(p[i].isError() ? " error: " : " warning: ");
493                     o.println(p[i].getMessage());
494                 }
495                 out.flush();
496                 if (err) { hasErrors = true; return; }
497             }
498
499             ClassFile[] c = result.getClassFiles();
500             for (int i=0; i < c.length; i++) {
501                 try {
502                     char[][] name = c[i].getCompoundName();
503                     if (verbose) {
504                         String pct = "";
505                         /*+ percent;
506                         percent++;
507                         while (pct.length() < 2) pct = " " + pct;
508                         pct = "(" + pct + "%) ";
509                         */
510                         String printme = " writing: " + pct + str(pack(name),'.') + "." + new String(name(name));
511                         if (clearing.length() < printme.length()) clearing = "";
512                         else clearing = clearing.substring(printme.length());
513                         System.out.print(printme + clearing + "\r");
514                         for(clearing = ""; clearing.length() < printme.length() + 5; clearing += " ");
515                     }
516                     if (buildzip) {
517                         try {
518                             jarfile.putNextEntry(new ZipEntry(str(pack(name), '/') + "/" + new String(name(name)) + ".class"));
519                             jarfile.write(c[i].getBytes());
520                         } catch (java.util.zip.ZipException ze) {
521                             // HACK: horrendous hack
522                             if (ze.getMessage().indexOf("duplicate entry") != -1) {
523                                 //System.out.println("compiler emitted class twice: " + new String(name(name)));
524                             } else {
525                                 throw ze;
526                             }
527                         }
528                     } else {
529                         // build package path to new class file
530                         File path = new File(builddir, str(pack(name), '/'));
531                         if (!path.exists()) path.mkdirs();
532                         // write new class file
533                         path = new File(path, new String(name(name)) + ".class");
534                         OutputStream o = new BufferedOutputStream(new FileOutputStream(path));
535                         o.write(c[i].getBytes());
536                         o.close();
537                     }
538                 } catch (IOException e) {
539                     System.out.println("IOException writing class"); // FIXME
540                     e.printStackTrace();
541                 }
542             }
543         }
544     };
545
546     int percent = 0;
547     String clearing = "";
548
549     /** Problem creater for compiler. */
550     private final IProblemFactory problems = new DefaultProblemFactory();
551
552
553     // Helper Functiosn ///////////////////////////////////////////////////////
554
555     /** Convert source file path into class name block.
556      *  eg. in:  java/lang/String.java -> { {java} {lang} {String} } */
557     private static char[][] classname(String name) {
558         String delim = name.indexOf('/') == -1 ? "." : "/";
559         name = name.trim();
560         if (name.endsWith(".java")) name = name.substring(0, name.length() - 5);
561         if (name.endsWith(".class")) name = name.substring(0, name.length() - 6);
562         if (name.startsWith(delim)) name = name.substring(1);
563
564         StringTokenizer st = new StringTokenizer(name, delim);
565         char[][] n = new char[st.countTokens()][];
566         for (int i=0; st.hasMoreTokens(); i++) n[i] = st.nextToken().toCharArray();
567         return n;
568     }
569
570     /** Convert class name into a String. */
571     private static String str(char[][] name, char delim) {
572         StringBuffer b = new StringBuffer();
573         for (int i=0; name != null && i < name.length; i++) {
574             if (name[i] == null || name[i].length == 0) continue;
575             if (i > 0) b.append(delim);
576             b.append(name[i]);
577         }
578         return b.toString();
579     }
580
581     /** Returns the package component of a class name.
582      *  Effectively returns char[length - 1][].  */
583     private static char[][] pack(char[][] c) {
584         char[][] p = new char[c.length - 1][];
585         for (int i=0; i < p.length; i++) p[i] = c[i];
586         return p;
587     }
588
589     /** Returns the direct-name component of a class name.
590      *  eg. String from java.lang.String */
591     private static char[] name(char[][] c) { return c[c.length - 1]; }
592
593     /** Returns true of contents of both char arrays are equal. */
594     private static boolean eq(char[][] c1, char[][] c2) {
595         if (c1 == null || c2 == null) return c1 == c2;
596         if (c1.length != c2.length) return false;
597         for (int i=0; i < c1.length; i++) if (!eq(c1[i], c2[i])) return false;
598         return true;
599     }
600
601     /** Returns true of contents of both char arrays are equal. */
602     private static boolean eq(char[] c1, char[] c2) {
603         if (c1 == null || c2 == null) return c1 == c2;
604         if (c1.length != c2.length) return false;
605         for (int i=0; i < c1.length; i++) if (c1[i] != c2[i]) return false;
606         return true;
607     }
608
609     /** Returns class name as per VM Spec 4.2. eg. java/lang/String */
610     private static char[] name(Class c) {
611         return c == null ? null : c.getName().replace('.', '/').toCharArray();
612     }
613
614     /** Returns the type name of a class as per VM Spec 4.3.2. */
615     private static char[] typeName(Class p) {
616         StringBuffer sb = new StringBuffer();
617         typeName(p, sb);
618         return sb.toString().toCharArray();
619     }
620
621     /** Returns the type name of a class as per VM Spec 4.3.2.
622      *  eg. int -> I, String -> Ljava/lang/String; */
623     private static void typeName(Class p, StringBuffer sb) {
624         String name = p.getName();
625         switch (name.charAt(0)) {
626             case 'B': case 'C': case 'D': case 'F': case 'I':
627             case 'J': case 'S': case 'Z': case 'V': case '[':
628                 sb.append(name(p)); break;
629
630             case 'b': if (name.equals("boolean")) { sb.append('Z'); break; }
631                       if (name.equals("byte"))    { sb.append('B'); break; }
632             case 'c': if (name.equals("char"))    { sb.append('C'); break; }
633             case 'd': if (name.equals("double"))  { sb.append('D'); break; }
634             case 'f': if (name.equals("float"))   { sb.append('F'); break; }
635             case 'i': if (name.equals("int"))     { sb.append('I'); break; }
636             case 'l': if (name.equals("long"))    { sb.append('J'); break; }
637             case 's': if (name.equals("short"))   { sb.append('S'); break; }
638             case 'v': if (name.equals("void"))    { sb.append('V'); break; }
639             default:
640                 sb.append('L'); sb.append(name(p)); sb.append(';');
641         }
642     }
643
644     /** Returns the descriptor of a method per VM Spec 4.3.3.
645      *  eg. int get(String n, boolean b) -> (Ljava/lang/String;B)I */
646     private static char[] descriptor(Class[] p, Class r) {
647         StringBuffer sb = new StringBuffer();
648         sb.append('(');
649         if (p != null) for (int i=0; i < p.length; i++) typeName(p[i], sb);
650         sb.append(')');
651         if (r != null) typeName(r, sb);
652         return sb.toString().toCharArray();
653     }
654
655     private static byte[] read(InputStream in) throws IOException {
656         byte[] bytes = new byte[16];
657         int off = 0, ret;
658         while ((ret = in.read(bytes, off, bytes.length - off)) != -1) {
659             off += ret;
660             if (off == bytes.length) {
661                 byte[] nb = new byte[bytes.length * 2];
662                 System.arraycopy(bytes, 0, nb, 0, bytes.length);
663                 bytes = nb;
664             }
665         }
666         if (off != bytes.length) {
667             byte[] nb = new byte[off];
668             System.arraycopy(bytes, 0, nb, 0, off);
669             bytes = nb;
670         }
671         return bytes;
672     }
673
674 }