5 import java.util.zip.*;
6 import java.util.jar.*;
8 import java.lang.reflect.*;
10 import org.eclipse.jdt.core.compiler.IProblem;
11 import org.eclipse.jdt.internal.compiler.ClassFile;
12 import org.eclipse.jdt.internal.compiler.CompilationResult;
13 //import org.eclipse.jdt.internal.compiler.Compiler;
14 import org.eclipse.jdt.internal.compiler.DefaultErrorHandlingPolicies;
15 import org.eclipse.jdt.internal.compiler.ICompilerRequestor;
16 import org.eclipse.jdt.internal.compiler.IErrorHandlingPolicy;
17 import org.eclipse.jdt.internal.compiler.IProblemFactory;
18 import org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader;
19 import org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException;
20 import org.eclipse.jdt.internal.compiler.env.*;
21 import org.eclipse.jdt.internal.compiler.impl.*;
22 import org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory;
24 // FEATURE: add build dependencies like make (grab some Java dependency-checker code off the net?)
26 public class Compiler {
27 // Static Entry Point /////////////////////////////////////////////////////
29 public static void main(String[] args) throws IOException {
30 boolean verbose = false, veryverbose = false, warnings = true;
31 List srcdir = new ArrayList();
32 String source = null, target = null, blddir = null, mainclass = null;
33 boolean buildjar = false;
35 if (args.length == 0) args = new String[] { "--help" };
36 for (int i=0; i < args.length; i++) {
37 if (args[i].charAt(0) == '-') {
38 if (args[i].length() == 1) {
39 System.out.println("Illegal switch: -"); return; }
40 switch (args[i].charAt(1)) {
42 if (args[i].equals("--help")) printHelp();
43 else System.out.println("Unknown switch: -");
46 if (i == args.length - 1) {
47 System.out.println("Missing parameter: "+args[i]); return; }
48 if (blddir != null) { System.out.println("cannot specify both -d and -j"); return; }
52 if (i == args.length - 1) {
53 System.out.println("Missing parameter: "+args[i]); return; }
54 if (blddir != null) { System.out.println("cannot specify both -d and -j"); return; }
59 if (i == args.length - 1) {
60 System.out.println("Missing parameter: "+args[i]); return; }
61 mainclass = args[++i];
64 if (i == args.length - 1) {
65 System.out.println("Missing parameter: "+args[i]); return; }
69 if (i == args.length - 1) {
70 System.out.println("Missing parameter: "+args[i]); return; }
74 if (i == args.length - 1) {
75 System.out.println("Missing parameter: "+args[i]); return; }
88 } else srcdir.add(args[i]);
91 Compiler c = new Compiler();
93 if (buildjar) c.setBuildJar(blddir);
94 else c.setBuildDir(blddir);
96 if (source != null) c.setSource(source);
97 if (target != null) c.setTarget(target);
98 if (mainclass != null) c.setMainClass(mainclass);
100 String[] s = new String[srcdir.size()];
104 c.setVerbose(verbose);
105 c.setWarnings(warnings);
106 c.setVeryVerbose(veryverbose);
109 private static void printHelp() {
110 System.out.println("Usage java -cp ... org.ibex.tool.Compiler [options] <source dir> ...");
111 System.out.println("Options:");
112 System.out.println(" -d <directory> Directory to put generated class files in");
113 System.out.println(" -j <jarfile> Jar file to put generated class files in");
114 System.out.println(" -m <class> Main-Class for jar file.");
115 System.out.println(" -s <release> Compile with specified source compatibility.");
116 System.out.println(" -t <release> Compile with specified class file compatibility.");
117 System.out.println(" -v Verbose output.");
118 System.out.println(" -V Very Verbose output.");
119 System.out.println(" -h or --help Print this message.");
120 System.out.println("");
124 // Compiler Interface /////////////////////////////////////////////////////
126 private ClassLoader loader = ClassLoader.getSystemClassLoader();
127 private Map loaded = new HashMap();
128 private PrintWriter out = new PrintWriter(System.out);
129 private Preprocessor preprocessor;
131 private Source[] sources;
133 private File builddir = null;
134 private boolean buildzip = false;
135 private ZipOutputStream jarfile = null;
136 private String mainclass = null;
138 private String[] sourcedirs = new String[0];
140 private PrintWriter warn;
141 private boolean hasErrors;
142 private boolean verbose = false;
143 private boolean veryverbose = false;
144 private boolean warnings = true;
147 List defs = Collections.EMPTY_LIST;
149 String define = System.getProperty("org.ibex.tool.preprocessor.define");
150 if (define != null) {
151 defs = new ArrayList();
152 StringTokenizer st = new StringTokenizer(define.toUpperCase(), ",");
153 while (st.hasMoreTokens()) defs.add(st.nextToken().trim());
156 preprocessor = new Preprocessor(null, null, defs);
159 public void setMainClass(String mainclass) { this.mainclass = mainclass; }
160 public void setBuildJar(String dir) throws IOException {
161 builddir = new File(dir == null ? "." : dir);
164 public void setBuildDir(String dir) throws IOException {
165 builddir = new File(dir == null ? "." : dir);
168 public void setSourceDirs(String[] dir) { sourcedirs = dir; }
170 /** Pass CompilerOptions.VERSION_1_*. A String of form "1.1", ".2", etc. */
171 public void setSource(String v) {
172 if (v.equals("1.1")) settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_1);
173 else if (v.equals("1.2")) settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_2);
174 else if (v.equals("1.3")) settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_3);
175 else if (v.equals("1.4")) settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_4);
176 else if (v.equals("1.5")) settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_5);
177 else throw new RuntimeException("I have no idea what Java " + v + " is. Ask David Crawshaw.");
180 /** Pass CompilerOptions.VERSION_1_*. A String of form "1.1", ".2", etc. */
181 public void setTarget(String v) {
182 if (v.equals("1.1")) settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_1);
183 else if (v.equals("1.2")) settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_2);
184 else if (v.equals("1.3")) settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_3);
185 else if (v.equals("1.4")) settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_4);
186 else if (v.equals("1.5")) settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_5);
187 else throw new RuntimeException("I have no idea what Java " + v + " is. Ask David Crawshaw.");
190 public void setVerbose(boolean v) { verbose = v; }
191 public void setVeryVerbose(boolean v) { veryverbose = v; }
192 public void setWarnings(boolean w) { warnings = w; }
194 public void compile() throws IOException {
195 List s = new ArrayList();
198 Manifest m = new Manifest();
199 m.getMainAttributes().putValue("Manifest-Version", "1.0");
200 if (mainclass != null) m.getMainAttributes().putValue("Main-Class", mainclass);
201 jarfile = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(builddir)), m);
203 for (int i=0; i < sourcedirs.length; i++) {
204 File src = new File(sourcedirs[i]);
206 if (veryverbose) System.out.println("source directory not found: "+sourcedirs[i]);
209 filterSources(s, src, new char[0][], sourcedirs[i]);
212 if (veryverbose) System.out.println("working with "+s.size() +" sources");
213 sources = new Source[s.size()]; s.toArray(sources);
214 ICompilationUnit[] units = new ICompilationUnit[s.size()];
215 int u = 0; for (int i=0; i < sources.length; i++)
216 if (sources[i].compiled == null) units[u++] = sources[i].unit;
217 if (u != units.length) {
218 ICompilationUnit[] newu = new ICompilationUnit[u];
219 System.arraycopy(units, 0, newu, 0, u);
225 StringWriter sw = new StringWriter();
226 StringBuffer w = sw.getBuffer();
227 warn = new PrintWriter(sw);
229 org.eclipse.jdt.internal.compiler.Compiler jdt =
230 new org.eclipse.jdt.internal.compiler.Compiler(
231 env, policy, settings, results, problems);
234 if (warnings && !hasErrors) { out.write(w.toString()); out.flush(); }
237 if (jarfile != null) jarfile.close();
238 } catch (Exception e) {
241 if (verbose) System.out.print(clearing + " \r");
244 private final FilenameFilter filterSrcs = new FilenameFilter() {
245 public boolean accept(File dir, String name) { return name.endsWith(".java"); }
247 private final FileFilter filterDirs = new FileFilter() {
248 public boolean accept(File path) { return path.isDirectory(); }
250 private byte[] bytes(File bfile) {
251 byte[] bytes = new byte[2 * 1024];
254 InputStream bin = new FileInputStream(bfile);
255 while ((in = bin.read(bytes, pos, bytes.length - pos)) != -1) {
257 if (pos == bytes.length) {
258 byte[] newbytes= new byte[pos * 2];
259 System.arraycopy(bytes, 0, newbytes, 0, pos);
264 } catch (IOException e) {
265 System.out.println("Error reading class file"); // FIXME
266 e.printStackTrace(); return null;
269 if (pos != bytes.length) {
270 byte[] newbytes= new byte[pos * 2];
271 System.arraycopy(bytes, 0, newbytes, 0, pos);
277 private void filterSources(List s, File dir, char[][] pack, String srcdir) {
278 List bclasses = new ArrayList();
279 File bdir = new File(builddir, str(pack, File.separatorChar));
281 // add the java files in this directory
282 File[] ja = dir.listFiles(filterSrcs);
283 for (int i=0; i < ja.length; i++) {
284 char[] n = name(classname(ja[i].getName()));
285 Source src = new Source(ja[i], n, pack, srcdir);
287 // skip the file if the build version is newer than the source
288 String bclass = new String(n);
289 File bfile = new File(bdir, bclass + ".class");
290 if (bfile.lastModified() > ja[i].lastModified()) {
291 src.compiled = bytes(bfile);
292 bclasses.add(bclass);
298 // process the inner classes of any binary files
299 for (int i=0; i < bclasses.size(); i++) {
300 final String bc = (String)bclasses.get(i);
301 final FilenameFilter f = new FilenameFilter() {
302 public boolean accept(File dir, String name) {
303 return name.length() > bc.length() && name.startsWith(bc) &&
304 name.charAt(bc.length()) == '$' && name.endsWith(".class");
307 File[] bfile = bdir.listFiles(f);
308 for (int j=0; j < bfile.length; j++) {
309 Source src = new Source(bfile[j],
310 name(classname(bfile[j].getName())), pack, srcdir);
311 src.compiled = bytes(bfile[j]);
316 // add the subdirectories as packages
317 File[] d = dir.listFiles(filterDirs);
318 for (int i=0; i < d.length; i++) {
319 char[][] newpack = new char[pack.length + 1][];
320 for (int j=0; j < pack.length; j++) newpack[j] = pack[j];
321 newpack[pack.length] = d[i].getName().toCharArray();
322 filterSources(s, d[i], newpack, srcdir);
327 /** Represents a file to be compiled. */
330 char[] n; char[][] p;
332 char[] processed = null;
333 byte[] compiled = null;
334 ClassFileReader reader = null;
336 final ICompilationUnit unit = new ICompilationUnit() {
337 public char[] getMainTypeName() { return n; }
338 public char[][] getPackageName() { return p; }
339 public char[] getFileName() { return fileName; }
340 public char[] getContents() {
341 if (processed != null) return processed;
344 Reader r = new InputStreamReader(new BufferedInputStream(
345 new FileInputStream(orig)));
346 StringWriter w = new StringWriter();
349 synchronized (preprocessor) {
350 preprocessor.setReader(r);
351 preprocessor.setWriter(w);
352 err = preprocessor.process();
355 if (err.size() > 0) {
356 for (int i=0; i < err.size(); i++) {
357 Preprocessor.Warning warn = (Preprocessor.Warning)err.get(i);
358 out.print(getFileName());
360 out.print(warn.getLine());
362 out.print(warn instanceof Preprocessor.Error ?
363 " error: " : " warning: ");
364 out.println(warn.getMessage());
369 processed = w.toString().toCharArray();
370 } catch (IOException e) {
371 System.out.println("IOException: "+e); // FIXME
379 private Source(File o, char[] n, char[][] p, String srcdir) {
380 orig = o; this.n = n; this.p = p;
381 String file = srcdir;
382 file += File.separatorChar + str(p, File.separatorChar);
383 file += File.separatorChar + new String(n) + ".java";
384 fileName = file.toCharArray();
388 // ClassLoader Wrappers ///////////////////////////////////////////////////
390 final static class LoadedNestedType implements IBinaryNestedType {
392 LoadedNestedType(Class c) { this.c = c; }
393 public char[] getName() { return name(c); }
394 public char[] getEnclosingTypeName() { return name(c.getDeclaringClass()); }
395 public int getModifiers() { return c.getModifiers(); }
398 final static class LoadedField implements IBinaryField {
402 LoadedField(Field f) {
404 int m = f.getModifiers();
406 c = Constant.NotAConstant;
407 if (Modifier.isFinal(m) && Modifier.isStatic(m)) {
409 Class type = f.getType();
410 if (type == Boolean.TYPE) {
411 c = new BooleanConstant(f.getBoolean(null));
412 } else if (type == Byte.TYPE) {
413 c = new ByteConstant(f.getByte(null));
414 } else if (type == Character.TYPE) {
415 c = new CharConstant(f.getChar(null));
416 } else if (type == Double.TYPE) {
417 c = new DoubleConstant(f.getDouble(null));
418 } else if (type == Float.TYPE) {
419 c = new FloatConstant(f.getFloat(null));
420 } else if (type == Integer.TYPE) {
421 c = new IntConstant(f.getInt(null));
422 } else if (type == Long.TYPE) {
423 c = new LongConstant(f.getLong(null));
424 } else if (type == Short.TYPE) {
425 c = new ShortConstant(f.getShort(null));
426 } else if (type == String.class) {
427 c = new StringConstant((String)f.get(null));
429 } catch (IllegalAccessException e) {}
432 public Constant getConstant() { return c; }
433 public char[] getTypeName() { return typeName(f.getType()); }
434 public char[] getName() { return f.getName().toCharArray(); }
435 public int getModifiers() { return f.getModifiers(); }
438 final static class LoadedConstructor implements IBinaryMethod {
439 private Constructor c;
443 LoadedConstructor(Constructor c) {
446 Class[] exs = c.getExceptionTypes();
447 ex = new char[exs.length][];
448 for (int i=0; i < ex.length; i++) ex[i] = name(exs[i]);
450 desc = descriptor(c.getParameterTypes(), null);
452 public int getModifiers() { return c.getModifiers(); }
453 public char[] getSelector() { return c.getName().toCharArray(); }
454 public boolean isConstructor() { return true; }
455 public boolean isClinit() { return false; }
456 public char[][] getArgumentNames() { return null; }
457 public char[][] getExceptionTypeNames() { return ex; }
458 public char[] getMethodDescriptor() { return desc; }
461 final static class LoadedMethod implements IBinaryMethod {
466 LoadedMethod(Method m) {
469 Class[] exs = m.getExceptionTypes();
470 ex = new char[exs.length][];
471 for (int i=0; i < ex.length; i++) ex[i] = name(exs[i]);
473 desc = descriptor(m.getParameterTypes(), m.getReturnType());
475 public int getModifiers() { return m.getModifiers(); }
476 public char[] getSelector() { return m.getName().toCharArray(); }
477 public boolean isConstructor() { return false; }
478 public boolean isClinit() { return false; }
479 public char[][] getArgumentNames() { return null; } // FEATURE: does this do anything cool?
480 public char[][] getExceptionTypeNames() { return ex; }
481 public char[] getMethodDescriptor() { return desc; }
484 final static class LoadedClass implements IBinaryType {
486 private IBinaryField[] f;
487 private char[][] inf;
488 private IBinaryNestedType[] nested;
489 private IBinaryMethod[] meth = null;
491 LoadedClass(Class c) {
494 Field[] fields = c.getDeclaredFields();
495 List flist = new ArrayList(fields.length);
496 for (int i=0; i < fields.length; i++)
497 if (!Modifier.isPrivate(fields[i].getModifiers()))
498 flist.add(new LoadedField(fields[i]));
499 f = new IBinaryField[flist.size()];
502 Class[] interfaces = c.getInterfaces();
503 inf = new char[interfaces.length][];
504 for (int i=0; i < inf.length; i++) inf[i] = name(interfaces[i]);
506 Class[] classes = c.getClasses();
507 nested = new IBinaryNestedType[classes.length];
508 for (int i=0; i < nested.length; i++)
509 nested[i] = new LoadedNestedType(classes[i]);
511 Constructor[] constructors = c.getDeclaredConstructors();
512 Method[] methods = c.getDeclaredMethods();
513 if (methods.length + constructors.length > 0) {
514 List m = new ArrayList(methods.length + constructors.length);
515 for (int j=0; j < methods.length; j++)
516 if (!Modifier.isPrivate(methods[j].getModifiers()))
517 m.add(new LoadedMethod(methods[j]));
518 for (int j=0; j < constructors.length; j++)
519 if (!Modifier.isPrivate(constructors[j].getModifiers()))
520 m.add(new LoadedConstructor(constructors[j]));
521 meth = new IBinaryMethod[m.size()]; m.toArray(meth);
525 public char[] getName() { return name(c); }
526 public char[] getEnclosingTypeName() { return name(c.getDeclaringClass()); }
527 public char[] getSuperclassName() { return name(c.getSuperclass()); }
528 public IBinaryField[] getFields() { return f; }
529 public char[][] getInterfaceNames() { return inf; }
530 public IBinaryNestedType[] getMemberTypes() { return nested; }
531 public IBinaryMethod[] getMethods() { return meth; }
532 public int getModifiers() { return c.getModifiers(); }
534 public boolean isBinaryType() { return true; }
535 public boolean isClass() { return true; }
536 public boolean isInterface() { return c.isInterface(); }
537 public boolean isAnonymous() { return false; }
538 public boolean isLocal() { return false; } // FIXME
539 public boolean isMember() { return false; } // FIXME
540 public char[] sourceFileName() { return null; }
541 public char[] getFileName() { return null; }
543 public boolean equals(Object o) {
544 return o == this || super.equals(o) ||
545 (o != null && o instanceof LoadedClass &&
546 c.equals(((LoadedClass)o).c));
551 // Compiler Parameters ////////////////////////////////////////////////////
553 /** Used by compiler to resolve classes. */
554 final INameEnvironment env = new INameEnvironment() {
555 public NameEnvironmentAnswer findType(char[][] c) { return findType(name(c), pack(c)); }
556 public NameEnvironmentAnswer findType(char[] n, char[][] p) {
557 if (veryverbose) System.out.print("findType: "+ str(p, '.') + "."+new String(n));
560 Class c = Class.forName(str(p, '.') + '.' + new String(n));
561 if (veryverbose) System.out.println(" found in classloader: "+ c);
562 IBinaryType b = (IBinaryType)loaded.get(c);
563 if (b == null) loaded.put(c, b = new LoadedClass(c));
564 return new NameEnvironmentAnswer(b);
565 } catch (ClassNotFoundException e) {}
567 // cut out searches for java.* packages in sources list
568 if (p.length > 0 && eq(p[0], "java".toCharArray())) {
569 if (veryverbose) System.out.println(" not found, unknown java.*");
574 for (int i=0; i < sources.length; i++) {
575 Source s = sources[i];
576 if (eq(n, s.n) && eq(p, s.p)) {
577 if (s.reader != null) {
578 if (veryverbose) System.out.println(" found reader");
579 return new NameEnvironmentAnswer(s.reader);
581 if (s.compiled != null) {
582 if (veryverbose) System.out.println(" found compiled, new reader");
583 s.reader = new ClassFileReader(s.compiled,
584 s.orig.getName().toCharArray(), true);
585 return new NameEnvironmentAnswer(s.reader);
587 if (veryverbose) System.out.println(" found unit");
588 return new NameEnvironmentAnswer(sources[i].unit);
591 } catch (ClassFormatException e) {
592 System.out.println("Unexpected ClassFormatException"); // FIXME
593 e.printStackTrace(); return null;
595 if (veryverbose) System.out.println(" not found");
598 public boolean isPackage(char[][] parent, char[] name) {
599 if (veryverbose) System.out.println("isPackage: "+ str(parent, '.') + "."+new String(name));
600 String parentName = str(parent, '/');
601 for (int i=0; i < sources.length; i++) {
602 if (eq(name, sources[i].n) && eq(parent, sources[i].p)) return false;
603 if (eq(pack(sources[i].p), parent) && eq(name(sources[i].p), name)) return true;
606 loader.getResource(parentName + ".class") == null &&
607 loader.getResource(parentName + '/' + new String(name) + ".class") == null;
609 public void cleanup() {}
612 /** Used by compiler to decide what do with problems.. */
613 private final IErrorHandlingPolicy policy =
614 DefaultErrorHandlingPolicies.proceedWithAllProblems();
616 /** Used by compiler for general options. */
617 private final Map settings = new HashMap();
619 settings.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE);
620 settings.put(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE);
621 settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_5);
622 settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_1);
625 /** Used by compiler for processing compiled classes and their errors. */
626 private final ICompilerRequestor results = new ICompilerRequestor() {
627 public void acceptResult(CompilationResult result) {
628 if (veryverbose) System.out.println("got result: "+result);
629 if (result.hasProblems()) {
631 IProblem[] p = result.getProblems();
633 for (int i=0; i < p.length; i++) {
634 if (p[i].isError()) { o = out; err = true; }
637 o.print(p[i].getOriginatingFileName());
639 o.print(p[i].getSourceLineNumber());
641 o.print(p[i].isError() ? " error: " : " warning: ");
642 o.println(p[i].getMessage());
645 if (err) { hasErrors = true; return; }
648 ClassFile[] c = result.getClassFiles();
649 for (int i=0; i < c.length; i++) {
651 char[][] name = c[i].getCompoundName();
656 while (pct.length() < 2) pct = " " + pct;
657 pct = "(" + pct + "%) ";
659 String printme = " writing: " + pct + str(pack(name),'.') + "." + new String(name(name));
660 if (clearing.length() < printme.length()) clearing = "";
661 else clearing = clearing.substring(printme.length());
662 System.out.print(printme + clearing + "\r");
663 for(clearing = ""; clearing.length() < printme.length() + 5; clearing += " ");
667 jarfile.putNextEntry(new ZipEntry(str(pack(name), '/') + "/" + new String(name(name)) + ".class"));
668 jarfile.write(c[i].getBytes());
669 } catch (java.util.zip.ZipException ze) {
670 // HACK: horrendous hack
671 if (ze.getMessage().indexOf("duplicate entry") != -1) {
672 //System.out.println("compiler emitted class twice: " + new String(name(name)));
678 // build package path to new class file
679 File path = new File(builddir, str(pack(name), '/'));
680 if (!path.exists()) path.mkdirs();
681 // write new class file
682 path = new File(path, new String(name(name)) + ".class");
683 OutputStream o = new BufferedOutputStream(new FileOutputStream(path));
684 o.write(c[i].getBytes());
687 } catch (IOException e) {
688 System.out.println("IOException writing class"); // FIXME
696 String clearing = "";
698 /** Problem creater for compiler. */
699 private final IProblemFactory problems = new DefaultProblemFactory();
702 // Helper Functiosn ///////////////////////////////////////////////////////
704 /** Convert source file path into class name block.
705 * eg. in: java/lang/String.java -> { {java} {lang} {String} } */
706 private char[][] classname(String name) {
707 String delim = name.indexOf('/') == -1 ? "." : "/";
709 if (name.endsWith(".java")) name = name.substring(0, name.length() - 5);
710 if (name.endsWith(".class")) name = name.substring(0, name.length() - 6);
711 if (name.startsWith(delim)) name = name.substring(1);
713 StringTokenizer st = new StringTokenizer(name, delim);
714 char[][] n = new char[st.countTokens()][];
715 for (int i=0; st.hasMoreTokens(); i++) n[i] = st.nextToken().toCharArray();
719 /** Convert class name into a String. */
720 private static String str(char[][] name, char delim) {
721 StringBuffer b = new StringBuffer();
722 for (int i=0; name != null && i < name.length; i++) {
723 if (name[i] == null || name[i].length == 0) continue;
724 if (i > 0) b.append(delim);
730 /** Returns the package component of a class name.
731 * Effectively returns char[length - 1][]. */
732 private static char[][] pack(char[][] c) {
733 char[][] p = new char[c.length - 1][];
734 for (int i=0; i < p.length; i++) p[i] = c[i];
738 /** Returns the direct-name component of a class name.
739 * eg. String from java.lang.String */
740 private static char[] name(char[][] c) { return c[c.length - 1]; }
742 /** Returns true of contents of both char arrays are equal. */
743 private static boolean eq(char[][] c1, char[][] c2) {
744 if (c1 == null || c2 == null) return c1 == c2;
745 if (c1.length != c2.length) return false;
746 for (int i=0; i < c1.length; i++) if (!eq(c1[i], c2[i])) return false;
750 /** Returns true of contents of both char arrays are equal. */
751 private static boolean eq(char[] c1, char[] c2) {
752 if (c1 == null || c2 == null) return c1 == c2;
753 if (c1.length != c2.length) return false;
754 for (int i=0; i < c1.length; i++) if (c1[i] != c2[i]) return false;
758 /** Returns class name as per VM Spec 4.2. eg. java/lang/String */
759 private static char[] name(Class c) {
760 return c == null ? null : c.getName().replace('.', '/').toCharArray();
763 /** Returns the type name of a class as per VM Spec 4.3.2. */
764 private static char[] typeName(Class p) {
765 StringBuffer sb = new StringBuffer();
767 return sb.toString().toCharArray();
770 /** Returns the type name of a class as per VM Spec 4.3.2.
771 * eg. int -> I, String -> Ljava/lang/String; */
772 private static void typeName(Class p, StringBuffer sb) {
773 String name = p.getName();
774 switch (name.charAt(0)) {
775 case 'B': case 'C': case 'D': case 'F': case 'I':
776 case 'J': case 'S': case 'Z': case 'V': case '[':
777 sb.append(name(p)); break;
779 case 'b': if (name.equals("boolean")) { sb.append('Z'); break; }
780 if (name.equals("byte")) { sb.append('B'); break; }
781 case 'c': if (name.equals("char")) { sb.append('C'); break; }
782 case 'd': if (name.equals("double")) { sb.append('D'); break; }
783 case 'f': if (name.equals("float")) { sb.append('F'); break; }
784 case 'i': if (name.equals("int")) { sb.append('I'); break; }
785 case 'l': if (name.equals("long")) { sb.append('J'); break; }
786 case 's': if (name.equals("short")) { sb.append('S'); break; }
787 case 'v': if (name.equals("void")) { sb.append('V'); break; }
789 sb.append('L'); sb.append(name(p)); sb.append(';');
793 /** Returns the descriptor of a method per VM Spec 4.3.3.
794 * eg. int get(String n, boolean b) -> (Ljava/lang/String;B)I */
795 private static char[] descriptor(Class[] p, Class r) {
796 StringBuffer sb = new StringBuffer();
798 if (p != null) for (int i=0; i < p.length; i++) typeName(p[i], sb);
800 if (r != null) typeName(r, sb);
801 return sb.toString().toCharArray();