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