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