Adopting to JDK8's Nashorn differences. Most tests should now pass with Nashorn now.
2 * Back 2 Browser Bytecode Translator
3 * Copyright (C) 2012 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, version 2 of the License.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. Look for COPYING file in the top folder.
16 * If not, see http://opensource.org/licenses/GPL-2.0.
18 package org.apidesign.vm4brwsr;
20 import java.io.IOException;
21 import java.io.InputStream;
22 import static org.apidesign.vm4brwsr.ByteCodeParser.*;
24 /** Translator of the code inside class files to JavaScript.
26 * @author Jaroslav Tulach <jtulach@netbeans.org>
28 abstract class ByteCodeToJavaScript {
31 final ObfuscationDelegate obfuscationDelegate;
33 protected ByteCodeToJavaScript(Appendable out) {
34 this(out, ObfuscationDelegate.NULL);
37 protected ByteCodeToJavaScript(
38 Appendable out, ObfuscationDelegate obfuscationDelegate) {
40 this.obfuscationDelegate = obfuscationDelegate;
43 /* Collects additional required resources.
45 * @param internalClassName classes that were referenced and should be loaded in order the
46 * generated JavaScript code works properly. The names are in internal
47 * JVM form so String is <code>java/lang/String</code>.
49 protected abstract boolean requireReference(String internalClassName);
52 * @param resourcePath name of resources to read
54 protected abstract void requireScript(String resourcePath) throws IOException;
56 /** Allows subclasses to redefine what field a function representing a
57 * class gets assigned. By default it returns the suggested name followed
58 * by <code>" = "</code>;
60 * @param className suggested name of the class
62 /* protected */ String assignClass(String className) {
63 return className + " = ";
65 /* protected */ String accessClass(String classOperation) {
66 return classOperation;
69 abstract String getVMObject();
71 /** Prints out a debug message.
73 * @param msg the message
74 * @return true if the message has been printed
77 boolean debug(String msg) throws IOException {
83 * Converts a given class file to a JavaScript version.
85 * @param classFile input stream with code of the .class file
86 * @return the initialization code for this class, if any. Otherwise <code>null</code>
88 * @throws IOException if something goes wrong during read or write or translating
91 public String compile(InputStream classFile) throws IOException {
92 this.jc = new ClassData(classFile);
93 if (jc.getMajor_version() < 50) {
94 throw new IOException("Can't compile " + jc.getClassName() + ". Class file version " + jc.getMajor_version() + "."
95 + jc.getMinor_version() + " - recompile with -target 1.6 (at least)."
98 byte[] arrData = jc.findAnnotationData(true);
100 String[] arr = findAnnotation(arrData, jc,
101 "org.apidesign.bck2brwsr.core.ExtraJavaScript",
102 "resource", "processByteCode"
105 if (!arr[0].isEmpty()) {
106 requireScript(arr[0]);
108 if ("0".equals(arr[1])) {
114 String[] arr = findAnnotation(arrData, jc,
115 "net.java.html.js.JavaScriptResource",
119 if (arr[0].startsWith("/")) {
120 requireScript(arr[0]);
122 int last = jc.getClassName().lastIndexOf('/');
124 jc.getClassName().substring(0, last + 1).replace('.', '/') + arr[0]
129 String[] proto = findAnnotation(arrData, jc,
130 "org.apidesign.bck2brwsr.core.JavaScriptPrototype",
131 "container", "prototype"
133 StringArray toInitilize = new StringArray();
134 final String className = className(jc);
135 out.append("\n\n").append(assignClass(className));
136 out.append("function ").append(className).append("() {");
137 out.append("\n var CLS = ").append(className).append(';');
138 out.append("\n if (!CLS.$class) {");
140 String sc = jc.getSuperClassName(); // with _
141 out.append("\n var pp = ").
142 append(accessClass(sc.replace('/', '_'))).append("(true);");
143 out.append("\n var p = CLS.prototype = pp;");
144 out.append("\n var c = p;");
145 out.append("\n var sprcls = pp.constructor.$class;");
147 out.append("\n var p = CLS.prototype = ").append(proto[1]).append(";");
148 if (proto[0] == null) {
151 out.append("\n var c = ").append(proto[0]).append(";");
152 out.append("\n var sprcls = null;");
154 for (FieldData v : jc.getFields()) {
156 out.append("\n CLS.fld_").append(v.getName()).append(initField(v));
157 out.append("\n c._").append(v.getName()).append(" = function (v) {")
158 .append(" if (arguments.length == 1) CLS.fld_").append(v.getName())
159 .append(" = v; return CLS.fld_").
160 append(v.getName()).append("; };");
162 out.append("\n c._").append(v.getName()).append(" = function (v) {")
163 .append(" if (arguments.length == 1) this.fld_").
164 append(className).append('_').append(v.getName())
165 .append(" = v; return this.fld_").
166 append(className).append('_').append(v.getName())
170 obfuscationDelegate.exportField(out, "c", "_" + v.getName(), v);
172 for (MethodData m : jc.getMethods()) {
173 byte[] onlyArr = m.findAnnotationData(true);
174 String[] only = findAnnotation(onlyArr, jc,
175 "org.apidesign.bck2brwsr.core.JavaScriptOnly",
179 if (only[0] != null && only[1] != null) {
180 out.append("\n p.").append(only[0]).append(" = ")
181 .append(only[1]).append(";");
190 mn = generateStaticMethod(destObject, m, toInitilize);
192 if (m.isConstructor()) {
194 mn = generateInstanceMethod(destObject, m);
197 mn = generateInstanceMethod(destObject, m);
200 obfuscationDelegate.exportMethod(out, destObject, mn, m);
201 byte[] runAnno = m.findAnnotationData(false);
202 if (runAnno != null) {
203 out.append("\n ").append(destObject).append(".").append(mn).append(".anno = {");
204 generateAnno(jc, out, runAnno);
207 out.append("\n ").append(destObject).append(".").append(mn).append(".access = " + m.getAccess()).append(";");
208 out.append("\n ").append(destObject).append(".").append(mn).append(".cls = CLS;");
210 out.append("\n c.constructor = CLS;");
211 out.append("\n function fillInstOf(x) {");
212 String instOfName = "$instOf_" + className;
213 out.append("\n x.").append(instOfName).append(" = true;");
214 for (String superInterface : jc.getSuperInterfaces()) {
215 String intrfc = superInterface.replace('/', '_');
216 out.append("\n vm.").append(intrfc).append("(false).fillInstOf(x);");
217 requireReference(superInterface);
220 out.append("\n c.fillInstOf = fillInstOf;");
221 out.append("\n fillInstOf(c);");
222 obfuscationDelegate.exportJSProperty(out, "c", instOfName);
223 out.append("\n CLS.$class = 'temp';");
224 out.append("\n CLS.$class = ");
225 out.append(accessClass("java_lang_Class(true);"));
226 out.append("\n CLS.$class.jvmName = '").append(jc.getClassName()).append("';");
227 out.append("\n CLS.$class.superclass = sprcls;");
228 out.append("\n CLS.$class.access = ").append(jc.getAccessFlags()+";");
229 out.append("\n CLS.$class.cnstr = CLS;");
230 byte[] classAnno = jc.findAnnotationData(false);
231 if (classAnno != null) {
232 out.append("\n CLS.$class.anno = {");
233 generateAnno(jc, out, classAnno);
236 for (String init : toInitilize.toArray()) {
237 out.append("\n ").append(init).append("();");
240 out.append("\n if (arguments.length === 0) {");
241 out.append("\n if (!(this instanceof CLS)) {");
242 out.append("\n return new CLS();");
244 for (FieldData v : jc.getFields()) {
245 byte[] onlyArr = v.findAnnotationData(true);
246 String[] only = findAnnotation(onlyArr, jc,
247 "org.apidesign.bck2brwsr.core.JavaScriptOnly",
251 if (only[0] != null && only[1] != null) {
252 out.append("\n p.").append(only[0]).append(" = ")
253 .append(only[1]).append(";");
258 out.append("\n this.fld_").
259 append(className).append('_').
260 append(v.getName()).append(initField(v));
263 out.append("\n return this;");
265 out.append("\n return arguments[0] ? new CLS() : CLS.prototype;");
268 obfuscationDelegate.exportClass(out, getVMObject(), className, jc);
270 // StringBuilder sb = new StringBuilder();
271 // for (String init : toInitilize.toArray()) {
272 // sb.append("\n").append(init).append("();");
276 private String generateStaticMethod(String destObject, MethodData m, StringArray toInitilize) throws IOException {
277 String jsb = javaScriptBody(destObject, m, true);
281 final String mn = findMethodName(m, new StringBuilder());
282 if (mn.equals("class__V")) {
283 toInitilize.add(accessClass(className(jc)) + "(false)." + mn);
285 generateMethod(destObject, mn, m);
289 private String generateInstanceMethod(String destObject, MethodData m) throws IOException {
290 String jsb = javaScriptBody(destObject, m, false);
294 final String mn = findMethodName(m, new StringBuilder());
295 generateMethod(destObject, mn, m);
299 private void generateMethod(String destObject, String name, MethodData m)
301 final StackMapIterator stackMapIterator = m.createStackMapIterator();
302 TrapDataIterator trap = m.getTrapDataIterator();
303 final LocalsMapper lmapper =
304 new LocalsMapper(stackMapIterator.getArguments());
306 out.append(destObject).append(".").append(name).append(" = function(");
307 lmapper.outputArguments(out, m.isStatic());
308 out.append(") {").append("\n");
310 final byte[] byteCodes = m.getCode();
311 if (byteCodes == null) {
312 out.append(" throw 'no code found for ")
313 .append(jc.getClassName()).append('.')
314 .append(m.getName()).append("';\n");
319 final StackMapper smapper = new StackMapper();
322 out.append(" var ").append(" lcA0 = this;\n");
325 int lastStackFrame = -1;
326 TrapData[] previousTrap = null;
327 boolean wide = false;
329 out.append("\n var gt = 0;\n");
331 int topMostLabel = 0;
332 for (int i = 0; i < byteCodes.length; i++) {
334 stackMapIterator.advanceTo(i);
335 boolean changeInCatch = trap.advanceTo(i);
336 if (changeInCatch || lastStackFrame != stackMapIterator.getFrameIndex()) {
337 if (previousTrap != null) {
338 generateCatch(previousTrap, i, topMostLabel);
342 if (lastStackFrame != stackMapIterator.getFrameIndex()) {
346 if (openBraces > 64) {
347 for (int c = 0; c < 64; c++) {
348 out.append("break;}\n");
354 lastStackFrame = stackMapIterator.getFrameIndex();
355 lmapper.syncWithFrameLocals(stackMapIterator.getFrameLocals());
356 smapper.syncWithFrameStack(stackMapIterator.getFrameStack());
357 out.append(" X_" + i).append(": for (;;) { IF: if (gt <= " + i + ") {\n");
359 changeInCatch = true;
361 debug(" /* " + i + " */ ");
363 if (changeInCatch && trap.useTry()) {
365 previousTrap = trap.current();
367 final int c = readUByte(byteCodes, i);
370 emit(out, "var @1 = @2;", smapper.pushA(), lmapper.getA(0));
373 emit(out, "var @1 = @2;", smapper.pushI(), lmapper.getI(0));
376 emit(out, "var @1 = @2;", smapper.pushL(), lmapper.getL(0));
379 emit(out, "var @1 = @2;", smapper.pushF(), lmapper.getF(0));
382 emit(out, "var @1 = @2;", smapper.pushD(), lmapper.getD(0));
385 emit(out, "var @1 = @2;", smapper.pushA(), lmapper.getA(1));
388 emit(out, "var @1 = @2;", smapper.pushI(), lmapper.getI(1));
391 emit(out, "var @1 = @2;", smapper.pushL(), lmapper.getL(1));
394 emit(out, "var @1 = @2;", smapper.pushF(), lmapper.getF(1));
397 emit(out, "var @1 = @2;", smapper.pushD(), lmapper.getD(1));
400 emit(out, "var @1 = @2;", smapper.pushA(), lmapper.getA(2));
403 emit(out, "var @1 = @2;", smapper.pushI(), lmapper.getI(2));
406 emit(out, "var @1 = @2;", smapper.pushL(), lmapper.getL(2));
409 emit(out, "var @1 = @2;", smapper.pushF(), lmapper.getF(2));
412 emit(out, "var @1 = @2;", smapper.pushD(), lmapper.getD(2));
415 emit(out, "var @1 = @2;", smapper.pushA(), lmapper.getA(3));
418 emit(out, "var @1 = @2;", smapper.pushI(), lmapper.getI(3));
421 emit(out, "var @1 = @2;", smapper.pushL(), lmapper.getL(3));
424 emit(out, "var @1 = @2;", smapper.pushF(), lmapper.getF(3));
427 emit(out, "var @1 = @2;", smapper.pushD(), lmapper.getD(3));
431 final int indx = wide ? readUShort(byteCodes, i++)
432 : readUByte(byteCodes, i);
434 emit(out, "var @1 = @2;",
435 smapper.pushI(), lmapper.getI(indx));
440 final int indx = wide ? readUShort(byteCodes, i++)
441 : readUByte(byteCodes, i);
443 emit(out, "var @1 = @2;",
444 smapper.pushL(), lmapper.getL(indx));
449 final int indx = wide ? readUShort(byteCodes, i++)
450 : readUByte(byteCodes, i);
452 emit(out, "var @1 = @2;",
453 smapper.pushF(), lmapper.getF(indx));
458 final int indx = wide ? readUShort(byteCodes, i++)
459 : readUByte(byteCodes, i);
461 emit(out, "var @1 = @2;",
462 smapper.pushD(), lmapper.getD(indx));
467 final int indx = wide ? readUShort(byteCodes, i++)
468 : readUByte(byteCodes, i);
470 emit(out, "var @1 = @2;",
471 smapper.pushA(), lmapper.getA(indx));
476 final int indx = wide ? readUShort(byteCodes, i++)
477 : readUByte(byteCodes, i);
479 emit(out, "var @1 = @2;",
480 lmapper.setI(indx), smapper.popI());
485 final int indx = wide ? readUShort(byteCodes, i++)
486 : readUByte(byteCodes, i);
488 emit(out, "var @1 = @2;",
489 lmapper.setL(indx), smapper.popL());
494 final int indx = wide ? readUShort(byteCodes, i++)
495 : readUByte(byteCodes, i);
497 emit(out, "var @1 = @2;",
498 lmapper.setF(indx), smapper.popF());
503 final int indx = wide ? readUShort(byteCodes, i++)
504 : readUByte(byteCodes, i);
506 emit(out, "var @1 = @2;",
507 lmapper.setD(indx), smapper.popD());
512 final int indx = wide ? readUShort(byteCodes, i++)
513 : readUByte(byteCodes, i);
515 emit(out, "var @1 = @2;",
516 lmapper.setA(indx), smapper.popA());
520 emit(out, "var @1 = @2;", lmapper.setA(0), smapper.popA());
523 emit(out, "var @1 = @2;", lmapper.setI(0), smapper.popI());
526 emit(out, "var @1 = @2;", lmapper.setL(0), smapper.popL());
529 emit(out, "var @1 = @2;", lmapper.setF(0), smapper.popF());
532 emit(out, "var @1 = @2;", lmapper.setD(0), smapper.popD());
535 emit(out, "var @1 = @2;", lmapper.setA(1), smapper.popA());
538 emit(out, "var @1 = @2;", lmapper.setI(1), smapper.popI());
541 emit(out, "var @1 = @2;", lmapper.setL(1), smapper.popL());
544 emit(out, "var @1 = @2;", lmapper.setF(1), smapper.popF());
547 emit(out, "var @1 = @2;", lmapper.setD(1), smapper.popD());
550 emit(out, "var @1 = @2;", lmapper.setA(2), smapper.popA());
553 emit(out, "var @1 = @2;", lmapper.setI(2), smapper.popI());
556 emit(out, "var @1 = @2;", lmapper.setL(2), smapper.popL());
559 emit(out, "var @1 = @2;", lmapper.setF(2), smapper.popF());
562 emit(out, "var @1 = @2;", lmapper.setD(2), smapper.popD());
565 emit(out, "var @1 = @2;", lmapper.setA(3), smapper.popA());
568 emit(out, "var @1 = @2;", lmapper.setI(3), smapper.popI());
571 emit(out, "var @1 = @2;", lmapper.setL(3), smapper.popL());
574 emit(out, "var @1 = @2;", lmapper.setF(3), smapper.popF());
577 emit(out, "var @1 = @2;", lmapper.setD(3), smapper.popD());
580 emit(out, "@1 = @1.add32(@2);", smapper.getI(1), smapper.popI());
583 emit(out, "@1 = @1.add64(@2);", smapper.getL(1), smapper.popL());
586 emit(out, "@1 += @2;", smapper.getF(1), smapper.popF());
589 emit(out, "@1 += @2;", smapper.getD(1), smapper.popD());
592 emit(out, "@1 = @1.sub32(@2);", smapper.getI(1), smapper.popI());
595 emit(out, "@1 = @1.sub64(@2);", smapper.getL(1), smapper.popL());
598 emit(out, "@1 -= @2;", smapper.getF(1), smapper.popF());
601 emit(out, "@1 -= @2;", smapper.getD(1), smapper.popD());
604 emit(out, "@1 = @1.mul32(@2);", smapper.getI(1), smapper.popI());
607 emit(out, "@1 = @1.mul64(@2);", smapper.getL(1), smapper.popL());
610 emit(out, "@1 *= @2;", smapper.getF(1), smapper.popF());
613 emit(out, "@1 *= @2;", smapper.getD(1), smapper.popD());
616 emit(out, "@1 = @1.div32(@2);",
617 smapper.getI(1), smapper.popI());
620 emit(out, "@1 = @1.div64(@2);",
621 smapper.getL(1), smapper.popL());
624 emit(out, "@1 /= @2;", smapper.getF(1), smapper.popF());
627 emit(out, "@1 /= @2;", smapper.getD(1), smapper.popD());
630 emit(out, "@1 = @1.mod32(@2);",
631 smapper.getI(1), smapper.popI());
634 emit(out, "@1 = @1.mod64(@2);",
635 smapper.getL(1), smapper.popL());
638 emit(out, "@1 %= @2;", smapper.getF(1), smapper.popF());
641 emit(out, "@1 %= @2;", smapper.getD(1), smapper.popD());
644 emit(out, "@1 &= @2;", smapper.getI(1), smapper.popI());
647 emit(out, "@1 = @1.and64(@2);", smapper.getL(1), smapper.popL());
650 emit(out, "@1 |= @2;", smapper.getI(1), smapper.popI());
653 emit(out, "@1 = @1.or64(@2);", smapper.getL(1), smapper.popL());
656 emit(out, "@1 ^= @2;", smapper.getI(1), smapper.popI());
659 emit(out, "@1 = @1.xor64(@2);", smapper.getL(1), smapper.popL());
662 emit(out, "@1 = @1.neg32();", smapper.getI(0));
665 emit(out, "@1 = @1.neg64();", smapper.getL(0));
668 emit(out, "@1 = -@1;", smapper.getF(0));
671 emit(out, "@1 = -@1;", smapper.getD(0));
674 emit(out, "@1 <<= @2;", smapper.getI(1), smapper.popI());
677 emit(out, "@1 = @1.shl64(@2);", smapper.getL(1), smapper.popI());
680 emit(out, "@1 >>= @2;", smapper.getI(1), smapper.popI());
683 emit(out, "@1 = @1.shr64(@2);", smapper.getL(1), smapper.popI());
686 emit(out, "@1 >>>= @2;", smapper.getI(1), smapper.popI());
689 emit(out, "@1 = @1.ushr64(@2);", smapper.getL(1), smapper.popI());
693 final int varIndx = wide ? readUShort(byteCodes, i++)
694 : readUByte(byteCodes, i);
696 final int incrBy = wide ? readShort(byteCodes, i++)
700 emit(out, "@1++;", lmapper.getI(varIndx));
702 emit(out, "@1 += @2;",
703 lmapper.getI(varIndx),
704 Integer.toString(incrBy));
709 emit(out, "return;");
712 emit(out, "return @1;", smapper.popI());
715 emit(out, "return @1;", smapper.popL());
718 emit(out, "return @1;", smapper.popF());
721 emit(out, "return @1;", smapper.popD());
724 emit(out, "return @1;", smapper.popA());
727 emit(out, "var @2 = @1;", smapper.popI(), smapper.pushL());
730 emit(out, "var @2 = @1;", smapper.popI(), smapper.pushF());
733 emit(out, "var @2 = @1;", smapper.popI(), smapper.pushD());
736 emit(out, "var @2 = @1.toInt32();", smapper.popL(), smapper.pushI());
740 emit(out, "var @2 = @1.toFP();", smapper.popL(), smapper.pushF());
743 emit(out, "var @2 = @1.toFP();", smapper.popL(), smapper.pushD());
746 emit(out, "var @2 = @1;", smapper.popF(), smapper.pushD());
749 emit(out, "var @2 = @1;", smapper.popD(), smapper.pushF());
752 emit(out, "var @2 = @1.toInt32();",
753 smapper.popF(), smapper.pushI());
756 emit(out, "var @2 = @1.toLong();",
757 smapper.popF(), smapper.pushL());
760 emit(out, "var @2 = @1.toInt32();",
761 smapper.popD(), smapper.pushI());
764 emit(out, "var @2 = @1.toLong();",
765 smapper.popD(), smapper.pushL());
768 emit(out, "var @1 = @1.toInt8();", smapper.getI(0));
771 out.append("{ /* number conversion */ }");
774 emit(out, "var @1 = @1.toInt16();", smapper.getI(0));
776 case opc_aconst_null:
777 emit(out, "var @1 = null;", smapper.pushA());
780 emit(out, "var @1 = -1;", smapper.pushI());
783 emit(out, "var @1 = 0;", smapper.pushI());
786 emit(out, "var @1 = 0;", smapper.pushD());
789 emit(out, "var @1 = 0;", smapper.pushL());
792 emit(out, "var @1 = 0;", smapper.pushF());
795 emit(out, "var @1 = 1;", smapper.pushI());
798 emit(out, "var @1 = 1;", smapper.pushL());
801 emit(out, "var @1 = 1;", smapper.pushF());
804 emit(out, "var @1 = 1;", smapper.pushD());
807 emit(out, "var @1 = 2;", smapper.pushI());
810 emit(out, "var @1 = 2;", smapper.pushF());
813 emit(out, "var @1 = 3;", smapper.pushI());
816 emit(out, "var @1 = 4;", smapper.pushI());
819 emit(out, "var @1 = 5;", smapper.pushI());
822 int indx = readUByte(byteCodes, ++i);
823 String v = encodeConstant(indx);
824 int type = VarType.fromConstantType(jc.getTag(indx));
825 emit(out, "var @1 = @2;", smapper.pushT(type), v);
830 int indx = readUShortArg(byteCodes, i);
832 String v = encodeConstant(indx);
833 int type = VarType.fromConstantType(jc.getTag(indx));
834 if (type == VarType.LONG) {
835 final Long lv = new Long(v);
836 final int low = (int)(lv.longValue() & 0xFFFFFFFF);
837 final int hi = (int)(lv.longValue() >> 32);
838 emit(out, "var @1 = 0x@3.next32(0x@2);", smapper.pushL(),
839 Integer.toHexString(low), Integer.toHexString(hi));
841 emit(out, "var @1 = @2;", smapper.pushT(type), v);
846 emit(out, "var @3 = @2.compare64(@1);",
847 smapper.popL(), smapper.popL(), smapper.pushI());
851 emit(out, "var @3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
852 smapper.popF(), smapper.popF(), smapper.pushI());
856 emit(out, "var @3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
857 smapper.popD(), smapper.popD(), smapper.pushI());
860 i = generateIf(byteCodes, i, smapper.popA(), smapper.popA(),
861 "===", topMostLabel);
864 i = generateIf(byteCodes, i, smapper.popA(), smapper.popA(),
865 "!==", topMostLabel);
868 i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
872 int indx = i + readShortArg(byteCodes, i);
873 emitIf(out, "if (@1 == 0) ",
874 smapper.popI(), i, indx, topMostLabel);
879 int indx = i + readShortArg(byteCodes, i);
880 emitIf(out, "if (@1 != 0) ",
881 smapper.popI(), i, indx, topMostLabel);
886 int indx = i + readShortArg(byteCodes, i);
887 emitIf(out, "if (@1 < 0) ",
888 smapper.popI(), i, indx, topMostLabel);
893 int indx = i + readShortArg(byteCodes, i);
894 emitIf(out, "if (@1 <= 0) ",
895 smapper.popI(), i, indx, topMostLabel);
900 int indx = i + readShortArg(byteCodes, i);
901 emitIf(out, "if (@1 > 0) ",
902 smapper.popI(), i, indx, topMostLabel);
907 int indx = i + readShortArg(byteCodes, i);
908 emitIf(out, "if (@1 >= 0) ",
909 smapper.popI(), i, indx, topMostLabel);
913 case opc_ifnonnull: {
914 int indx = i + readShortArg(byteCodes, i);
915 emitIf(out, "if (@1 !== null) ",
916 smapper.popA(), i, indx, topMostLabel);
921 int indx = i + readShortArg(byteCodes, i);
922 emitIf(out, "if (@1 === null) ",
923 smapper.popA(), i, indx, topMostLabel);
928 i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
932 i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
936 i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
940 i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
944 i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
948 int indx = i + readShortArg(byteCodes, i);
949 goTo(out, i, indx, topMostLabel);
953 case opc_lookupswitch: {
954 i = generateLookupSwitch(i, byteCodes, smapper, topMostLabel);
957 case opc_tableswitch: {
958 i = generateTableSwitch(i, byteCodes, smapper, topMostLabel);
961 case opc_invokeinterface: {
962 i = invokeVirtualMethod(byteCodes, i, smapper) + 2;
965 case opc_invokevirtual:
966 i = invokeVirtualMethod(byteCodes, i, smapper);
968 case opc_invokespecial:
969 i = invokeStaticMethod(byteCodes, i, smapper, false);
971 case opc_invokestatic:
972 i = invokeStaticMethod(byteCodes, i, smapper, true);
975 int indx = readUShortArg(byteCodes, i);
976 String ci = jc.getClassName(indx);
977 emit(out, "var @1 = new @2;",
978 smapper.pushA(), accessClass(ci.replace('/', '_')));
984 int atype = readUByte(byteCodes, ++i);
985 generateNewArray(atype, smapper);
987 case opc_anewarray: {
988 int type = readUShortArg(byteCodes, i);
990 generateANewArray(type, smapper);
993 case opc_multianewarray: {
994 int type = readUShortArg(byteCodes, i);
996 i = generateMultiANewArray(type, byteCodes, i, smapper);
999 case opc_arraylength:
1000 emit(out, "var @2 = @1.length;",
1001 smapper.popA(), smapper.pushI());
1004 emit(out, "Array.at(@3, @2, @1);",
1005 smapper.popL(), smapper.popI(), smapper.popA());
1008 emit(out, "Array.at(@3, @2, @1);",
1009 smapper.popF(), smapper.popI(), smapper.popA());
1012 emit(out, "Array.at(@3, @2, @1);",
1013 smapper.popD(), smapper.popI(), smapper.popA());
1016 emit(out, "Array.at(@3, @2, @1);",
1017 smapper.popA(), smapper.popI(), smapper.popA());
1023 emit(out, "Array.at(@3, @2, @1);",
1024 smapper.popI(), smapper.popI(), smapper.popA());
1027 emit(out, "var @3 = Array.at(@2, @1);",
1028 smapper.popI(), smapper.popA(), smapper.pushL());
1031 emit(out, "var @3 = Array.at(@2, @1);",
1032 smapper.popI(), smapper.popA(), smapper.pushF());
1035 emit(out, "var @3 = Array.at(@2, @1);",
1036 smapper.popI(), smapper.popA(), smapper.pushD());
1039 emit(out, "var @3 = Array.at(@2, @1);",
1040 smapper.popI(), smapper.popA(), smapper.pushA());
1046 emit(out, "var @3 = Array.at(@2, @1);",
1047 smapper.popI(), smapper.popA(), smapper.pushI());
1055 final Variable v = smapper.get(0);
1056 emit(out, "var @1 = @2;", smapper.pushT(v.getType()), v);
1060 final Variable vi1 = smapper.get(0);
1062 if (vi1.isCategory2()) {
1063 emit(out, "var @1 = @2;",
1064 smapper.pushT(vi1.getType()), vi1);
1066 final Variable vi2 = smapper.get(1);
1067 emit(out, "var @1 = @2, @3 = @4;",
1068 smapper.pushT(vi2.getType()), vi2,
1069 smapper.pushT(vi1.getType()), vi1);
1074 final Variable vi1 = smapper.pop();
1075 final Variable vi2 = smapper.pop();
1076 final Variable vo3 = smapper.pushT(vi1.getType());
1077 final Variable vo2 = smapper.pushT(vi2.getType());
1078 final Variable vo1 = smapper.pushT(vi1.getType());
1080 emit(out, "var @1 = @2, @3 = @4, @5 = @6;",
1081 vo1, vi1, vo2, vi2, vo3, vo1);
1085 final Variable vi1 = smapper.pop();
1086 final Variable vi2 = smapper.pop();
1088 if (vi1.isCategory2()) {
1089 final Variable vo3 = smapper.pushT(vi1.getType());
1090 final Variable vo2 = smapper.pushT(vi2.getType());
1091 final Variable vo1 = smapper.pushT(vi1.getType());
1093 emit(out, "var @1 = @2, @3 = @4, @5 = @6;",
1094 vo1, vi1, vo2, vi2, vo3, vo1);
1096 final Variable vi3 = smapper.pop();
1097 final Variable vo5 = smapper.pushT(vi2.getType());
1098 final Variable vo4 = smapper.pushT(vi1.getType());
1099 final Variable vo3 = smapper.pushT(vi3.getType());
1100 final Variable vo2 = smapper.pushT(vi2.getType());
1101 final Variable vo1 = smapper.pushT(vi1.getType());
1103 emit(out, "var @1 = @2, @3 = @4, @5 = @6,",
1104 vo1, vi1, vo2, vi2, vo3, vi3);
1105 emit(out, " @1 = @2, @3 = @4;",
1106 vo4, vo1, vo5, vo2);
1111 final Variable vi1 = smapper.pop();
1112 final Variable vi2 = smapper.pop();
1114 if (vi2.isCategory2()) {
1115 final Variable vo3 = smapper.pushT(vi1.getType());
1116 final Variable vo2 = smapper.pushT(vi2.getType());
1117 final Variable vo1 = smapper.pushT(vi1.getType());
1119 emit(out, "var @1 = @2, @3 = @4, @5 = @6;",
1120 vo1, vi1, vo2, vi2, vo3, vo1);
1122 final Variable vi3 = smapper.pop();
1123 final Variable vo4 = smapper.pushT(vi1.getType());
1124 final Variable vo3 = smapper.pushT(vi3.getType());
1125 final Variable vo2 = smapper.pushT(vi2.getType());
1126 final Variable vo1 = smapper.pushT(vi1.getType());
1128 emit(out, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1129 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1134 final Variable vi1 = smapper.pop();
1135 final Variable vi2 = smapper.pop();
1137 if (vi1.isCategory2()) {
1138 if (vi2.isCategory2()) {
1139 final Variable vo3 = smapper.pushT(vi1.getType());
1140 final Variable vo2 = smapper.pushT(vi2.getType());
1141 final Variable vo1 = smapper.pushT(vi1.getType());
1143 emit(out, "var @1 = @2, @3 = @4, @5 = @6;",
1144 vo1, vi1, vo2, vi2, vo3, vo1);
1146 final Variable vi3 = smapper.pop();
1147 final Variable vo4 = smapper.pushT(vi1.getType());
1148 final Variable vo3 = smapper.pushT(vi3.getType());
1149 final Variable vo2 = smapper.pushT(vi2.getType());
1150 final Variable vo1 = smapper.pushT(vi1.getType());
1152 emit(out, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1153 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1156 final Variable vi3 = smapper.pop();
1158 if (vi3.isCategory2()) {
1159 final Variable vo5 = smapper.pushT(vi2.getType());
1160 final Variable vo4 = smapper.pushT(vi1.getType());
1161 final Variable vo3 = smapper.pushT(vi3.getType());
1162 final Variable vo2 = smapper.pushT(vi2.getType());
1163 final Variable vo1 = smapper.pushT(vi1.getType());
1165 emit(out, "var @1 = @2, @3 = @4, @5 = @6,",
1166 vo1, vi1, vo2, vi2, vo3, vi3);
1167 emit(out, " @1 = @2, @3 = @4;",
1168 vo4, vo1, vo5, vo2);
1170 final Variable vi4 = smapper.pop();
1171 final Variable vo6 = smapper.pushT(vi2.getType());
1172 final Variable vo5 = smapper.pushT(vi1.getType());
1173 final Variable vo4 = smapper.pushT(vi4.getType());
1174 final Variable vo3 = smapper.pushT(vi3.getType());
1175 final Variable vo2 = smapper.pushT(vi2.getType());
1176 final Variable vo1 = smapper.pushT(vi1.getType());
1178 emit(out, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8,",
1179 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vi4);
1180 emit(out, " @1 = @2, @3 = @4;",
1181 vo5, vo1, vo6, vo2);
1187 final Variable vi1 = smapper.get(0);
1188 final Variable vi2 = smapper.get(1);
1190 if (vi1.getType() == vi2.getType()) {
1191 final Variable tmp = smapper.pushT(vi1.getType());
1193 emit(out, "var @1 = @2, @2 = @3, @3 = @1;",
1198 smapper.pushT(vi1.getType());
1199 smapper.pushT(vi2.getType());
1204 emit(out, "var @1 = @2;",
1205 smapper.pushI(), Integer.toString(byteCodes[++i]));
1208 emit(out, "var @1 = @2;",
1210 Integer.toString(readShortArg(byteCodes, i)));
1213 case opc_getfield: {
1214 int indx = readUShortArg(byteCodes, i);
1215 String[] fi = jc.getFieldInfoName(indx);
1216 final int type = VarType.fromFieldType(fi[2].charAt(0));
1217 final String mangleClass = mangleSig(fi[0]);
1218 final String mangleClassAccess = accessClass(mangleClass);
1219 emit(out, "var @2 = @4(false)._@3.call(@1);",
1221 smapper.pushT(type), fi[1], mangleClassAccess
1226 case opc_putfield: {
1227 int indx = readUShortArg(byteCodes, i);
1228 String[] fi = jc.getFieldInfoName(indx);
1229 final int type = VarType.fromFieldType(fi[2].charAt(0));
1230 final String mangleClass = mangleSig(fi[0]);
1231 final String mangleClassAccess = accessClass(mangleClass);
1232 emit(out, "@4(false)._@3.call(@2, @1);",
1234 smapper.popA(), fi[1],
1240 case opc_getstatic: {
1241 int indx = readUShortArg(byteCodes, i);
1242 String[] fi = jc.getFieldInfoName(indx);
1243 final int type = VarType.fromFieldType(fi[2].charAt(0));
1244 emit(out, "var @1 = @2(false)._@3();",
1245 smapper.pushT(type),
1246 accessClass(fi[0].replace('/', '_')), fi[1]);
1248 addReference(fi[0]);
1251 case opc_putstatic: {
1252 int indx = readUShortArg(byteCodes, i);
1253 String[] fi = jc.getFieldInfoName(indx);
1254 final int type = VarType.fromFieldType(fi[2].charAt(0));
1255 emit(out, "@1(false)._@2(@3);",
1256 accessClass(fi[0].replace('/', '_')), fi[1],
1257 smapper.popT(type));
1259 addReference(fi[0]);
1262 case opc_checkcast: {
1263 int indx = readUShortArg(byteCodes, i);
1264 generateCheckcast(indx, smapper);
1268 case opc_instanceof: {
1269 int indx = readUShortArg(byteCodes, i);
1270 generateInstanceOf(indx, smapper);
1275 final Variable v = smapper.popA();
1278 emit(out, "{ var @1 = @2; throw @2; }",
1279 smapper.pushA(), v);
1283 case opc_monitorenter: {
1284 out.append("/* monitor enter */");
1289 case opc_monitorexit: {
1290 out.append("/* monitor exit */");
1301 emit(out, "throw 'unknown bytecode @1';",
1302 Integer.toString(c));
1306 generateByteCodeComment(prev, i, byteCodes);
1310 if (previousTrap != null) {
1311 generateCatch(previousTrap, byteCodes.length, topMostLabel);
1313 out.append("\n }\n");
1314 while (openBraces-- > 0) {
1320 private int generateIf(byte[] byteCodes, int i, final Variable v2, final Variable v1, final String test, int topMostLabel) throws IOException {
1321 int indx = i + readShortArg(byteCodes, i);
1322 out.append("if (").append(v1)
1323 .append(' ').append(test).append(' ')
1324 .append(v2).append(") ");
1325 goTo(out, i, indx, topMostLabel);
1329 private int readInt4(byte[] byteCodes, int offset) {
1330 final int d = byteCodes[offset + 0] << 24;
1331 final int c = byteCodes[offset + 1] << 16;
1332 final int b = byteCodes[offset + 2] << 8;
1333 final int a = byteCodes[offset + 3];
1334 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
1336 private static int readUByte(byte[] byteCodes, int offset) {
1337 return byteCodes[offset] & 0xff;
1340 private static int readUShort(byte[] byteCodes, int offset) {
1341 return ((byteCodes[offset] & 0xff) << 8)
1342 | (byteCodes[offset + 1] & 0xff);
1344 private static int readUShortArg(byte[] byteCodes, int offsetInstruction) {
1345 return readUShort(byteCodes, offsetInstruction + 1);
1348 private static int readShort(byte[] byteCodes, int offset) {
1349 int signed = byteCodes[offset];
1350 byte b0 = (byte)signed;
1351 return (b0 << 8) | (byteCodes[offset + 1] & 0xff);
1353 private static int readShortArg(byte[] byteCodes, int offsetInstruction) {
1354 return readShort(byteCodes, offsetInstruction + 1);
1357 private static void countArgs(String descriptor, char[] returnType, StringBuilder sig, StringBuilder cnt) {
1359 Boolean count = null;
1360 boolean array = false;
1362 int firstPos = sig.length();
1363 while (i < descriptor.length()) {
1364 char ch = descriptor.charAt(i++);
1385 if (ch == 'J' || ch == 'D') {
1391 sig.insert(firstPos, ch);
1393 returnType[0] = '[';
1394 sig.insert(firstPos, "_3");
1403 returnType[0] = 'V';
1404 sig.insert(firstPos, 'V');
1407 int next = descriptor.indexOf(';', i);
1408 String realSig = mangleSig(descriptor, i - 1, next + 1);
1413 sig.append(realSig);
1416 sig.insert(firstPos, realSig);
1418 sig.insert(firstPos, "_3");
1420 returnType[0] = 'L';
1429 throw new IllegalStateException("Invalid char: " + ch);
1434 static String mangleSig(String sig) {
1435 return mangleSig(sig, 0, sig.length());
1438 private static String mangleSig(String txt, int first, int last) {
1439 StringBuilder sb = new StringBuilder();
1440 for (int i = first; i < last; i++) {
1441 final char ch = txt.charAt(i);
1443 case '/': sb.append('_'); break;
1444 case '_': sb.append("_1"); break;
1445 case ';': sb.append("_2"); break;
1446 case '[': sb.append("_3"); break;
1447 default: sb.append(ch); break;
1450 return sb.toString();
1453 private static String findMethodName(MethodData m, StringBuilder cnt) {
1454 StringBuilder name = new StringBuilder();
1455 if ("<init>".equals(m.getName())) { // NOI18N
1456 name.append("cons"); // NOI18N
1457 } else if ("<clinit>".equals(m.getName())) { // NOI18N
1458 name.append("class"); // NOI18N
1460 name.append(m.getName());
1463 countArgs(m.getInternalSig(), new char[1], name, cnt);
1464 return name.toString();
1467 static String findMethodName(String[] mi, StringBuilder cnt, char[] returnType) {
1468 StringBuilder name = new StringBuilder();
1469 String descr = mi[2];//mi.getDescriptor();
1471 if ("<init>".equals(nm)) { // NOI18N
1472 name.append("cons"); // NOI18N
1476 countArgs(descr, returnType, name, cnt);
1477 return name.toString();
1480 private int invokeStaticMethod(byte[] byteCodes, int i, final StackMapper mapper, boolean isStatic)
1481 throws IOException {
1482 int methodIndex = readUShortArg(byteCodes, i);
1483 String[] mi = jc.getFieldInfoName(methodIndex);
1484 char[] returnType = { 'V' };
1485 StringBuilder cnt = new StringBuilder();
1486 String mn = findMethodName(mi, cnt, returnType);
1488 final int numArguments = isStatic ? cnt.length() : cnt.length() + 1;
1489 final Variable[] vars = new Variable[numArguments];
1491 for (int j = numArguments - 1; j >= 0; --j) {
1492 vars[j] = mapper.pop();
1495 if (returnType[0] != 'V') {
1497 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1501 final String in = mi[0];
1502 out.append(accessClass(in.replace('/', '_')));
1503 out.append("(false).");
1504 if (mn.startsWith("cons_")) {
1505 out.append("constructor.");
1511 out.append(".call(");
1513 if (numArguments > 0) {
1514 out.append(vars[0]);
1515 for (int j = 1; j < numArguments; ++j) {
1517 out.append(vars[j]);
1525 private int invokeVirtualMethod(byte[] byteCodes, int i, final StackMapper mapper)
1526 throws IOException {
1527 int methodIndex = readUShortArg(byteCodes, i);
1528 String[] mi = jc.getFieldInfoName(methodIndex);
1529 char[] returnType = { 'V' };
1530 StringBuilder cnt = new StringBuilder();
1531 String mn = findMethodName(mi, cnt, returnType);
1533 final int numArguments = cnt.length() + 1;
1534 final Variable[] vars = new Variable[numArguments];
1536 for (int j = numArguments - 1; j >= 0; --j) {
1537 vars[j] = mapper.pop();
1540 if (returnType[0] != 'V') {
1542 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1546 out.append(vars[0]).append('.');
1550 for (int j = 1; j < numArguments; ++j) {
1552 out.append(vars[j]);
1560 private void addReference(String cn) throws IOException {
1561 if (requireReference(cn)) {
1562 debug(" /* needs " + cn + " */");
1566 private void outType(String d, StringBuilder out) {
1568 while (d.charAt(0) == '[') {
1572 if (d.charAt(0) == 'L') {
1573 assert d.charAt(d.length() - 1) == ';';
1574 out.append(d.replace('/', '_').substring(0, d.length() - 1));
1580 private String encodeConstant(int entryIndex) throws IOException {
1581 String[] classRef = { null };
1582 String s = jc.stringValue(entryIndex, classRef);
1583 if (classRef[0] != null) {
1584 if (classRef[0].startsWith("[")) {
1585 s = accessClass("java_lang_Class") + "(false).forName__Ljava_lang_Class_2Ljava_lang_String_2('" + classRef[0] + "');";
1587 addReference(classRef[0]);
1588 s = accessClass(s.replace('/', '_')) + "(false).constructor.$class";
1594 private String javaScriptBody(String destObject, MethodData m, boolean isStatic) throws IOException {
1595 byte[] arr = m.findAnnotationData(true);
1599 final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
1600 final String htmlType = "Lnet/java/html/js/JavaScriptBody;";
1601 class P extends AnnotationParser {
1607 String[] args = new String[30];
1612 protected void visitAttr(String type, String attr, String at, String value) {
1613 if (type.equals(jvmType)) {
1614 if ("body".equals(attr)) {
1616 } else if ("args".equals(attr)) {
1617 args[cnt++] = value;
1619 throw new IllegalArgumentException(attr);
1622 if (type.equals(htmlType)) {
1623 if ("body".equals(attr)) {
1625 } else if ("args".equals(attr)) {
1626 args[cnt++] = value;
1627 } else if ("javacall".equals(attr)) {
1628 javacall = "1".equals(value);
1630 throw new IllegalArgumentException(attr);
1637 if (p.body == null) {
1640 StringBuilder cnt = new StringBuilder();
1641 final String mn = findMethodName(m, cnt);
1642 out.append(destObject).append(".").append(mn);
1643 out.append(" = function(");
1646 for (int i = 0; i < cnt.length(); i++) {
1648 space = outputArg(out, p.args, index);
1651 out.append(") {").append("\n");
1653 int lastSlash = jc.getClassName().lastIndexOf('/');
1654 final String pkg = jc.getClassName().substring(0, lastSlash);
1655 out.append(mangleCallbacks(pkg, p.body));
1656 requireReference(pkg + "/$JsCallbacks$");
1660 out.append("\n}\n");
1664 private static CharSequence mangleCallbacks(String pkgName, String body) {
1665 StringBuilder sb = new StringBuilder();
1668 int next = body.indexOf(".@", pos);
1670 sb.append(body.substring(pos));
1671 body = sb.toString();
1676 if (!Character.isJavaIdentifierPart(body.charAt(--ident))) {
1681 String refId = body.substring(ident, next);
1683 sb.append(body.substring(pos, ident));
1685 int sigBeg = body.indexOf('(', next);
1686 int sigEnd = body.indexOf(')', sigBeg);
1687 int colon4 = body.indexOf("::", next);
1688 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
1689 throw new IllegalStateException("Malformed body " + body);
1691 String fqn = body.substring(next + 2, colon4);
1692 String method = body.substring(colon4 + 2, sigBeg);
1693 String params = body.substring(sigBeg, sigEnd + 1);
1695 int paramBeg = body.indexOf('(', sigEnd + 1);
1697 sb.append("vm.").append(pkgName.replace('/', '_')).append("_$JsCallbacks$(false)._VM().");
1698 sb.append(mangle(fqn, method, params, false));
1699 sb.append("(").append(refId);
1700 if (body.charAt(paramBeg + 1) != ')') {
1708 int next = body.indexOf("@", pos);
1713 sb.append(body.substring(pos));
1717 sb = new StringBuilder();
1720 sb.append(body.substring(pos, next));
1722 int sigBeg = body.indexOf('(', next);
1723 int sigEnd = body.indexOf(')', sigBeg);
1724 int colon4 = body.indexOf("::", next);
1725 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
1726 throw new IllegalStateException("Malformed body " + body);
1728 String fqn = body.substring(next + 1, colon4);
1729 String method = body.substring(colon4 + 2, sigBeg);
1730 String params = body.substring(sigBeg, sigEnd + 1);
1732 int paramBeg = body.indexOf('(', sigEnd + 1);
1734 sb.append("vm.").append(pkgName.replace('/', '_')).append("_$JsCallbacks$(false)._VM().");
1735 sb.append(mangle(fqn, method, params, true));
1740 private static String mangle(String fqn, String method, String params, boolean isStatic) {
1741 if (params.startsWith("(")) {
1742 params = params.substring(1);
1744 if (params.endsWith(")")) {
1745 params = params.substring(0, params.length() - 1);
1747 StringBuilder sb = new StringBuilder();
1748 final String rfqn = replace(fqn);
1749 final String rm = replace(method);
1750 final String rp = replace(params);
1751 sb.append(rfqn).append("$").append(rm).
1752 append('$').append(rp).append("__Ljava_lang_Object_2");
1754 sb.append('L').append(rfqn).append("_2");
1757 return sb.toString();
1760 private static String replace(String orig) {
1761 return orig.replace("_", "_1").
1764 replace('.', '_').replace('/', '_');
1767 private static String className(ClassData jc) {
1768 //return jc.getName().getInternalName().replace('/', '_');
1769 return jc.getClassName().replace('/', '_');
1772 private static String[] findAnnotation(
1773 byte[] arr, ClassData cd, final String className,
1774 final String... attrNames
1775 ) throws IOException {
1779 final String[] values = new String[attrNames.length];
1780 final boolean[] found = { false };
1781 final String jvmType = "L" + className.replace('.', '/') + ";";
1782 AnnotationParser ap = new AnnotationParser(false, true) {
1784 protected void visitAttr(String type, String attr, String at, String value) {
1785 if (type.equals(jvmType)) {
1787 for (int i = 0; i < attrNames.length; i++) {
1788 if (attrNames[i].equals(attr)) {
1797 return found[0] ? values : null;
1800 private CharSequence initField(FieldData v) {
1801 final String is = v.getInternalSig();
1802 if (is.length() == 1) {
1803 switch (is.charAt(0)) {
1809 case 'I': return " = 0;";
1811 case 'D': return " = 0.0;";
1813 throw new IllegalStateException(is);
1819 private void generateAnno(ClassData cd, final Appendable out, byte[] data) throws IOException {
1820 AnnotationParser ap = new AnnotationParser(true, false) {
1821 int[] cnt = new int[32];
1825 protected void visitAnnotationStart(String attrType, boolean top) throws IOException {
1826 final String slashType = attrType.substring(1, attrType.length() - 1);
1827 requireReference(slashType);
1829 if (cnt[depth]++ > 0) {
1833 out.append('"').append(attrType).append("\" : ");
1840 protected void visitAnnotationEnd(String type, boolean top) throws IOException {
1841 out.append("\n}\n");
1846 protected void visitValueStart(String attrName, char type) throws IOException {
1847 if (cnt[depth]++ > 0) {
1851 if (attrName != null) {
1852 out.append(attrName).append(" : ");
1860 protected void visitValueEnd(String attrName, char type) throws IOException {
1868 protected void visitAttr(String type, String attr, String attrType, String value)
1869 throws IOException {
1870 if (attr == null && value == null) {
1877 protected void visitEnumAttr(String type, String attr, String attrType, String value)
1878 throws IOException {
1879 final String slashType = attrType.substring(1, attrType.length() - 1);
1880 requireReference(slashType);
1882 out.append(accessClass(slashType.replace('/', '_')))
1883 .append("(false).constructor.fld_").append(value);
1889 private static String outputArg(Appendable out, String[] args, int indx) throws IOException {
1890 final String name = args[indx];
1894 if (name.contains(",")) {
1895 throw new IOException("Wrong parameter with ',': " + name);
1901 private static void emit(final Appendable out,
1902 final String format,
1903 final CharSequence... params) throws IOException {
1904 final int length = format.length();
1907 int paramOffset = format.indexOf('@');
1908 while ((paramOffset != -1) && (paramOffset < (length - 1))) {
1909 final char paramChar = format.charAt(paramOffset + 1);
1910 if ((paramChar >= '1') && (paramChar <= '9')) {
1911 final int paramIndex = paramChar - '0' - 1;
1913 out.append(format, processed, paramOffset);
1914 out.append(params[paramIndex]);
1917 processed = paramOffset + 1;
1920 paramOffset = format.indexOf('@', paramOffset + 1);
1923 out.append(format, processed, length);
1926 private void generateCatch(TrapData[] traps, int current, int topMostLabel) throws IOException {
1927 out.append("} catch (e) {\n");
1929 for (TrapData e : traps) {
1933 if (e.catch_cpx != 0) { //not finally
1934 final String classInternalName = jc.getClassName(e.catch_cpx);
1935 addReference(classInternalName);
1936 out.append("e = vm.java_lang_Throwable(false).bck2BrwsrCnvrt(e);");
1937 out.append("if (e.$instOf_" + classInternalName.replace('/', '_') + ") {");
1938 out.append("var stA0 = e;");
1939 goTo(out, current, e.handler_pc, topMostLabel);
1942 finallyPC = e.handler_pc;
1945 if (finallyPC == -1) {
1946 out.append("throw e;");
1948 out.append("var stA0 = e;");
1949 goTo(out, current, finallyPC, topMostLabel);
1954 private static void goTo(Appendable out, int current, int to, int canBack) throws IOException {
1957 out.append("{ gt = 0; continue X_" + to + "; }");
1959 out.append("{ gt = " + to + "; continue X_0; }");
1962 out.append("{ gt = " + to + "; break IF; }");
1966 private static void emitIf(
1967 Appendable out, String pattern, Variable param,
1968 int current, int to, int canBack
1969 ) throws IOException {
1970 emit(out, pattern, param);
1971 goTo(out, current, to, canBack);
1974 private void generateNewArray(int atype, final StackMapper smapper) throws IOException, IllegalStateException {
1977 case 4: jvmType = "[Z"; break;
1978 case 5: jvmType = "[C"; break;
1979 case 6: jvmType = "[F"; break;
1980 case 7: jvmType = "[D"; break;
1981 case 8: jvmType = "[B"; break;
1982 case 9: jvmType = "[S"; break;
1983 case 10: jvmType = "[I"; break;
1984 case 11: jvmType = "[J"; break;
1985 default: throw new IllegalStateException("Array type: " + atype);
1987 emit(out, "var @2 = Array.prototype.newArray__Ljava_lang_Object_2ZLjava_lang_String_2I(true, '@3', @1);",
1988 smapper.popI(), smapper.pushA(), jvmType);
1991 private void generateANewArray(int type, final StackMapper smapper) throws IOException {
1992 String typeName = jc.getClassName(type);
1993 if (typeName.startsWith("[")) {
1994 typeName = "[" + typeName;
1996 typeName = "[L" + typeName + ";";
1998 emit(out, "var @2 = Array.prototype.newArray__Ljava_lang_Object_2ZLjava_lang_String_2I(false, '@3', @1);",
1999 smapper.popI(), smapper.pushA(), typeName);
2002 private int generateMultiANewArray(int type, final byte[] byteCodes, int i, final StackMapper smapper) throws IOException {
2003 String typeName = jc.getClassName(type);
2004 int dim = readUByte(byteCodes, ++i);
2005 StringBuilder dims = new StringBuilder();
2007 for (int d = 0; d < dim; d++) {
2009 dims.insert(1, ",");
2011 dims.insert(1, smapper.popI());
2014 emit(out, "var @2 = Array.prototype.multiNewArray__Ljava_lang_Object_2Ljava_lang_String_2_3II('@3', @1, 0);",
2015 dims.toString(), smapper.pushA(), typeName);
2019 private int generateTableSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2020 int table = i / 4 * 4 + 4;
2021 int dflt = i + readInt4(byteCodes, table);
2023 int low = readInt4(byteCodes, table);
2025 int high = readInt4(byteCodes, table);
2027 out.append("switch (").append(smapper.popI()).append(") {\n");
2028 while (low <= high) {
2029 int offset = i + readInt4(byteCodes, table);
2031 out.append(" case " + low).append(":"); goTo(out, i, offset, topMostLabel); out.append('\n');
2034 out.append(" default: ");
2035 goTo(out, i, dflt, topMostLabel);
2041 private int generateLookupSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2042 int table = i / 4 * 4 + 4;
2043 int dflt = i + readInt4(byteCodes, table);
2045 int n = readInt4(byteCodes, table);
2047 out.append("switch (").append(smapper.popI()).append(") {\n");
2049 int cnstnt = readInt4(byteCodes, table);
2051 int offset = i + readInt4(byteCodes, table);
2053 out.append(" case " + cnstnt).append(": "); goTo(out, i, offset, topMostLabel); out.append('\n');
2055 out.append(" default: ");
2056 goTo(out, i, dflt, topMostLabel);
2062 private void generateInstanceOf(int indx, final StackMapper smapper) throws IOException {
2063 final String type = jc.getClassName(indx);
2064 if (!type.startsWith("[")) {
2065 emit(out, "var @2 = @1 != null && @1.$instOf_@3 ? 1 : 0;",
2066 smapper.popA(), smapper.pushI(),
2067 type.replace('/', '_'));
2069 emit(out, "var @2 = vm.java_lang_Class(false).forName__Ljava_lang_Class_2Ljava_lang_String_2('@3').isInstance__ZLjava_lang_Object_2(@1);",
2070 smapper.popA(), smapper.pushI(),
2076 private void generateCheckcast(int indx, final StackMapper smapper) throws IOException {
2077 final String type = jc.getClassName(indx);
2078 if (!type.startsWith("[")) {
2080 "if (@1 !== null && !@1.$instOf_@2) throw vm.java_lang_ClassCastException(true);",
2081 smapper.getA(0), type.replace('/', '_'));
2083 emit(out, "vm.java_lang_Class(false).forName__Ljava_lang_Class_2Ljava_lang_String_2('@2').cast__Ljava_lang_Object_2Ljava_lang_Object_2(@1);",
2084 smapper.getA(0), type
2089 private void generateByteCodeComment(int prev, int i, final byte[] byteCodes) throws IOException {
2090 for (int j = prev; j <= i; j++) {
2092 final int cc = readUByte(byteCodes, j);
2093 out.append(Integer.toString(cc));