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