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