bf1ad56557626ef0224cec6600090fcc99dc584c
[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
251     private void filterSources(List s, File dir, char[][] pack, String srcdir) {
252         List bclasses = new ArrayList();
253         File bdir = new File(builddir, str(pack, File.separatorChar));
254
255         // add the java files in this directory
256         File[] ja = dir.listFiles(filterSrcs);
257         for (int i=0; i < ja.length; i++) {
258             char[] n = name(classname(ja[i].getName()));
259             Source src = new Source(ja[i], n, pack, srcdir);
260
261             // skip the file if the build version is newer than the source
262             String bclass = new String(n);
263             File bfile = new File(bdir, bclass + ".class");
264             if (bfile.lastModified() > ja[i].lastModified()) {
265                 src.compiled = bytes(bfile);
266                 bclasses.add(bclass);
267             }
268
269             s.add(src);
270         }
271
272         // process the inner classes of any binary files
273         for (int i=0; i < bclasses.size(); i++) {
274             final String bc = (String)bclasses.get(i);
275             final FilenameFilter f = new FilenameFilter() {
276                 public boolean accept(File dir, String name) {
277                     return name.length() > bc.length() && name.startsWith(bc) &&
278                            name.charAt(bc.length()) == '$' && name.endsWith(".class");
279                 }
280             };
281             File[] bfile = bdir.listFiles(f);
282             for (int j=0; j < bfile.length; j++) {
283                 Source src = new Source(bfile[j],
284                     name(classname(bfile[j].getName())), pack, srcdir);
285                 src.compiled = bytes(bfile[j]);
286                 s.add(src);
287             }
288         }
289
290         // add the subdirectories as packages
291         File[] d = dir.listFiles(filterDirs);
292         for (int i=0; i < d.length; i++) {
293             char[][] newpack = new char[pack.length + 1][];
294             for (int j=0; j < pack.length; j++) newpack[j] = pack[j];
295             newpack[pack.length] = d[i].getName().toCharArray();
296             filterSources(s, d[i], newpack, srcdir);
297         }
298     }
299
300
301     /** Represents a file to be compiled. */
302     final class Source {
303         char[] fileName;
304         char[] n; char[][] p;
305         File orig;
306         char[] processed = null;
307         byte[] compiled = null;
308         ClassFileReader reader = null;
309
310         final ICompilationUnit unit = new ICompilationUnit() {
311             public char[] getMainTypeName() { return n; }
312             public char[][] getPackageName() { return p; }
313             public char[] getFileName() { return fileName; }
314             public char[] getContents() {
315                 if (processed != null) return processed;
316
317                 try {
318                     Reader r = new InputStreamReader(new BufferedInputStream(
319                                new FileInputStream(orig)));
320                     StringWriter w = new StringWriter();
321                     Vector err;
322
323                     synchronized (preprocessor) {
324                         preprocessor.setReader(r);
325                         preprocessor.setWriter(w);
326                         err = preprocessor.process();
327                     }
328
329                     if (err.size() > 0) {
330                         for (int i=0; i < err.size(); i++) {
331                             Preprocessor.Warning warn = (Preprocessor.Warning)err.get(i);
332                             out.print(getFileName());
333                             out.print(':');
334                             out.print(warn.getLine());
335                             out.print(':');
336                             out.print(warn instanceof Preprocessor.Error ?
337                                       " error: " : " warning: ");
338                             out.println(warn.getMessage());
339                         }
340                         return null;
341                     }
342
343                     processed  = w.toString().toCharArray();
344                 } catch (IOException e) {
345                     System.out.println("IOException: "+e); // FIXME
346                     return null;
347                 }
348
349                 return processed;
350             }
351         };
352
353         private Source(File o, char[] n, char[][] p, String srcdir) {
354             orig = o; this.n = n; this.p = p;
355             String file = srcdir;
356             file += File.separatorChar +  str(p, File.separatorChar);
357             file += File.separatorChar + new String(n) + ".java";
358             fileName = file.toCharArray();
359         }
360     }
361
362     // Compiler Parameters ////////////////////////////////////////////////////
363
364     // FEATURE: may be able to use this to block access to APIs generated for stack objects
365     final AccessRestriction access = new AccessRestriction(null, null, null, null);
366
367     /** Used by compiler to resolve classes. */
368     final INameEnvironment env = new INameEnvironment() {
369         public NameEnvironmentAnswer findType(char[][] c) { return findType(name(c), pack(c)); }
370         public NameEnvironmentAnswer findType(char[] n, char[][] p) {
371             if (veryverbose) System.out.print("findType: "+ str(p, '.') + "."+new String(n));
372
373             try {
374                 String classname = new String(n);
375                 Class c = Class.forName(str(p, '.') + '.' + classname);
376                 if (veryverbose) System.out.println("  found in classloader: "+ c);
377                 IBinaryType b = (IBinaryType)loaded.get(c);
378                 if (b == null) loaded.put(c, b = new ClassFileReader(
379                     bytes(c), (str(p, '/') + '/' + classname).toCharArray()));
380                 return new NameEnvironmentAnswer(b, access);
381             } catch (ClassNotFoundException e) {
382             } catch (ClassFormatException e) {
383                 e.printStackTrace();
384                 throw new Error("ClassFormatException reading system class: " +
385                     str(p, '.')+new String(n));
386             }
387
388             // cut out searches for java.* packages in sources list
389             if (p.length > 0 && eq(p[0], "java".toCharArray())) {
390                 if (veryverbose) System.out.println("  not found, unknown java.*");
391                 return null;
392             }
393
394             try {
395                 for (int i=0; i < sources.length; i++) {
396                     Source s = sources[i];
397                     if (eq(n, s.n) && eq(p, s.p)) {
398                         if (s.reader != null) {
399                             if (veryverbose) System.out.println("  found reader");
400                             return new NameEnvironmentAnswer(s.reader, access);
401                         }
402                         if (s.compiled != null) {
403                             if (veryverbose) System.out.println("  found compiled, new reader");
404                             s.reader = new ClassFileReader(s.compiled,
405                                 s.orig.getName().toCharArray());
406                             return new NameEnvironmentAnswer(s.reader, access);
407                         }
408                         if (veryverbose) System.out.println("  found unit");
409                         return new NameEnvironmentAnswer(sources[i].unit, access);
410                     }
411                 }
412             } catch (ClassFormatException e) {
413                 System.out.println("Unexpected ClassFormatException"); // FIXME
414                 e.printStackTrace(); return null;
415             }
416             if (veryverbose) System.out.println("  not found");
417             return null;
418         }
419         public boolean isPackage(char[][] parent, char[] name) {
420             if (veryverbose) System.out.println("isPackage: "+ str(parent, '.') + "."+new String(name));
421             String parentName = str(parent, '/');
422             for (int i=0; i < sources.length; i++) {
423                 if (eq(name, sources[i].n) && eq(parent, sources[i].p)) return false;
424                 if (eq(pack(sources[i].p), parent) && eq(name(sources[i].p), name)) return true;
425             }
426             return
427                 loader.getResource(parentName + ".class") == null &&
428                 loader.getResource(parentName + '/' + new String(name) + ".class") == null;
429         }
430         public void cleanup() {}
431     };
432
433     /** Used by compiler to decide what do with problems.. */
434     private final IErrorHandlingPolicy policy =
435         DefaultErrorHandlingPolicies.proceedWithAllProblems();
436
437     /** Used by compiler for general options. */
438     private final Map settings = new HashMap();
439     {
440         settings.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE);
441         settings.put(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE);
442         settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_5);
443         settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_1);
444     };
445
446     /** Used by compiler for processing compiled classes and their errors. */
447     private final ICompilerRequestor results = new ICompilerRequestor() {
448         public void acceptResult(CompilationResult result) {
449             if (veryverbose) System.out.println("got result: "+result);
450             if (result.hasProblems()) {
451                 boolean err = false;
452                 IProblem[] p = result.getProblems();
453                 PrintWriter o;
454                 for (int i=0; i < p.length; i++) {
455                     if (p[i].isError()) { o = out; err = true; }
456                     else o = warn;
457
458                     o.print(p[i].getOriginatingFileName());
459                     o.print(':');
460                     o.print(p[i].getSourceLineNumber());
461                     o.print(':');
462                     o.print(p[i].isError() ? " error: " : " warning: ");
463                     o.println(p[i].getMessage());
464                 }
465                 out.flush();
466                 if (err) { hasErrors = true; return; }
467             }
468
469             ClassFile[] c = result.getClassFiles();
470             for (int i=0; i < c.length; i++) {
471                 try {
472                     char[][] name = c[i].getCompoundName();
473                     if (verbose) {
474                         String pct = "";
475                         /*+ percent;
476                         percent++;
477                         while (pct.length() < 2) pct = " " + pct;
478                         pct = "(" + pct + "%) ";
479                         */
480                         String printme = " writing: " + pct + str(pack(name),'.') + "." + new String(name(name));
481                         if (clearing.length() < printme.length()) clearing = "";
482                         else clearing = clearing.substring(printme.length());
483                         System.out.print(printme + clearing + "\r");
484                         for(clearing = ""; clearing.length() < printme.length() + 5; clearing += " ");
485                     }
486                     if (buildzip) {
487                         try {
488                             jarfile.putNextEntry(new ZipEntry(str(pack(name), '/') + "/" + new String(name(name)) + ".class"));
489                             jarfile.write(c[i].getBytes());
490                         } catch (java.util.zip.ZipException ze) {
491                             // HACK: horrendous hack
492                             if (ze.getMessage().indexOf("duplicate entry") != -1) {
493                                 //System.out.println("compiler emitted class twice: " + new String(name(name)));
494                             } else {
495                                 throw ze;
496                             }
497                         }
498                     } else {
499                         // build package path to new class file
500                         File path = new File(builddir, str(pack(name), '/'));
501                         if (!path.exists()) path.mkdirs();
502                         // write new class file
503                         path = new File(path, new String(name(name)) + ".class");
504                         OutputStream o = new BufferedOutputStream(new FileOutputStream(path));
505                         o.write(c[i].getBytes());
506                         o.close();
507                     }
508                 } catch (IOException e) {
509                     System.out.println("IOException writing class"); // FIXME
510                     e.printStackTrace();
511                 }
512             }
513         }
514     };
515
516     int percent = 0;
517     String clearing = "";
518
519     /** Problem creater for compiler. */
520     private final IProblemFactory problems = new DefaultProblemFactory();
521
522
523     // Helper Functiosn ///////////////////////////////////////////////////////
524
525     /** Convert source file path into class name block.
526      *  eg. in:  java/lang/String.java -> { {java} {lang} {String} } */
527     private static char[][] classname(String name) {
528         String delim = name.indexOf('/') == -1 ? "." : "/";
529         name = name.trim();
530         if (name.endsWith(".java")) name = name.substring(0, name.length() - 5);
531         if (name.endsWith(".class")) name = name.substring(0, name.length() - 6);
532         if (name.startsWith(delim)) name = name.substring(1);
533
534         StringTokenizer st = new StringTokenizer(name, delim);
535         char[][] n = new char[st.countTokens()][];
536         for (int i=0; st.hasMoreTokens(); i++) n[i] = st.nextToken().toCharArray();
537         return n;
538     }
539
540     /** Convert class name into a String. */
541     private static String str(char[][] name, char delim) {
542         StringBuffer b = new StringBuffer();
543         for (int i=0; name != null && i < name.length; i++) {
544             if (name[i] == null || name[i].length == 0) continue;
545             if (i > 0) b.append(delim);
546             b.append(name[i]);
547         }
548         return b.toString();
549     }
550
551     /** Returns the package component of a class name.
552      *  Effectively returns char[length - 1][].  */
553     private static char[][] pack(char[][] c) {
554         char[][] p = new char[c.length - 1][];
555         for (int i=0; i < p.length; i++) p[i] = c[i];
556         return p;
557     }
558
559     /** Returns the direct-name component of a class name.
560      *  eg. String from java.lang.String */
561     private static char[] name(char[][] c) { return c[c.length - 1]; }
562
563     /** Returns true of contents of both char arrays are equal. */
564     private static boolean eq(char[][] c1, char[][] c2) {
565         if (c1 == null || c2 == null) return c1 == c2;
566         if (c1.length != c2.length) return false;
567         for (int i=0; i < c1.length; i++) if (!eq(c1[i], c2[i])) return false;
568         return true;
569     }
570
571     /** Returns true of contents of both char arrays are equal. */
572     private static boolean eq(char[] c1, char[] c2) {
573         if (c1 == null || c2 == null) return c1 == c2;
574         if (c1.length != c2.length) return false;
575         for (int i=0; i < c1.length; i++) if (c1[i] != c2[i]) return false;
576         return true;
577     }
578
579     /** Returns class name as per VM Spec 4.2. eg. java/lang/String */
580     private static char[] name(Class c) {
581         return c == null ? null : c.getName().replace('.', '/').toCharArray();
582     }
583
584     /** Returns the type name of a class as per VM Spec 4.3.2. */
585     private static char[] typeName(Class p) {
586         StringBuffer sb = new StringBuffer();
587         typeName(p, sb);
588         return sb.toString().toCharArray();
589     }
590
591     /** Returns the type name of a class as per VM Spec 4.3.2.
592      *  eg. int -> I, String -> Ljava/lang/String; */
593     private static void typeName(Class p, StringBuffer sb) {
594         String name = p.getName();
595         switch (name.charAt(0)) {
596             case 'B': case 'C': case 'D': case 'F': case 'I':
597             case 'J': case 'S': case 'Z': case 'V': case '[':
598                 sb.append(name(p)); break;
599
600             case 'b': if (name.equals("boolean")) { sb.append('Z'); break; }
601                       if (name.equals("byte"))    { sb.append('B'); break; }
602             case 'c': if (name.equals("char"))    { sb.append('C'); break; }
603             case 'd': if (name.equals("double"))  { sb.append('D'); break; }
604             case 'f': if (name.equals("float"))   { sb.append('F'); break; }
605             case 'i': if (name.equals("int"))     { sb.append('I'); break; }
606             case 'l': if (name.equals("long"))    { sb.append('J'); break; }
607             case 's': if (name.equals("short"))   { sb.append('S'); break; }
608             case 'v': if (name.equals("void"))    { sb.append('V'); break; }
609             default:
610                 sb.append('L'); sb.append(name(p)); sb.append(';');
611         }
612     }
613
614     /** Returns the descriptor of a method per VM Spec 4.3.3.
615      *  eg. int get(String n, boolean b) -> (Ljava/lang/String;B)I */
616     private static char[] descriptor(Class[] p, Class r) {
617         StringBuffer sb = new StringBuffer();
618         sb.append('(');
619         if (p != null) for (int i=0; i < p.length; i++) typeName(p[i], sb);
620         sb.append(')');
621         if (r != null) typeName(r, sb);
622         return sb.toString().toCharArray();
623     }
624
625     private static byte[] bytes(Class c) {
626         return bytes(c.getResourceAsStream('/' + c.getName().replace('.', '/') + ".class"));
627     }
628     private static byte[] bytes(File bfile) {
629         try { return bytes(new FileInputStream(bfile)); }
630         catch (FileNotFoundException e) { throw new Error("FileNotFoundException reading bytes: "+e); }
631     }
632     private static byte[] bytes(InputStream bin) {
633         byte[] bytes = new byte[2 * 1024];
634         int pos = 0, in = 0;
635         try {
636             while ((in = bin.read(bytes, pos, bytes.length - pos)) != -1) {
637                 pos += in;
638                 if (pos == bytes.length) {
639                     byte[] newbytes= new byte[pos * 2];
640                     System.arraycopy(bytes, 0, newbytes, 0, pos);
641                     bytes = newbytes;
642                 }
643             }
644             bin.close();
645         } catch (IOException e) {
646             e.printStackTrace();
647             throw new Error("IOException reading class file: "+e);
648         }
649
650         if (pos != bytes.length) {
651             byte[] newbytes= new byte[pos * 2];
652             System.arraycopy(bytes, 0, newbytes, 0, pos);
653             bytes = newbytes;
654         }
655
656         return bytes;
657     }
658 }