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