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