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