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(";");
140 mn = generateStaticMethod("\n c.", m, toInitilize);
142 mn = generateInstanceMethod("\n c.", m);
144 byte[] runAnno = m.findAnnotationData(false);
145 if (runAnno != null) {
146 out.append("\n c.").append(mn).append(".anno = {");
147 generateAnno(jc, out, runAnno);
151 out.append("\n c.constructor = CLS;");
152 out.append("\n c.$instOf_").append(className).append(" = true;");
153 for (String superInterface : jc.getSuperInterfaces()) {
154 out.append("\n c.$instOf_").append(superInterface.replace('/', '_')).append(" = true;");
156 out.append("\n CLS.$class = ");
157 out.append(accessClass("java_lang_Class(true);"));
158 out.append("\n CLS.$class.jvmName = '").append(jc.getClassName()).append("';");
159 out.append("\n CLS.$class.superclass = sprcls;");
160 out.append("\n CLS.$class.access = ").append(jc.getAccessFlags()+";");
161 out.append("\n CLS.$class.cnstr = CLS;");
162 byte[] classAnno = jc.findAnnotationData(false);
163 if (classAnno != null) {
164 out.append("\n CLS.$class.anno = {");
165 generateAnno(jc, out, classAnno);
169 out.append("\n if (arguments.length === 0) {");
170 out.append("\n if (!(this instanceof CLS)) {");
171 out.append("\n return new CLS();");
173 for (FieldData v : jc.getFields()) {
174 byte[] onlyArr = v.findAnnotationData(true);
175 String[] only = findAnnotation(onlyArr, jc,
176 "org.apidesign.bck2brwsr.core.JavaScriptOnly",
180 if (only[0] != null && only[1] != null) {
181 out.append("\n p.").append(only[0]).append(" = ")
182 .append(only[1]).append(";");
187 out.append("\n this.fld_").
188 append(v.getName()).append(initField(v));
191 out.append("\n return this;");
193 out.append("\n return arguments[0] ? new CLS() : CLS.prototype;");
195 StringBuilder sb = new StringBuilder();
196 for (String init : toInitilize.toArray()) {
197 sb.append("\n").append(init).append("();");
199 return sb.toString();
201 private String generateStaticMethod(String prefix, MethodData m, StringArray toInitilize) throws IOException {
202 String jsb = javaScriptBody(prefix, m, true);
206 final String mn = findMethodName(m, new StringBuilder());
207 if (mn.equals("class__V")) {
208 toInitilize.add(accessClass(className(jc)) + "(false)." + mn);
210 generateMethod(prefix, mn, m);
214 private String generateInstanceMethod(String prefix, MethodData m) throws IOException {
215 String jsb = javaScriptBody(prefix, m, false);
219 final String mn = findMethodName(m, new StringBuilder());
220 generateMethod(prefix, mn, m);
224 private void generateMethod(String prefix, String name, MethodData m)
226 final StackMapIterator stackMapIterator = m.createStackMapIterator();
227 TrapDataIterator trap = m.getTrapDataIterator();
228 final LocalsMapper lmapper =
229 new LocalsMapper(stackMapIterator.getArguments());
231 out.append(prefix).append(name).append(" = function(");
232 lmapper.outputArguments(out);
233 out.append(") {").append("\n");
235 final byte[] byteCodes = m.getCode();
236 if (byteCodes == null) {
237 out.append(" throw 'no code found for ")
238 .append(m.getInternalSig()).append("';\n");
243 final StackMapper smapper = new StackMapper();
245 final int maxLocals = m.getMaxLocals();
247 // TODO: generate only used local variables
248 for (int j = 0; j <= VarType.LAST; ++j) {
249 out.append("\n var ").append(Variable.getLocalVariable(j, 0));
250 for (int i = 1; i < maxLocals; ++i) {
252 out.append(Variable.getLocalVariable(j, i));
258 // maxStack includes two stack positions for every pushed long / double
259 // so this might generate more stack variables than we need
260 final int maxStack = m.getMaxStack();
262 // TODO: generate only used stack variables
263 for (int j = 0; j <= VarType.LAST; ++j) {
264 out.append("\n var ").append(Variable.getStackVariable(j, 0));
265 for (int i = 1; i < maxStack; ++i) {
267 out.append(Variable.getStackVariable(j, i));
273 int lastStackFrame = -1;
275 out.append("\n var gt = 0;\n for(;;) switch(gt) {\n");
276 for (int i = 0; i < byteCodes.length; i++) {
278 stackMapIterator.advanceTo(i);
280 if (lastStackFrame != stackMapIterator.getFrameIndex()) {
281 lastStackFrame = stackMapIterator.getFrameIndex();
282 lmapper.syncWithFrameLocals(stackMapIterator.getFrameLocals());
283 smapper.syncWithFrameStack(stackMapIterator.getFrameStack());
284 out.append(" case " + i).append(": ");
286 out.append(" /* " + i).append(" */ ");
291 final int c = readByte(byteCodes, i);
294 emit(out, "@1 = @2;", smapper.pushA(), lmapper.getA(0));
297 emit(out, "@1 = @2;", smapper.pushI(), lmapper.getI(0));
300 emit(out, "@1 = @2;", smapper.pushL(), lmapper.getL(0));
303 emit(out, "@1 = @2;", smapper.pushF(), lmapper.getF(0));
306 emit(out, "@1 = @2;", smapper.pushD(), lmapper.getD(0));
309 emit(out, "@1 = @2;", smapper.pushA(), lmapper.getA(1));
312 emit(out, "@1 = @2;", smapper.pushI(), lmapper.getI(1));
315 emit(out, "@1 = @2;", smapper.pushL(), lmapper.getL(1));
318 emit(out, "@1 = @2;", smapper.pushF(), lmapper.getF(1));
321 emit(out, "@1 = @2;", smapper.pushD(), lmapper.getD(1));
324 emit(out, "@1 = @2;", smapper.pushA(), lmapper.getA(2));
327 emit(out, "@1 = @2;", smapper.pushI(), lmapper.getI(2));
330 emit(out, "@1 = @2;", smapper.pushL(), lmapper.getL(2));
333 emit(out, "@1 = @2;", smapper.pushF(), lmapper.getF(2));
336 emit(out, "@1 = @2;", smapper.pushD(), lmapper.getD(2));
339 emit(out, "@1 = @2;", smapper.pushA(), lmapper.getA(3));
342 emit(out, "@1 = @2;", smapper.pushI(), lmapper.getI(3));
345 emit(out, "@1 = @2;", smapper.pushL(), lmapper.getL(3));
348 emit(out, "@1 = @2;", smapper.pushF(), lmapper.getF(3));
351 emit(out, "@1 = @2;", smapper.pushD(), lmapper.getD(3));
354 final int indx = readByte(byteCodes, ++i);
355 emit(out, "@1 = @2;", smapper.pushI(), lmapper.getI(indx));
359 final int indx = readByte(byteCodes, ++i);
360 emit(out, "@1 = @2;", smapper.pushL(), lmapper.getL(indx));
364 final int indx = readByte(byteCodes, ++i);
365 emit(out, "@1 = @2;", smapper.pushF(), lmapper.getF(indx));
369 final int indx = readByte(byteCodes, ++i);
370 emit(out, "@1 = @2;", smapper.pushD(), lmapper.getD(indx));
374 final int indx = readByte(byteCodes, ++i);
375 emit(out, "@1 = @2;", smapper.pushA(), lmapper.getA(indx));
379 final int indx = readByte(byteCodes, ++i);
380 emit(out, "@1 = @2;", lmapper.setI(indx), smapper.popI());
384 final int indx = readByte(byteCodes, ++i);
385 emit(out, "@1 = @2;", lmapper.setL(indx), smapper.popL());
389 final int indx = readByte(byteCodes, ++i);
390 emit(out, "@1 = @2;", lmapper.setF(indx), smapper.popF());
394 final int indx = readByte(byteCodes, ++i);
395 emit(out, "@1 = @2;", lmapper.setD(indx), smapper.popD());
399 final int indx = readByte(byteCodes, ++i);
400 emit(out, "@1 = @2;", lmapper.setA(indx), smapper.popA());
404 emit(out, "@1 = @2;", lmapper.setA(0), smapper.popA());
407 emit(out, "@1 = @2;", lmapper.setI(0), smapper.popI());
410 emit(out, "@1 = @2;", lmapper.setL(0), smapper.popL());
413 emit(out, "@1 = @2;", lmapper.setF(0), smapper.popF());
416 emit(out, "@1 = @2;", lmapper.setD(0), smapper.popD());
419 emit(out, "@1 = @2;", lmapper.setA(1), smapper.popA());
422 emit(out, "@1 = @2;", lmapper.setI(1), smapper.popI());
425 emit(out, "@1 = @2;", lmapper.setL(1), smapper.popL());
428 emit(out, "@1 = @2;", lmapper.setF(1), smapper.popF());
431 emit(out, "@1 = @2;", lmapper.setD(1), smapper.popD());
434 emit(out, "@1 = @2;", lmapper.setA(2), smapper.popA());
437 emit(out, "@1 = @2;", lmapper.setI(2), smapper.popI());
440 emit(out, "@1 = @2;", lmapper.setL(2), smapper.popL());
443 emit(out, "@1 = @2;", lmapper.setF(2), smapper.popF());
446 emit(out, "@1 = @2;", lmapper.setD(2), smapper.popD());
449 emit(out, "@1 = @2;", lmapper.setA(3), smapper.popA());
452 emit(out, "@1 = @2;", lmapper.setI(3), smapper.popI());
455 emit(out, "@1 = @2;", lmapper.setL(3), smapper.popL());
458 emit(out, "@1 = @2;", lmapper.setF(3), smapper.popF());
461 emit(out, "@1 = @2;", lmapper.setD(3), smapper.popD());
464 emit(out, "@1 += @2;", smapper.getI(1), smapper.popI());
467 emit(out, "@1 += @2;", smapper.getL(1), smapper.popL());
470 emit(out, "@1 += @2;", smapper.getF(1), smapper.popF());
473 emit(out, "@1 += @2;", smapper.getD(1), smapper.popD());
476 emit(out, "@1 -= @2;", smapper.getI(1), smapper.popI());
479 emit(out, "@1 -= @2;", smapper.getL(1), smapper.popL());
482 emit(out, "@1 -= @2;", smapper.getF(1), smapper.popF());
485 emit(out, "@1 -= @2;", smapper.getD(1), smapper.popD());
488 emit(out, "@1 *= @2;", smapper.getI(1), smapper.popI());
491 emit(out, "@1 *= @2;", smapper.getL(1), smapper.popL());
494 emit(out, "@1 *= @2;", smapper.getF(1), smapper.popF());
497 emit(out, "@1 *= @2;", smapper.getD(1), smapper.popD());
500 emit(out, "@1 = Math.floor(@1 / @2);",
501 smapper.getI(1), smapper.popI());
504 emit(out, "@1 = Math.floor(@1 / @2);",
505 smapper.getL(1), smapper.popL());
508 emit(out, "@1 /= @2;", smapper.getF(1), smapper.popF());
511 emit(out, "@1 /= @2;", smapper.getD(1), smapper.popD());
514 emit(out, "@1 %= @2;", smapper.getI(1), smapper.popI());
517 emit(out, "@1 %= @2;", smapper.getL(1), smapper.popL());
520 emit(out, "@1 %= @2;", smapper.getF(1), smapper.popF());
523 emit(out, "@1 %= @2;", smapper.getD(1), smapper.popD());
526 emit(out, "@1 &= @2;", smapper.getI(1), smapper.popI());
529 emit(out, "@1 &= @2;", smapper.getL(1), smapper.popL());
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.getI(1), smapper.popI());
541 emit(out, "@1 ^= @2;", smapper.getL(1), smapper.popL());
544 emit(out, "@1 = -@1;", smapper.getI(0));
547 emit(out, "@1 = -@1;", smapper.getL(0));
550 emit(out, "@1 = -@1;", smapper.getF(0));
553 emit(out, "@1 = -@1;", smapper.getD(0));
556 emit(out, "@1 <<= @2;", smapper.getI(1), smapper.popI());
559 emit(out, "@1 <<= @2;", smapper.getL(1), smapper.popI());
562 emit(out, "@1 >>= @2;", smapper.getI(1), smapper.popI());
565 emit(out, "@1 >>= @2;", smapper.getL(1), smapper.popI());
568 emit(out, "@1 >>>= @2;", smapper.getI(1), smapper.popI());
571 emit(out, "@1 >>>= @2;", smapper.getL(1), smapper.popI());
574 final int varIndx = readByte(byteCodes, ++i);
575 final int incrBy = byteCodes[++i];
577 emit(out, "@1++;", lmapper.getI(varIndx));
579 emit(out, "@1 += @2;",
580 lmapper.getI(varIndx),
581 Integer.toString(incrBy));
586 emit(out, "return;");
589 emit(out, "return @1;", smapper.popI());
592 emit(out, "return @1;", smapper.popL());
595 emit(out, "return @1;", smapper.popF());
598 emit(out, "return @1;", smapper.popD());
601 emit(out, "return @1;", smapper.popA());
604 emit(out, "@2 = @1;", smapper.popI(), smapper.pushL());
607 emit(out, "@2 = @1;", smapper.popI(), smapper.pushF());
610 emit(out, "@2 = @1;", smapper.popI(), smapper.pushD());
613 emit(out, "@2 = @1;", smapper.popL(), smapper.pushI());
617 emit(out, "@2 = @1;", smapper.popL(), smapper.pushF());
620 emit(out, "@2 = @1;", smapper.popL(), smapper.pushD());
623 emit(out, "@2 = @1;", smapper.popF(), smapper.pushD());
626 emit(out, "@2 = @1;", smapper.popD(), smapper.pushF());
629 emit(out, "@2 = Math.floor(@1);",
630 smapper.popF(), smapper.pushI());
633 emit(out, "@2 = Math.floor(@1);",
634 smapper.popF(), smapper.pushL());
637 emit(out, "@2 = Math.floor(@1);",
638 smapper.popD(), smapper.pushI());
641 emit(out, "@2 = Math.floor(@1);",
642 smapper.popD(), smapper.pushL());
647 out.append("{ /* number conversion */ }");
649 case opc_aconst_null:
650 emit(out, "@1 = null;", smapper.pushA());
653 emit(out, "@1 = -1;", smapper.pushI());
656 emit(out, "@1 = 0;", smapper.pushI());
659 emit(out, "@1 = 0;", smapper.pushD());
662 emit(out, "@1 = 0;", smapper.pushL());
665 emit(out, "@1 = 0;", smapper.pushF());
668 emit(out, "@1 = 1;", smapper.pushI());
671 emit(out, "@1 = 1;", smapper.pushL());
674 emit(out, "@1 = 1;", smapper.pushF());
677 emit(out, "@1 = 1;", smapper.pushD());
680 emit(out, "@1 = 2;", smapper.pushI());
683 emit(out, "@1 = 2;", smapper.pushF());
686 emit(out, "@1 = 3;", smapper.pushI());
689 emit(out, "@1 = 4;", smapper.pushI());
692 emit(out, "@1 = 5;", smapper.pushI());
695 int indx = readByte(byteCodes, ++i);
696 String v = encodeConstant(indx);
697 int type = VarType.fromConstantType(jc.getTag(indx));
698 emit(out, "@1 = @2;", smapper.pushT(type), v);
703 int indx = readIntArg(byteCodes, i);
705 String v = encodeConstant(indx);
706 int type = VarType.fromConstantType(jc.getTag(indx));
707 emit(out, "@1 = @2;", smapper.pushT(type), v);
711 emit(out, "@3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
712 smapper.popL(), smapper.popL(), smapper.pushI());
716 emit(out, "@3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
717 smapper.popF(), smapper.popF(), smapper.pushI());
721 emit(out, "@3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
722 smapper.popD(), smapper.popD(), smapper.pushI());
725 i = generateIf(byteCodes, i, smapper.popA(), smapper.popA(),
729 i = generateIf(byteCodes, i, smapper.popA(), smapper.popA(),
733 i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
737 int indx = i + readIntArg(byteCodes, i);
738 emit(out, "if (@1 == 0) { gt = @2; continue; }",
739 smapper.popI(), Integer.toString(indx));
744 int indx = i + readIntArg(byteCodes, i);
745 emit(out, "if (@1 != 0) { gt = @2; continue; }",
746 smapper.popI(), Integer.toString(indx));
751 int indx = i + readIntArg(byteCodes, i);
752 emit(out, "if (@1 < 0) { gt = @2; continue; }",
753 smapper.popI(), Integer.toString(indx));
758 int indx = i + readIntArg(byteCodes, i);
759 emit(out, "if (@1 <= 0) { gt = @2; continue; }",
760 smapper.popI(), Integer.toString(indx));
765 int indx = i + readIntArg(byteCodes, i);
766 emit(out, "if (@1 > 0) { gt = @2; continue; }",
767 smapper.popI(), Integer.toString(indx));
772 int indx = i + readIntArg(byteCodes, i);
773 emit(out, "if (@1 >= 0) { gt = @2; continue; }",
774 smapper.popI(), Integer.toString(indx));
778 case opc_ifnonnull: {
779 int indx = i + readIntArg(byteCodes, i);
780 emit(out, "if (@1 !== null) { gt = @2; continue; }",
781 smapper.popA(), Integer.toString(indx));
786 int indx = i + readIntArg(byteCodes, i);
787 emit(out, "if (@1 === null) { gt = @2; continue; }",
788 smapper.popA(), Integer.toString(indx));
793 i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
797 i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
801 i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
805 i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
809 i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
813 int indx = i + readIntArg(byteCodes, i);
814 emit(out, "gt = @1; continue;", Integer.toString(indx));
818 case opc_lookupswitch: {
819 int table = i / 4 * 4 + 4;
820 int dflt = i + readInt4(byteCodes, table);
822 int n = readInt4(byteCodes, table);
824 out.append("switch (").append(smapper.popI()).append(") {\n");
826 int cnstnt = readInt4(byteCodes, table);
828 int offset = i + readInt4(byteCodes, table);
830 out.append(" case " + cnstnt).append(": gt = " + offset).append("; continue;\n");
832 out.append(" default: gt = " + dflt).append("; continue;\n}");
836 case opc_tableswitch: {
837 int table = i / 4 * 4 + 4;
838 int dflt = i + readInt4(byteCodes, table);
840 int low = readInt4(byteCodes, table);
842 int high = readInt4(byteCodes, table);
844 out.append("switch (").append(smapper.popI()).append(") {\n");
845 while (low <= high) {
846 int offset = i + readInt4(byteCodes, table);
848 out.append(" case " + low).append(": gt = " + offset).append("; continue;\n");
851 out.append(" default: gt = " + dflt).append("; continue;\n}");
855 case opc_invokeinterface: {
856 i = invokeVirtualMethod(byteCodes, i, smapper) + 2;
859 case opc_invokevirtual:
860 i = invokeVirtualMethod(byteCodes, i, smapper);
862 case opc_invokespecial:
863 i = invokeStaticMethod(byteCodes, i, smapper, false);
865 case opc_invokestatic:
866 i = invokeStaticMethod(byteCodes, i, smapper, true);
869 int indx = readIntArg(byteCodes, i);
870 String ci = jc.getClassName(indx);
871 emit(out, "@1 = new @2;",
872 smapper.pushA(), accessClass(ci.replace('/', '_')));
878 ++i; // skip type of array
879 emit(out, "@2 = new Array(@1).fillNulls();",
880 smapper.popI(), smapper.pushA());
883 i += 2; // skip type of array
884 emit(out, "@2 = new Array(@1).fillNulls();",
885 smapper.popI(), smapper.pushA());
887 case opc_multianewarray: {
889 int dim = readByte(byteCodes, ++i);
890 out.append("{ var a0 = new Array(").append(smapper.popI())
891 .append(").fillNulls();");
892 for (int d = 1; d < dim; d++) {
893 out.append("\n var l" + d).append(" = ")
894 .append(smapper.popI()).append(';');
895 out.append("\n for (var i" + d).append (" = 0; i" + d).
896 append(" < a" + (d - 1)).
897 append(".length; i" + d).append("++) {");
898 out.append("\n var a" + d).
899 append (" = new Array(l" + d).append(").fillNulls();");
900 out.append("\n a" + (d - 1)).append("[i" + d).append("] = a" + d).
903 for (int d = 1; d < dim; d++) {
906 out.append("\n").append(smapper.pushA()).append(" = a0; }");
909 case opc_arraylength:
910 emit(out, "@2 = @1.length;", smapper.popA(), smapper.pushI());
913 emit(out, "@3[@2] = @1;",
914 smapper.popL(), smapper.popI(), smapper.popA());
917 emit(out, "@3[@2] = @1;",
918 smapper.popF(), smapper.popI(), smapper.popA());
921 emit(out, "@3[@2] = @1;",
922 smapper.popD(), smapper.popI(), smapper.popA());
925 emit(out, "@3[@2] = @1;",
926 smapper.popA(), smapper.popI(), smapper.popA());
932 emit(out, "@3[@2] = @1;",
933 smapper.popI(), smapper.popI(), smapper.popA());
936 emit(out, "@3 = @2[@1];",
937 smapper.popI(), smapper.popA(), smapper.pushL());
940 emit(out, "@3 = @2[@1];",
941 smapper.popI(), smapper.popA(), smapper.pushF());
944 emit(out, "@3 = @2[@1];",
945 smapper.popI(), smapper.popA(), smapper.pushD());
948 emit(out, "@3 = @2[@1];",
949 smapper.popI(), smapper.popA(), smapper.pushA());
955 emit(out, "@3 = @2[@1];",
956 smapper.popI(), smapper.popA(), smapper.pushI());
961 out.append("/* pop */");
964 final Variable v = smapper.get(0);
965 emit(out, "@1 = @2;", smapper.pushT(v.getType()), v);
969 if (smapper.get(0).isCategory2()) {
970 final Variable v = smapper.get(0);
971 emit(out, "@1 = @2;", smapper.pushT(v.getType()), v);
973 final Variable v1 = smapper.get(0);
974 final Variable v2 = smapper.get(1);
975 emit(out, "{ @1 = @2; @3 = @4; }",
976 smapper.pushT(v2.getType()), v2,
977 smapper.pushT(v1.getType()), v1);
982 final Variable vi1 = smapper.pop();
983 final Variable vi2 = smapper.pop();
984 final Variable vo3 = smapper.pushT(vi1.getType());
985 final Variable vo2 = smapper.pushT(vi2.getType());
986 final Variable vo1 = smapper.pushT(vi1.getType());
988 emit(out, "{ @1 = @2; @3 = @4; @5 = @6; }",
989 vo1, vi1, vo2, vi2, vo3, vo1);
993 if (smapper.get(1).isCategory2()) {
994 final Variable vi1 = smapper.pop();
995 final Variable vi2 = smapper.pop();
996 final Variable vo3 = smapper.pushT(vi1.getType());
997 final Variable vo2 = smapper.pushT(vi2.getType());
998 final Variable vo1 = smapper.pushT(vi1.getType());
1000 emit(out, "{ @1 = @2; @3 = @4; @5 = @6; }",
1001 vo1, vi1, vo2, vi2, vo3, vo1);
1003 final Variable vi1 = smapper.pop();
1004 final Variable vi2 = smapper.pop();
1005 final Variable vi3 = smapper.pop();
1006 final Variable vo4 = smapper.pushT(vi1.getType());
1007 final Variable vo3 = smapper.pushT(vi3.getType());
1008 final Variable vo2 = smapper.pushT(vi2.getType());
1009 final Variable vo1 = smapper.pushT(vi1.getType());
1011 emit(out, "{ @1 = @2; @3 = @4; @5 = @6; @7 = @8; }",
1012 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1017 emit(out, "@1 = @2;",
1018 smapper.pushI(), Integer.toString(byteCodes[++i]));
1021 emit(out, "@1 = @2;",
1023 Integer.toString(readIntArg(byteCodes, i)));
1026 case opc_getfield: {
1027 int indx = readIntArg(byteCodes, i);
1028 String[] fi = jc.getFieldInfoName(indx);
1029 final int type = VarType.fromFieldType(fi[2].charAt(0));
1030 emit(out, "@2 = @1.fld_@3;",
1031 smapper.popA(), smapper.pushT(type), fi[1]);
1035 case opc_getstatic: {
1036 int indx = readIntArg(byteCodes, i);
1037 String[] fi = jc.getFieldInfoName(indx);
1038 final int type = VarType.fromFieldType(fi[2].charAt(0));
1039 emit(out, "@1 = @2(false).constructor.@3;",
1040 smapper.pushT(type),
1041 accessClass(fi[0].replace('/', '_')), fi[1]);
1043 addReference(fi[0]);
1046 case opc_putfield: {
1047 int indx = readIntArg(byteCodes, i);
1048 String[] fi = jc.getFieldInfoName(indx);
1049 final int type = VarType.fromFieldType(fi[2].charAt(0));
1050 emit(out, "@2.fld_@3 = @1;",
1051 smapper.popT(type), smapper.popA(), fi[1]);
1055 case opc_putstatic: {
1056 int indx = readIntArg(byteCodes, i);
1057 String[] fi = jc.getFieldInfoName(indx);
1058 final int type = VarType.fromFieldType(fi[2].charAt(0));
1059 emit(out, "@1(false).constructor.@2 = @3;",
1060 accessClass(fi[0].replace('/', '_')), fi[1],
1061 smapper.popT(type));
1063 addReference(fi[0]);
1066 case opc_checkcast: {
1067 int indx = readIntArg(byteCodes, i);
1068 final String type = jc.getClassName(indx);
1069 if (!type.startsWith("[")) {
1070 // no way to check arrays right now
1071 // XXX proper exception
1073 "if (@1 !== null && !@1.$instOf_@2) throw {};",
1074 smapper.getA(0), type.replace('/', '_'));
1079 case opc_instanceof: {
1080 int indx = readIntArg(byteCodes, i);
1081 final String type = jc.getClassName(indx);
1082 emit(out, "@2 = @1.$instOf_@3 ? 1 : 0;",
1083 smapper.popA(), smapper.pushI(),
1084 type.replace('/', '_'));
1089 final Variable v = smapper.popA();
1092 emit(out, "{ @1 = @2; throw @2; }",
1093 smapper.pushA(), v);
1097 case opc_monitorenter: {
1098 out.append("/* monitor enter */");
1103 case opc_monitorexit: {
1104 out.append("/* monitor exit */");
1110 emit(out, "throw 'unknown bytecode @1';",
1111 Integer.toString(c));
1114 if (trap.useTry()) {
1115 out.append("} catch (e) {");
1116 for (TrapData e : trap.current()) {
1120 if (e.catch_cpx != 0) { //not finally
1121 final String classInternalName = jc.getClassName(e.catch_cpx);
1122 addReference(classInternalName);
1123 out.append("if (e.$instOf_"+classInternalName.replace('/', '_')+") {");
1124 out.append("gt="+e.handler_pc+"; continue;");
1130 out.append("throw e;");
1134 for (int j = prev; j <= i; j++) {
1136 final int cc = readByte(byteCodes, j);
1137 out.append(Integer.toString(cc));
1145 private int generateIf(byte[] byteCodes, int i,
1146 final Variable v2, final Variable v1,
1147 final String test) throws IOException {
1148 int indx = i + readIntArg(byteCodes, i);
1149 out.append("if (").append(v1)
1150 .append(' ').append(test).append(' ')
1151 .append(v2).append(") { gt = " + indx)
1152 .append("; continue; }");
1156 private int readIntArg(byte[] byteCodes, int offsetInstruction) {
1157 final int indxHi = byteCodes[offsetInstruction + 1] << 8;
1158 final int indxLo = byteCodes[offsetInstruction + 2];
1159 return (indxHi & 0xffffff00) | (indxLo & 0xff);
1161 private int readInt4(byte[] byteCodes, int offsetInstruction) {
1162 final int d = byteCodes[offsetInstruction + 0] << 24;
1163 final int c = byteCodes[offsetInstruction + 1] << 16;
1164 final int b = byteCodes[offsetInstruction + 2] << 8;
1165 final int a = byteCodes[offsetInstruction + 3];
1166 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
1168 private int readByte(byte[] byteCodes, int offsetInstruction) {
1169 return byteCodes[offsetInstruction] & 0xff;
1172 private static void countArgs(String descriptor, char[] returnType, StringBuilder sig, StringBuilder cnt) {
1174 Boolean count = null;
1175 boolean array = false;
1177 int firstPos = sig.length();
1178 while (i < descriptor.length()) {
1179 char ch = descriptor.charAt(i++);
1200 if (ch == 'J' || ch == 'D') {
1206 sig.insert(firstPos, ch);
1208 returnType[0] = '[';
1209 sig.insert(firstPos, "_3");
1218 returnType[0] = 'V';
1219 sig.insert(firstPos, 'V');
1222 int next = descriptor.indexOf(';', i);
1223 String realSig = mangleSig(descriptor, i - 1, next + 1);
1228 sig.append(realSig);
1231 sig.insert(firstPos, realSig);
1233 sig.insert(firstPos, "_3");
1235 returnType[0] = 'L';
1243 throw new IllegalStateException("Invalid char: " + ch);
1248 private static String mangleSig(String txt, int first, int last) {
1249 StringBuilder sb = new StringBuilder();
1250 for (int i = first; i < last; i++) {
1251 final char ch = txt.charAt(i);
1253 case '/': sb.append('_'); break;
1254 case '_': sb.append("_1"); break;
1255 case ';': sb.append("_2"); break;
1256 case '[': sb.append("_3"); break;
1257 default: sb.append(ch); break;
1260 return sb.toString();
1263 private static String findMethodName(MethodData m, StringBuilder cnt) {
1264 StringBuilder name = new StringBuilder();
1265 if ("<init>".equals(m.getName())) { // NOI18N
1266 name.append("cons"); // NOI18N
1267 } else if ("<clinit>".equals(m.getName())) { // NOI18N
1268 name.append("class"); // NOI18N
1270 name.append(m.getName());
1273 countArgs(m.getInternalSig(), new char[1], name, cnt);
1274 return name.toString();
1277 static String findMethodName(String[] mi, StringBuilder cnt, char[] returnType) {
1278 StringBuilder name = new StringBuilder();
1279 String descr = mi[2];//mi.getDescriptor();
1281 if ("<init>".equals(nm)) { // NOI18N
1282 name.append("cons"); // NOI18N
1286 countArgs(descr, returnType, name, cnt);
1287 return name.toString();
1290 private int invokeStaticMethod(byte[] byteCodes, int i, final StackMapper mapper, boolean isStatic)
1291 throws IOException {
1292 int methodIndex = readIntArg(byteCodes, i);
1293 String[] mi = jc.getFieldInfoName(methodIndex);
1294 char[] returnType = { 'V' };
1295 StringBuilder cnt = new StringBuilder();
1296 String mn = findMethodName(mi, cnt, returnType);
1298 final int numArguments = isStatic ? cnt.length() : cnt.length() + 1;
1299 final Variable[] vars = new Variable[numArguments];
1301 for (int j = numArguments - 1; j >= 0; --j) {
1302 vars[j] = mapper.pop();
1305 if (returnType[0] != 'V') {
1306 out.append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1310 final String in = mi[0];
1311 out.append(accessClass(in.replace('/', '_')));
1312 out.append("(false).");
1315 if (numArguments > 0) {
1316 out.append(vars[0]);
1317 for (int j = 1; j < numArguments; ++j) {
1319 out.append(vars[j]);
1327 private int invokeVirtualMethod(byte[] byteCodes, int i, final StackMapper mapper)
1328 throws IOException {
1329 int methodIndex = readIntArg(byteCodes, i);
1330 String[] mi = jc.getFieldInfoName(methodIndex);
1331 char[] returnType = { 'V' };
1332 StringBuilder cnt = new StringBuilder();
1333 String mn = findMethodName(mi, cnt, returnType);
1335 final int numArguments = cnt.length() + 1;
1336 final Variable[] vars = new Variable[numArguments];
1338 for (int j = numArguments - 1; j >= 0; --j) {
1339 vars[j] = mapper.pop();
1342 if (returnType[0] != 'V') {
1343 out.append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1347 out.append(vars[0]).append('.');
1350 out.append(vars[0]);
1351 for (int j = 1; j < numArguments; ++j) {
1353 out.append(vars[j]);
1360 private void addReference(String cn) throws IOException {
1361 if (requireReference(cn)) {
1362 out.append(" /* needs ").append(cn).append(" */");
1366 private void outType(String d, StringBuilder out) {
1368 while (d.charAt(0) == '[') {
1372 if (d.charAt(0) == 'L') {
1373 assert d.charAt(d.length() - 1) == ';';
1374 out.append(d.replace('/', '_').substring(0, d.length() - 1));
1380 private String encodeConstant(int entryIndex) throws IOException {
1381 String[] classRef = { null };
1382 String s = jc.stringValue(entryIndex, classRef);
1383 if (classRef[0] != null) {
1384 addReference(classRef[0]);
1385 s = accessClass(s.replace('/', '_')) + "(false).constructor.$class";
1390 private String javaScriptBody(String prefix, MethodData m, boolean isStatic) throws IOException {
1391 byte[] arr = m.findAnnotationData(true);
1395 final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
1396 class P extends AnnotationParser {
1402 String[] args = new String[30];
1406 protected void visitAttr(String type, String attr, String at, String value) {
1407 if (type.equals(jvmType)) {
1408 if ("body".equals(attr)) {
1410 } else if ("args".equals(attr)) {
1411 args[cnt++] = value;
1413 throw new IllegalArgumentException(attr);
1420 if (p.body == null) {
1423 StringBuilder cnt = new StringBuilder();
1424 final String mn = findMethodName(m, cnt);
1425 out.append(prefix).append(mn);
1426 out.append(" = function(");
1430 space = outputArg(out, p.args, 0);
1436 for (int i = 0; i < cnt.length(); i++) {
1438 space = outputArg(out, p.args, index);
1441 out.append(") {").append("\n");
1443 out.append("\n}\n");
1446 private static String className(ClassData jc) {
1447 //return jc.getName().getInternalName().replace('/', '_');
1448 return jc.getClassName().replace('/', '_');
1451 private static String[] findAnnotation(
1452 byte[] arr, ClassData cd, final String className,
1453 final String... attrNames
1454 ) throws IOException {
1458 final String[] values = new String[attrNames.length];
1459 final boolean[] found = { false };
1460 final String jvmType = "L" + className.replace('.', '/') + ";";
1461 AnnotationParser ap = new AnnotationParser(false) {
1463 protected void visitAttr(String type, String attr, String at, String value) {
1464 if (type.equals(jvmType)) {
1466 for (int i = 0; i < attrNames.length; i++) {
1467 if (attrNames[i].equals(attr)) {
1476 return found[0] ? values : null;
1479 private CharSequence initField(FieldData v) {
1480 final String is = v.getInternalSig();
1481 if (is.length() == 1) {
1482 switch (is.charAt(0)) {
1488 case 'I': return " = 0;";
1490 case 'D': return " = 0.0;";
1492 throw new IllegalStateException(is);
1498 private static void generateAnno(ClassData cd, final Appendable out, byte[] data) throws IOException {
1499 AnnotationParser ap = new AnnotationParser(true) {
1504 protected void visitAnnotationStart(String type) throws IOException {
1508 out.append('"').append(type).append("\" : {\n");
1513 protected void visitAnnotationEnd(String type) throws IOException {
1514 out.append("\n}\n");
1518 protected void visitAttr(String type, String attr, String attrType, String value)
1519 throws IOException {
1526 out.append(attr).append("__").append(attrType).append(" : ").append(value);
1532 private static String outputArg(Appendable out, String[] args, int indx) throws IOException {
1533 final String name = args[indx];
1537 if (name.contains(",")) {
1538 throw new IOException("Wrong parameter with ',': " + name);
1544 private static void emit(final Appendable out,
1545 final String format,
1546 final CharSequence... params) throws IOException {
1547 final int length = format.length();
1550 int paramOffset = format.indexOf('@');
1551 while ((paramOffset != -1) && (paramOffset < (length - 1))) {
1552 final char paramChar = format.charAt(paramOffset + 1);
1553 if ((paramChar >= '1') && (paramChar <= '9')) {
1554 final int paramIndex = paramChar - '0' - 1;
1556 out.append(format, processed, paramOffset);
1557 out.append(params[paramIndex]);
1560 processed = paramOffset + 1;
1563 paramOffset = format.indexOf('@', paramOffset + 1);
1566 out.append(format, processed, length);