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 org.apidesign.javap.AnnotationParser;
23 import org.apidesign.javap.ClassData;
24 import org.apidesign.javap.FieldData;
25 import org.apidesign.javap.MethodData;
26 import org.apidesign.javap.StackMapIterator;
27 import static org.apidesign.javap.RuntimeConstants.*;
28 import org.apidesign.javap.TrapData;
29 import org.apidesign.javap.TrapDataIterator;
31 /** Translator of the code inside class files to JavaScript.
33 * @author Jaroslav Tulach <jtulach@netbeans.org>
35 abstract class ByteCodeToJavaScript {
39 protected ByteCodeToJavaScript(Appendable out) {
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);
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;
70 * Converts a given class file to a JavaScript version.
72 * @param classFile input stream with code of the .class file
73 * @return the initialization code for this class, if any. Otherwise <code>null</code>
75 * @throws IOException if something goes wrong during read or write or translating
78 public String compile(InputStream classFile) throws IOException {
79 this.jc = new ClassData(classFile);
80 if (jc.getMajor_version() < 50) {
81 throw new IOException("Can't compile " + jc.getClassName() + ". Class file version " + jc.getMajor_version() + "."
82 + jc.getMinor_version() + " - recompile with -target 1.6 (at least)."
85 byte[] arrData = jc.findAnnotationData(true);
86 String[] arr = findAnnotation(arrData, jc,
87 "org.apidesign.bck2brwsr.core.ExtraJavaScript",
88 "resource", "processByteCode"
91 requireScript(arr[0]);
92 if ("0".equals(arr[1])) {
96 String[] proto = findAnnotation(arrData, jc,
97 "org.apidesign.bck2brwsr.core.JavaScriptPrototype",
98 "container", "prototype"
100 StringArray toInitilize = new StringArray();
101 final String className = className(jc);
102 out.append("\n\n").append(assignClass(className));
103 out.append("function CLS() {");
104 out.append("\n if (!CLS.prototype.$instOf_").append(className).append(") {");
105 for (FieldData v : jc.getFields()) {
107 out.append("\n CLS.").append(v.getName()).append(initField(v));
111 String sc = jc.getSuperClassName(); // with _
112 out.append("\n var pp = ").
113 append(accessClass(sc.replace('/', '_'))).append("(true);");
114 out.append("\n var p = CLS.prototype = pp;");
115 out.append("\n var c = p;");
116 out.append("\n var sprcls = pp.constructor.$class;");
118 out.append("\n var p = CLS.prototype = ").append(proto[1]).append(";");
119 if (proto[0] == null) {
122 out.append("\n var c = ").append(proto[0]).append(";");
123 out.append("\n var sprcls = null;");
125 for (MethodData m : jc.getMethods()) {
126 byte[] onlyArr = m.findAnnotationData(true);
127 String[] only = findAnnotation(onlyArr, jc,
128 "org.apidesign.bck2brwsr.core.JavaScriptOnly",
132 if (only[0] != null && only[1] != null) {
133 out.append("\n p.").append(only[0]).append(" = ")
134 .append(only[1]).append(";");
142 mn = generateStaticMethod(prefix, m, toInitilize);
144 if (m.isConstructor()) {
146 mn = generateInstanceMethod(prefix, m);
149 mn = generateInstanceMethod(prefix, m);
152 byte[] runAnno = m.findAnnotationData(false);
153 if (runAnno != null) {
154 out.append(prefix).append(mn).append(".anno = {");
155 generateAnno(jc, out, runAnno);
158 out.append(prefix).append(mn).append(".access = " + m.getAccess()).append(";");
160 out.append("\n c.constructor = CLS;");
161 out.append("\n c.$instOf_").append(className).append(" = true;");
162 for (String superInterface : jc.getSuperInterfaces()) {
163 out.append("\n c.$instOf_").append(superInterface.replace('/', '_')).append(" = true;");
165 out.append("\n CLS.$class = ");
166 out.append(accessClass("java_lang_Class(true);"));
167 out.append("\n CLS.$class.jvmName = '").append(jc.getClassName()).append("';");
168 out.append("\n CLS.$class.superclass = sprcls;");
169 out.append("\n CLS.$class.access = ").append(jc.getAccessFlags()+";");
170 out.append("\n CLS.$class.cnstr = CLS;");
171 byte[] classAnno = jc.findAnnotationData(false);
172 if (classAnno != null) {
173 out.append("\n CLS.$class.anno = {");
174 generateAnno(jc, out, classAnno);
178 out.append("\n if (arguments.length === 0) {");
179 out.append("\n if (!(this instanceof CLS)) {");
180 out.append("\n return new CLS();");
182 for (FieldData v : jc.getFields()) {
183 byte[] onlyArr = v.findAnnotationData(true);
184 String[] only = findAnnotation(onlyArr, jc,
185 "org.apidesign.bck2brwsr.core.JavaScriptOnly",
189 if (only[0] != null && only[1] != null) {
190 out.append("\n p.").append(only[0]).append(" = ")
191 .append(only[1]).append(";");
196 out.append("\n this.fld_").
197 append(v.getName()).append(initField(v));
200 out.append("\n return this;");
202 out.append("\n return arguments[0] ? new CLS() : CLS.prototype;");
204 StringBuilder sb = new StringBuilder();
205 for (String init : toInitilize.toArray()) {
206 sb.append("\n").append(init).append("();");
208 return sb.toString();
210 private String generateStaticMethod(String prefix, MethodData m, StringArray toInitilize) throws IOException {
211 String jsb = javaScriptBody(prefix, m, true);
215 final String mn = findMethodName(m, new StringBuilder());
216 if (mn.equals("class__V")) {
217 toInitilize.add(accessClass(className(jc)) + "(false)." + mn);
219 generateMethod(prefix, mn, m);
223 private String generateInstanceMethod(String prefix, MethodData m) throws IOException {
224 String jsb = javaScriptBody(prefix, m, false);
228 final String mn = findMethodName(m, new StringBuilder());
229 generateMethod(prefix, mn, m);
233 private void generateMethod(String prefix, String name, MethodData m)
235 final StackMapIterator stackMapIterator = m.createStackMapIterator();
236 TrapDataIterator trap = m.getTrapDataIterator();
237 final LocalsMapper lmapper =
238 new LocalsMapper(stackMapIterator.getArguments());
240 out.append(prefix).append(name).append(" = function(");
241 lmapper.outputArguments(out);
242 out.append(") {").append("\n");
244 final byte[] byteCodes = m.getCode();
245 if (byteCodes == null) {
246 out.append(" throw 'no code found for ")
247 .append(m.getInternalSig()).append("';\n");
252 final StackMapper smapper = new StackMapper();
254 final int maxLocals = m.getMaxLocals();
256 // TODO: generate only used local variables
257 for (int j = 0; j <= VarType.LAST; ++j) {
258 out.append("\n var ").append(Variable.getLocalVariable(j, 0));
259 for (int i = 1; i < maxLocals; ++i) {
261 out.append(Variable.getLocalVariable(j, i));
267 // maxStack includes two stack positions for every pushed long / double
268 // so this might generate more stack variables than we need
269 final int maxStack = m.getMaxStack();
271 // TODO: generate only used stack variables
272 for (int j = 0; j <= VarType.LAST; ++j) {
273 out.append("\n var ").append(Variable.getStackVariable(j, 0));
274 for (int i = 1; i < maxStack; ++i) {
276 out.append(Variable.getStackVariable(j, i));
282 int lastStackFrame = -1;
283 TrapData[] previousTrap = null;
285 out.append("\n var gt = 0;\n for(;;) switch(gt) {\n");
286 for (int i = 0; i < byteCodes.length; i++) {
288 stackMapIterator.advanceTo(i);
289 boolean changeInCatch = trap.advanceTo(i);
290 if (changeInCatch || lastStackFrame != stackMapIterator.getFrameIndex()) {
291 if (previousTrap != null) {
292 generateCatch(previousTrap);
296 if (lastStackFrame != stackMapIterator.getFrameIndex()) {
297 lastStackFrame = stackMapIterator.getFrameIndex();
298 lmapper.syncWithFrameLocals(stackMapIterator.getFrameLocals());
299 smapper.syncWithFrameStack(stackMapIterator.getFrameStack());
300 out.append(" case " + i).append(": ");
301 changeInCatch = true;
303 out.append(" /* " + i).append(" */ ");
305 if (changeInCatch && trap.useTry()) {
307 previousTrap = trap.current();
309 final int c = readByte(byteCodes, i);
312 emit(out, "@1 = @2;", smapper.pushA(), lmapper.getA(0));
315 emit(out, "@1 = @2;", smapper.pushI(), lmapper.getI(0));
318 emit(out, "@1 = @2;", smapper.pushL(), lmapper.getL(0));
321 emit(out, "@1 = @2;", smapper.pushF(), lmapper.getF(0));
324 emit(out, "@1 = @2;", smapper.pushD(), lmapper.getD(0));
327 emit(out, "@1 = @2;", smapper.pushA(), lmapper.getA(1));
330 emit(out, "@1 = @2;", smapper.pushI(), lmapper.getI(1));
333 emit(out, "@1 = @2;", smapper.pushL(), lmapper.getL(1));
336 emit(out, "@1 = @2;", smapper.pushF(), lmapper.getF(1));
339 emit(out, "@1 = @2;", smapper.pushD(), lmapper.getD(1));
342 emit(out, "@1 = @2;", smapper.pushA(), lmapper.getA(2));
345 emit(out, "@1 = @2;", smapper.pushI(), lmapper.getI(2));
348 emit(out, "@1 = @2;", smapper.pushL(), lmapper.getL(2));
351 emit(out, "@1 = @2;", smapper.pushF(), lmapper.getF(2));
354 emit(out, "@1 = @2;", smapper.pushD(), lmapper.getD(2));
357 emit(out, "@1 = @2;", smapper.pushA(), lmapper.getA(3));
360 emit(out, "@1 = @2;", smapper.pushI(), lmapper.getI(3));
363 emit(out, "@1 = @2;", smapper.pushL(), lmapper.getL(3));
366 emit(out, "@1 = @2;", smapper.pushF(), lmapper.getF(3));
369 emit(out, "@1 = @2;", smapper.pushD(), lmapper.getD(3));
372 final int indx = readByte(byteCodes, ++i);
373 emit(out, "@1 = @2;", smapper.pushI(), lmapper.getI(indx));
377 final int indx = readByte(byteCodes, ++i);
378 emit(out, "@1 = @2;", smapper.pushL(), lmapper.getL(indx));
382 final int indx = readByte(byteCodes, ++i);
383 emit(out, "@1 = @2;", smapper.pushF(), lmapper.getF(indx));
387 final int indx = readByte(byteCodes, ++i);
388 emit(out, "@1 = @2;", smapper.pushD(), lmapper.getD(indx));
392 final int indx = readByte(byteCodes, ++i);
393 emit(out, "@1 = @2;", smapper.pushA(), lmapper.getA(indx));
397 final int indx = readByte(byteCodes, ++i);
398 emit(out, "@1 = @2;", lmapper.setI(indx), smapper.popI());
402 final int indx = readByte(byteCodes, ++i);
403 emit(out, "@1 = @2;", lmapper.setL(indx), smapper.popL());
407 final int indx = readByte(byteCodes, ++i);
408 emit(out, "@1 = @2;", lmapper.setF(indx), smapper.popF());
412 final int indx = readByte(byteCodes, ++i);
413 emit(out, "@1 = @2;", lmapper.setD(indx), smapper.popD());
417 final int indx = readByte(byteCodes, ++i);
418 emit(out, "@1 = @2;", lmapper.setA(indx), smapper.popA());
422 emit(out, "@1 = @2;", lmapper.setA(0), smapper.popA());
425 emit(out, "@1 = @2;", lmapper.setI(0), smapper.popI());
428 emit(out, "@1 = @2;", lmapper.setL(0), smapper.popL());
431 emit(out, "@1 = @2;", lmapper.setF(0), smapper.popF());
434 emit(out, "@1 = @2;", lmapper.setD(0), smapper.popD());
437 emit(out, "@1 = @2;", lmapper.setA(1), smapper.popA());
440 emit(out, "@1 = @2;", lmapper.setI(1), smapper.popI());
443 emit(out, "@1 = @2;", lmapper.setL(1), smapper.popL());
446 emit(out, "@1 = @2;", lmapper.setF(1), smapper.popF());
449 emit(out, "@1 = @2;", lmapper.setD(1), smapper.popD());
452 emit(out, "@1 = @2;", lmapper.setA(2), smapper.popA());
455 emit(out, "@1 = @2;", lmapper.setI(2), smapper.popI());
458 emit(out, "@1 = @2;", lmapper.setL(2), smapper.popL());
461 emit(out, "@1 = @2;", lmapper.setF(2), smapper.popF());
464 emit(out, "@1 = @2;", lmapper.setD(2), smapper.popD());
467 emit(out, "@1 = @2;", lmapper.setA(3), smapper.popA());
470 emit(out, "@1 = @2;", lmapper.setI(3), smapper.popI());
473 emit(out, "@1 = @2;", lmapper.setL(3), smapper.popL());
476 emit(out, "@1 = @2;", lmapper.setF(3), smapper.popF());
479 emit(out, "@1 = @2;", lmapper.setD(3), smapper.popD());
482 emit(out, "@1 += @2;", smapper.getI(1), smapper.popI());
485 emit(out, "@1 += @2;", smapper.getL(1), smapper.popL());
488 emit(out, "@1 += @2;", smapper.getF(1), smapper.popF());
491 emit(out, "@1 += @2;", smapper.getD(1), smapper.popD());
494 emit(out, "@1 -= @2;", smapper.getI(1), smapper.popI());
497 emit(out, "@1 -= @2;", smapper.getL(1), smapper.popL());
500 emit(out, "@1 -= @2;", smapper.getF(1), smapper.popF());
503 emit(out, "@1 -= @2;", smapper.getD(1), smapper.popD());
506 emit(out, "@1 *= @2;", smapper.getI(1), smapper.popI());
509 emit(out, "@1 *= @2;", smapper.getL(1), smapper.popL());
512 emit(out, "@1 *= @2;", smapper.getF(1), smapper.popF());
515 emit(out, "@1 *= @2;", smapper.getD(1), smapper.popD());
518 emit(out, "@1 = Math.floor(@1 / @2);",
519 smapper.getI(1), smapper.popI());
522 emit(out, "@1 = Math.floor(@1 / @2);",
523 smapper.getL(1), smapper.popL());
526 emit(out, "@1 /= @2;", smapper.getF(1), smapper.popF());
529 emit(out, "@1 /= @2;", smapper.getD(1), smapper.popD());
532 emit(out, "@1 %= @2;", smapper.getI(1), smapper.popI());
535 emit(out, "@1 %= @2;", smapper.getL(1), smapper.popL());
538 emit(out, "@1 %= @2;", smapper.getF(1), smapper.popF());
541 emit(out, "@1 %= @2;", smapper.getD(1), smapper.popD());
544 emit(out, "@1 &= @2;", smapper.getI(1), smapper.popI());
547 emit(out, "@1 &= @2;", smapper.getL(1), smapper.popL());
550 emit(out, "@1 |= @2;", smapper.getI(1), smapper.popI());
553 emit(out, "@1 |= @2;", smapper.getL(1), smapper.popL());
556 emit(out, "@1 ^= @2;", smapper.getI(1), smapper.popI());
559 emit(out, "@1 ^= @2;", smapper.getL(1), smapper.popL());
562 emit(out, "@1 = -@1;", smapper.getI(0));
565 emit(out, "@1 = -@1;", smapper.getL(0));
568 emit(out, "@1 = -@1;", smapper.getF(0));
571 emit(out, "@1 = -@1;", smapper.getD(0));
574 emit(out, "@1 <<= @2;", smapper.getI(1), smapper.popI());
577 emit(out, "@1 <<= @2;", smapper.getL(1), smapper.popI());
580 emit(out, "@1 >>= @2;", smapper.getI(1), smapper.popI());
583 emit(out, "@1 >>= @2;", smapper.getL(1), smapper.popI());
586 emit(out, "@1 >>>= @2;", smapper.getI(1), smapper.popI());
589 emit(out, "@1 >>>= @2;", smapper.getL(1), smapper.popI());
592 final int varIndx = readByte(byteCodes, ++i);
593 final int incrBy = byteCodes[++i];
595 emit(out, "@1++;", lmapper.getI(varIndx));
597 emit(out, "@1 += @2;",
598 lmapper.getI(varIndx),
599 Integer.toString(incrBy));
604 emit(out, "return;");
607 emit(out, "return @1;", smapper.popI());
610 emit(out, "return @1;", smapper.popL());
613 emit(out, "return @1;", smapper.popF());
616 emit(out, "return @1;", smapper.popD());
619 emit(out, "return @1;", smapper.popA());
622 emit(out, "@2 = @1;", smapper.popI(), smapper.pushL());
625 emit(out, "@2 = @1;", smapper.popI(), smapper.pushF());
628 emit(out, "@2 = @1;", smapper.popI(), smapper.pushD());
631 emit(out, "@2 = @1;", smapper.popL(), smapper.pushI());
635 emit(out, "@2 = @1;", smapper.popL(), smapper.pushF());
638 emit(out, "@2 = @1;", smapper.popL(), smapper.pushD());
641 emit(out, "@2 = @1;", smapper.popF(), smapper.pushD());
644 emit(out, "@2 = @1;", smapper.popD(), smapper.pushF());
647 emit(out, "@2 = Math.floor(@1);",
648 smapper.popF(), smapper.pushI());
651 emit(out, "@2 = Math.floor(@1);",
652 smapper.popF(), smapper.pushL());
655 emit(out, "@2 = Math.floor(@1);",
656 smapper.popD(), smapper.pushI());
659 emit(out, "@2 = Math.floor(@1);",
660 smapper.popD(), smapper.pushL());
665 out.append("{ /* number conversion */ }");
667 case opc_aconst_null:
668 emit(out, "@1 = null;", smapper.pushA());
671 emit(out, "@1 = -1;", smapper.pushI());
674 emit(out, "@1 = 0;", smapper.pushI());
677 emit(out, "@1 = 0;", smapper.pushD());
680 emit(out, "@1 = 0;", smapper.pushL());
683 emit(out, "@1 = 0;", smapper.pushF());
686 emit(out, "@1 = 1;", smapper.pushI());
689 emit(out, "@1 = 1;", smapper.pushL());
692 emit(out, "@1 = 1;", smapper.pushF());
695 emit(out, "@1 = 1;", smapper.pushD());
698 emit(out, "@1 = 2;", smapper.pushI());
701 emit(out, "@1 = 2;", smapper.pushF());
704 emit(out, "@1 = 3;", smapper.pushI());
707 emit(out, "@1 = 4;", smapper.pushI());
710 emit(out, "@1 = 5;", smapper.pushI());
713 int indx = readByte(byteCodes, ++i);
714 String v = encodeConstant(indx);
715 int type = VarType.fromConstantType(jc.getTag(indx));
716 emit(out, "@1 = @2;", smapper.pushT(type), v);
721 int indx = readIntArg(byteCodes, i);
723 String v = encodeConstant(indx);
724 int type = VarType.fromConstantType(jc.getTag(indx));
725 emit(out, "@1 = @2;", smapper.pushT(type), v);
729 emit(out, "@3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
730 smapper.popL(), smapper.popL(), smapper.pushI());
734 emit(out, "@3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
735 smapper.popF(), smapper.popF(), smapper.pushI());
739 emit(out, "@3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
740 smapper.popD(), smapper.popD(), smapper.pushI());
743 i = generateIf(byteCodes, i, smapper.popA(), smapper.popA(),
747 i = generateIf(byteCodes, i, smapper.popA(), smapper.popA(),
751 i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
755 int indx = i + readIntArg(byteCodes, i);
756 emit(out, "if (@1 == 0) { gt = @2; continue; }",
757 smapper.popI(), Integer.toString(indx));
762 int indx = i + readIntArg(byteCodes, i);
763 emit(out, "if (@1 != 0) { gt = @2; continue; }",
764 smapper.popI(), Integer.toString(indx));
769 int indx = i + readIntArg(byteCodes, i);
770 emit(out, "if (@1 < 0) { gt = @2; continue; }",
771 smapper.popI(), Integer.toString(indx));
776 int indx = i + readIntArg(byteCodes, i);
777 emit(out, "if (@1 <= 0) { gt = @2; continue; }",
778 smapper.popI(), Integer.toString(indx));
783 int indx = i + readIntArg(byteCodes, i);
784 emit(out, "if (@1 > 0) { gt = @2; continue; }",
785 smapper.popI(), Integer.toString(indx));
790 int indx = i + readIntArg(byteCodes, i);
791 emit(out, "if (@1 >= 0) { gt = @2; continue; }",
792 smapper.popI(), Integer.toString(indx));
796 case opc_ifnonnull: {
797 int indx = i + readIntArg(byteCodes, i);
798 emit(out, "if (@1 !== null) { gt = @2; continue; }",
799 smapper.popA(), Integer.toString(indx));
804 int indx = i + readIntArg(byteCodes, i);
805 emit(out, "if (@1 === null) { gt = @2; continue; }",
806 smapper.popA(), Integer.toString(indx));
811 i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
815 i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
819 i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
823 i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
827 i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
831 int indx = i + readIntArg(byteCodes, i);
832 emit(out, "gt = @1; continue;", Integer.toString(indx));
836 case opc_lookupswitch: {
837 int table = i / 4 * 4 + 4;
838 int dflt = i + readInt4(byteCodes, table);
840 int n = readInt4(byteCodes, table);
842 out.append("switch (").append(smapper.popI()).append(") {\n");
844 int cnstnt = readInt4(byteCodes, table);
846 int offset = i + readInt4(byteCodes, table);
848 out.append(" case " + cnstnt).append(": gt = " + offset).append("; continue;\n");
850 out.append(" default: gt = " + dflt).append("; continue;\n}");
854 case opc_tableswitch: {
855 int table = i / 4 * 4 + 4;
856 int dflt = i + readInt4(byteCodes, table);
858 int low = readInt4(byteCodes, table);
860 int high = readInt4(byteCodes, table);
862 out.append("switch (").append(smapper.popI()).append(") {\n");
863 while (low <= high) {
864 int offset = i + readInt4(byteCodes, table);
866 out.append(" case " + low).append(": gt = " + offset).append("; continue;\n");
869 out.append(" default: gt = " + dflt).append("; continue;\n}");
873 case opc_invokeinterface: {
874 i = invokeVirtualMethod(byteCodes, i, smapper) + 2;
877 case opc_invokevirtual:
878 i = invokeVirtualMethod(byteCodes, i, smapper);
880 case opc_invokespecial:
881 i = invokeStaticMethod(byteCodes, i, smapper, false);
883 case opc_invokestatic:
884 i = invokeStaticMethod(byteCodes, i, smapper, true);
887 int indx = readIntArg(byteCodes, i);
888 String ci = jc.getClassName(indx);
889 emit(out, "@1 = new @2;",
890 smapper.pushA(), accessClass(ci.replace('/', '_')));
896 ++i; // skip type of array
897 emit(out, "@2 = new Array(@1).fillNulls();",
898 smapper.popI(), smapper.pushA());
901 i += 2; // skip type of array
902 emit(out, "@2 = new Array(@1).fillNulls();",
903 smapper.popI(), smapper.pushA());
905 case opc_multianewarray: {
907 int dim = readByte(byteCodes, ++i);
908 out.append("{ var a0 = new Array(").append(smapper.popI())
909 .append(").fillNulls();");
910 for (int d = 1; d < dim; d++) {
911 out.append("\n var l" + d).append(" = ")
912 .append(smapper.popI()).append(';');
913 out.append("\n for (var i" + d).append (" = 0; i" + d).
914 append(" < a" + (d - 1)).
915 append(".length; i" + d).append("++) {");
916 out.append("\n var a" + d).
917 append (" = new Array(l" + d).append(").fillNulls();");
918 out.append("\n a" + (d - 1)).append("[i" + d).append("] = a" + d).
921 for (int d = 1; d < dim; d++) {
924 out.append("\n").append(smapper.pushA()).append(" = a0; }");
927 case opc_arraylength:
928 emit(out, "@2 = @1.length;", smapper.popA(), smapper.pushI());
931 emit(out, "@3[@2] = @1;",
932 smapper.popL(), smapper.popI(), smapper.popA());
935 emit(out, "@3[@2] = @1;",
936 smapper.popF(), smapper.popI(), smapper.popA());
939 emit(out, "@3[@2] = @1;",
940 smapper.popD(), smapper.popI(), smapper.popA());
943 emit(out, "@3[@2] = @1;",
944 smapper.popA(), smapper.popI(), smapper.popA());
950 emit(out, "@3[@2] = @1;",
951 smapper.popI(), smapper.popI(), smapper.popA());
954 emit(out, "@3 = @2[@1];",
955 smapper.popI(), smapper.popA(), smapper.pushL());
958 emit(out, "@3 = @2[@1];",
959 smapper.popI(), smapper.popA(), smapper.pushF());
962 emit(out, "@3 = @2[@1];",
963 smapper.popI(), smapper.popA(), smapper.pushD());
966 emit(out, "@3 = @2[@1];",
967 smapper.popI(), smapper.popA(), smapper.pushA());
973 emit(out, "@3 = @2[@1];",
974 smapper.popI(), smapper.popA(), smapper.pushI());
979 out.append("/* pop */");
982 final Variable v = smapper.get(0);
983 emit(out, "@1 = @2;", smapper.pushT(v.getType()), v);
987 if (smapper.get(0).isCategory2()) {
988 final Variable v = smapper.get(0);
989 emit(out, "@1 = @2;", smapper.pushT(v.getType()), v);
991 final Variable v1 = smapper.get(0);
992 final Variable v2 = smapper.get(1);
993 emit(out, "{ @1 = @2; @3 = @4; }",
994 smapper.pushT(v2.getType()), v2,
995 smapper.pushT(v1.getType()), v1);
1000 final Variable vi1 = smapper.pop();
1001 final Variable vi2 = smapper.pop();
1002 final Variable vo3 = smapper.pushT(vi1.getType());
1003 final Variable vo2 = smapper.pushT(vi2.getType());
1004 final Variable vo1 = smapper.pushT(vi1.getType());
1006 emit(out, "{ @1 = @2; @3 = @4; @5 = @6; }",
1007 vo1, vi1, vo2, vi2, vo3, vo1);
1011 if (smapper.get(1).isCategory2()) {
1012 final Variable vi1 = smapper.pop();
1013 final Variable vi2 = smapper.pop();
1014 final Variable vo3 = smapper.pushT(vi1.getType());
1015 final Variable vo2 = smapper.pushT(vi2.getType());
1016 final Variable vo1 = smapper.pushT(vi1.getType());
1018 emit(out, "{ @1 = @2; @3 = @4; @5 = @6; }",
1019 vo1, vi1, vo2, vi2, vo3, vo1);
1021 final Variable vi1 = smapper.pop();
1022 final Variable vi2 = smapper.pop();
1023 final Variable vi3 = smapper.pop();
1024 final Variable vo4 = smapper.pushT(vi1.getType());
1025 final Variable vo3 = smapper.pushT(vi3.getType());
1026 final Variable vo2 = smapper.pushT(vi2.getType());
1027 final Variable vo1 = smapper.pushT(vi1.getType());
1029 emit(out, "{ @1 = @2; @3 = @4; @5 = @6; @7 = @8; }",
1030 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1035 emit(out, "@1 = @2;",
1036 smapper.pushI(), Integer.toString(byteCodes[++i]));
1039 emit(out, "@1 = @2;",
1041 Integer.toString(readIntArg(byteCodes, i)));
1044 case opc_getfield: {
1045 int indx = readIntArg(byteCodes, i);
1046 String[] fi = jc.getFieldInfoName(indx);
1047 final int type = VarType.fromFieldType(fi[2].charAt(0));
1048 emit(out, "@2 = @1.fld_@3;",
1049 smapper.popA(), smapper.pushT(type), fi[1]);
1053 case opc_getstatic: {
1054 int indx = readIntArg(byteCodes, i);
1055 String[] fi = jc.getFieldInfoName(indx);
1056 final int type = VarType.fromFieldType(fi[2].charAt(0));
1057 emit(out, "@1 = @2(false).constructor.@3;",
1058 smapper.pushT(type),
1059 accessClass(fi[0].replace('/', '_')), fi[1]);
1061 addReference(fi[0]);
1064 case opc_putfield: {
1065 int indx = readIntArg(byteCodes, i);
1066 String[] fi = jc.getFieldInfoName(indx);
1067 final int type = VarType.fromFieldType(fi[2].charAt(0));
1068 emit(out, "@2.fld_@3 = @1;",
1069 smapper.popT(type), smapper.popA(), fi[1]);
1073 case opc_putstatic: {
1074 int indx = readIntArg(byteCodes, i);
1075 String[] fi = jc.getFieldInfoName(indx);
1076 final int type = VarType.fromFieldType(fi[2].charAt(0));
1077 emit(out, "@1(false).constructor.@2 = @3;",
1078 accessClass(fi[0].replace('/', '_')), fi[1],
1079 smapper.popT(type));
1081 addReference(fi[0]);
1084 case opc_checkcast: {
1085 int indx = readIntArg(byteCodes, i);
1086 final String type = jc.getClassName(indx);
1087 if (!type.startsWith("[")) {
1088 // no way to check arrays right now
1089 // XXX proper exception
1091 "if (@1 !== null && !@1.$instOf_@2) throw {};",
1092 smapper.getA(0), type.replace('/', '_'));
1097 case opc_instanceof: {
1098 int indx = readIntArg(byteCodes, i);
1099 final String type = jc.getClassName(indx);
1100 emit(out, "@2 = @1.$instOf_@3 ? 1 : 0;",
1101 smapper.popA(), smapper.pushI(),
1102 type.replace('/', '_'));
1107 final Variable v = smapper.popA();
1110 emit(out, "{ @1 = @2; throw @2; }",
1111 smapper.pushA(), v);
1115 case opc_monitorenter: {
1116 out.append("/* monitor enter */");
1121 case opc_monitorexit: {
1122 out.append("/* monitor exit */");
1128 emit(out, "throw 'unknown bytecode @1';",
1129 Integer.toString(c));
1133 for (int j = prev; j <= i; j++) {
1135 final int cc = readByte(byteCodes, j);
1136 out.append(Integer.toString(cc));
1140 if (previousTrap != null) {
1141 generateCatch(previousTrap);
1147 private int generateIf(byte[] byteCodes, int i,
1148 final Variable v2, final Variable v1,
1149 final String test) throws IOException {
1150 int indx = i + readIntArg(byteCodes, i);
1151 out.append("if (").append(v1)
1152 .append(' ').append(test).append(' ')
1153 .append(v2).append(") { gt = " + indx)
1154 .append("; continue; }");
1158 private int readIntArg(byte[] byteCodes, int offsetInstruction) {
1159 final int indxHi = byteCodes[offsetInstruction + 1] << 8;
1160 final int indxLo = byteCodes[offsetInstruction + 2];
1161 return (indxHi & 0xffffff00) | (indxLo & 0xff);
1163 private int readInt4(byte[] byteCodes, int offsetInstruction) {
1164 final int d = byteCodes[offsetInstruction + 0] << 24;
1165 final int c = byteCodes[offsetInstruction + 1] << 16;
1166 final int b = byteCodes[offsetInstruction + 2] << 8;
1167 final int a = byteCodes[offsetInstruction + 3];
1168 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
1170 private int readByte(byte[] byteCodes, int offsetInstruction) {
1171 return byteCodes[offsetInstruction] & 0xff;
1174 private static void countArgs(String descriptor, char[] returnType, StringBuilder sig, StringBuilder cnt) {
1176 Boolean count = null;
1177 boolean array = false;
1179 int firstPos = sig.length();
1180 while (i < descriptor.length()) {
1181 char ch = descriptor.charAt(i++);
1202 if (ch == 'J' || ch == 'D') {
1208 sig.insert(firstPos, ch);
1210 returnType[0] = '[';
1211 sig.insert(firstPos, "_3");
1220 returnType[0] = 'V';
1221 sig.insert(firstPos, 'V');
1224 int next = descriptor.indexOf(';', i);
1225 String realSig = mangleSig(descriptor, i - 1, next + 1);
1230 sig.append(realSig);
1233 sig.insert(firstPos, realSig);
1235 sig.insert(firstPos, "_3");
1237 returnType[0] = 'L';
1245 throw new IllegalStateException("Invalid char: " + ch);
1250 private static String mangleSig(String txt, int first, int last) {
1251 StringBuilder sb = new StringBuilder();
1252 for (int i = first; i < last; i++) {
1253 final char ch = txt.charAt(i);
1255 case '/': sb.append('_'); break;
1256 case '_': sb.append("_1"); break;
1257 case ';': sb.append("_2"); break;
1258 case '[': sb.append("_3"); break;
1259 default: sb.append(ch); break;
1262 return sb.toString();
1265 private static String findMethodName(MethodData m, StringBuilder cnt) {
1266 StringBuilder name = new StringBuilder();
1267 if ("<init>".equals(m.getName())) { // NOI18N
1268 name.append("cons"); // NOI18N
1269 } else if ("<clinit>".equals(m.getName())) { // NOI18N
1270 name.append("class"); // NOI18N
1272 name.append(m.getName());
1275 countArgs(m.getInternalSig(), new char[1], name, cnt);
1276 return name.toString();
1279 static String findMethodName(String[] mi, StringBuilder cnt, char[] returnType) {
1280 StringBuilder name = new StringBuilder();
1281 String descr = mi[2];//mi.getDescriptor();
1283 if ("<init>".equals(nm)) { // NOI18N
1284 name.append("cons"); // NOI18N
1288 countArgs(descr, returnType, name, cnt);
1289 return name.toString();
1292 private int invokeStaticMethod(byte[] byteCodes, int i, final StackMapper mapper, boolean isStatic)
1293 throws IOException {
1294 int methodIndex = readIntArg(byteCodes, i);
1295 String[] mi = jc.getFieldInfoName(methodIndex);
1296 char[] returnType = { 'V' };
1297 StringBuilder cnt = new StringBuilder();
1298 String mn = findMethodName(mi, cnt, returnType);
1300 final int numArguments = isStatic ? cnt.length() : cnt.length() + 1;
1301 final Variable[] vars = new Variable[numArguments];
1303 for (int j = numArguments - 1; j >= 0; --j) {
1304 vars[j] = mapper.pop();
1307 if (returnType[0] != 'V') {
1308 out.append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1312 final String in = mi[0];
1313 out.append(accessClass(in.replace('/', '_')));
1314 out.append("(false).");
1315 if (mn.startsWith("cons_")) {
1316 out.append("constructor.");
1320 if (numArguments > 0) {
1321 out.append(vars[0]);
1322 for (int j = 1; j < numArguments; ++j) {
1324 out.append(vars[j]);
1332 private int invokeVirtualMethod(byte[] byteCodes, int i, final StackMapper mapper)
1333 throws IOException {
1334 int methodIndex = readIntArg(byteCodes, i);
1335 String[] mi = jc.getFieldInfoName(methodIndex);
1336 char[] returnType = { 'V' };
1337 StringBuilder cnt = new StringBuilder();
1338 String mn = findMethodName(mi, cnt, returnType);
1340 final int numArguments = cnt.length() + 1;
1341 final Variable[] vars = new Variable[numArguments];
1343 for (int j = numArguments - 1; j >= 0; --j) {
1344 vars[j] = mapper.pop();
1347 if (returnType[0] != 'V') {
1348 out.append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1352 out.append(vars[0]).append('.');
1355 out.append(vars[0]);
1356 for (int j = 1; j < numArguments; ++j) {
1358 out.append(vars[j]);
1365 private void addReference(String cn) throws IOException {
1366 if (requireReference(cn)) {
1367 out.append(" /* needs ").append(cn).append(" */");
1371 private void outType(String d, StringBuilder out) {
1373 while (d.charAt(0) == '[') {
1377 if (d.charAt(0) == 'L') {
1378 assert d.charAt(d.length() - 1) == ';';
1379 out.append(d.replace('/', '_').substring(0, d.length() - 1));
1385 private String encodeConstant(int entryIndex) throws IOException {
1386 String[] classRef = { null };
1387 String s = jc.stringValue(entryIndex, classRef);
1388 if (classRef[0] != null) {
1389 addReference(classRef[0]);
1390 s = accessClass(s.replace('/', '_')) + "(false).constructor.$class";
1395 private String javaScriptBody(String prefix, MethodData m, boolean isStatic) throws IOException {
1396 byte[] arr = m.findAnnotationData(true);
1400 final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
1401 class P extends AnnotationParser {
1407 String[] args = new String[30];
1411 protected void visitAttr(String type, String attr, String at, String value) {
1412 if (type.equals(jvmType)) {
1413 if ("body".equals(attr)) {
1415 } else if ("args".equals(attr)) {
1416 args[cnt++] = value;
1418 throw new IllegalArgumentException(attr);
1425 if (p.body == null) {
1428 StringBuilder cnt = new StringBuilder();
1429 final String mn = findMethodName(m, cnt);
1430 out.append(prefix).append(mn);
1431 out.append(" = function(");
1435 space = outputArg(out, p.args, 0);
1441 for (int i = 0; i < cnt.length(); i++) {
1443 space = outputArg(out, p.args, index);
1446 out.append(") {").append("\n");
1448 out.append("\n}\n");
1451 private static String className(ClassData jc) {
1452 //return jc.getName().getInternalName().replace('/', '_');
1453 return jc.getClassName().replace('/', '_');
1456 private static String[] findAnnotation(
1457 byte[] arr, ClassData cd, final String className,
1458 final String... attrNames
1459 ) throws IOException {
1463 final String[] values = new String[attrNames.length];
1464 final boolean[] found = { false };
1465 final String jvmType = "L" + className.replace('.', '/') + ";";
1466 AnnotationParser ap = new AnnotationParser(false) {
1468 protected void visitAttr(String type, String attr, String at, String value) {
1469 if (type.equals(jvmType)) {
1471 for (int i = 0; i < attrNames.length; i++) {
1472 if (attrNames[i].equals(attr)) {
1481 return found[0] ? values : null;
1484 private CharSequence initField(FieldData v) {
1485 final String is = v.getInternalSig();
1486 if (is.length() == 1) {
1487 switch (is.charAt(0)) {
1493 case 'I': return " = 0;";
1495 case 'D': return " = 0.0;";
1497 throw new IllegalStateException(is);
1503 private static void generateAnno(ClassData cd, final Appendable out, byte[] data) throws IOException {
1504 AnnotationParser ap = new AnnotationParser(true) {
1509 protected void visitAnnotationStart(String type) throws IOException {
1513 out.append('"').append(type).append("\" : {\n");
1518 protected void visitAnnotationEnd(String type) throws IOException {
1519 out.append("\n}\n");
1523 protected void visitAttr(String type, String attr, String attrType, String value)
1524 throws IOException {
1531 out.append(attr).append("__").append(attrType).append(" : ").append(value);
1537 private static String outputArg(Appendable out, String[] args, int indx) throws IOException {
1538 final String name = args[indx];
1542 if (name.contains(",")) {
1543 throw new IOException("Wrong parameter with ',': " + name);
1549 private static void emit(final Appendable out,
1550 final String format,
1551 final CharSequence... params) throws IOException {
1552 final int length = format.length();
1555 int paramOffset = format.indexOf('@');
1556 while ((paramOffset != -1) && (paramOffset < (length - 1))) {
1557 final char paramChar = format.charAt(paramOffset + 1);
1558 if ((paramChar >= '1') && (paramChar <= '9')) {
1559 final int paramIndex = paramChar - '0' - 1;
1561 out.append(format, processed, paramOffset);
1562 out.append(params[paramIndex]);
1565 processed = paramOffset + 1;
1568 paramOffset = format.indexOf('@', paramOffset + 1);
1571 out.append(format, processed, length);
1574 private void generateCatch(TrapData[] traps) throws IOException {
1575 out.append("} catch (e) {");
1576 for (TrapData e : traps) {
1580 if (e.catch_cpx != 0) { //not finally
1581 final String classInternalName = jc.getClassName(e.catch_cpx);
1582 addReference(classInternalName);
1583 out.append("if (e.$instOf_" + classInternalName.replace('/', '_') + ") {");
1584 out.append("gt=" + e.handler_pc + "; stA0 = e; continue;");
1590 out.append("throw e;");