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.bck2brwsr.core.JavaScriptBody;
23 import org.apidesign.javap.AnnotationParser;
24 import org.apidesign.javap.ClassData;
25 import org.apidesign.javap.FieldData;
26 import org.apidesign.javap.MethodData;
27 import org.apidesign.javap.StackMapIterator;
28 import static org.apidesign.javap.RuntimeConstants.*;
30 /** Translator of the code inside class files to JavaScript.
32 * @author Jaroslav Tulach <jtulach@netbeans.org>
34 abstract class ByteCodeToJavaScript {
38 protected ByteCodeToJavaScript(Appendable out) {
42 /* Collects additional required resources.
44 * @param internalClassName classes that were referenced and should be loaded in order the
45 * generated JavaScript code works properly. The names are in internal
46 * JVM form so String is <code>java/lang/String</code>.
48 protected abstract boolean requireReference(String internalClassName);
51 * @param resourcePath name of resources to read
53 protected abstract void requireScript(String resourcePath);
55 /** Allows subclasses to redefine what field a function representing a
56 * class gets assigned. By default it returns the suggested name followed
57 * by <code>" = "</code>;
59 * @param className suggested name of the class
61 /* protected */ String assignClass(String className) {
62 return className + " = ";
64 /* protected */ String accessClass(String classOperation) {
65 return classOperation;
69 * Converts a given class file to a JavaScript version.
71 * @param classFile input stream with code of the .class file
72 * @return the initialization code for this class, if any. Otherwise <code>null</code>
74 * @throws IOException if something goes wrong during read or write or translating
77 public String compile(InputStream classFile) throws IOException {
78 this.jc = new ClassData(classFile);
79 byte[] arrData = jc.findAnnotationData(true);
80 String[] arr = findAnnotation(arrData, jc,
81 "org.apidesign.bck2brwsr.core.ExtraJavaScript",
82 "resource", "processByteCode"
85 requireScript(arr[0]);
86 if ("0".equals(arr[1])) {
90 String[] proto = findAnnotation(arrData, jc,
91 "org.apidesign.bck2brwsr.core.JavaScriptPrototype",
92 "container", "prototype"
94 StringArray toInitilize = new StringArray();
95 final String className = className(jc);
96 out.append("\n\n").append(assignClass(className));
97 out.append("function CLS() {");
98 out.append("\n if (!CLS.prototype.$instOf_").append(className).append(") {");
99 for (FieldData v : jc.getFields()) {
101 out.append("\n CLS.").append(v.getName()).append(initField(v));
105 String sc = jc.getSuperClassName(); // with _
106 out.append("\n var pp = ").
107 append(accessClass(sc.replace('/', '_'))).append("(true);");
108 out.append("\n var p = CLS.prototype = pp;");
109 out.append("\n var c = p;");
110 out.append("\n var sprcls = pp.constructor.$class;");
112 out.append("\n var p = CLS.prototype = ").append(proto[1]).append(";");
113 if (proto[0] == null) {
116 out.append("\n var c = ").append(proto[0]).append(";");
117 out.append("\n var sprcls = null;");
119 for (MethodData m : jc.getMethods()) {
120 byte[] onlyArr = m.findAnnotationData(true);
121 String[] only = findAnnotation(onlyArr, jc,
122 "org.apidesign.bck2brwsr.core.JavaScriptOnly",
126 if (only[0] != null && only[1] != null) {
127 out.append("\n p.").append(only[0]).append(" = ")
128 .append(only[1]).append(";");
134 mn = generateStaticMethod("\n c.", m, toInitilize);
136 mn = generateInstanceMethod("\n c.", m);
138 byte[] runAnno = m.findAnnotationData(false);
139 if (runAnno != null) {
140 out.append("\n c.").append(mn).append(".anno = {");
141 generateAnno(jc, out, runAnno);
145 out.append("\n c.constructor = CLS;");
146 out.append("\n c.$instOf_").append(className).append(" = true;");
147 for (String superInterface : jc.getSuperInterfaces()) {
148 out.append("\n c.$instOf_").append(superInterface.replace('/', '_')).append(" = true;");
150 out.append("\n CLS.$class = ");
151 out.append(accessClass("java_lang_Class(true);"));
152 out.append("\n CLS.$class.jvmName = '").append(jc.getClassName()).append("';");
153 out.append("\n CLS.$class.superclass = sprcls;");
154 out.append("\n CLS.$class.cnstr = CLS;");
155 byte[] classAnno = jc.findAnnotationData(false);
156 if (classAnno != null) {
157 out.append("\n CLS.$class.anno = {");
158 generateAnno(jc, out, classAnno);
162 out.append("\n if (arguments.length === 0) {");
163 out.append("\n if (!(this instanceof CLS)) {");
164 out.append("\n return new CLS();");
166 for (FieldData v : jc.getFields()) {
167 byte[] onlyArr = v.findAnnotationData(true);
168 String[] only = findAnnotation(onlyArr, jc,
169 "org.apidesign.bck2brwsr.core.JavaScriptOnly",
173 if (only[0] != null && only[1] != null) {
174 out.append("\n p.").append(only[0]).append(" = ")
175 .append(only[1]).append(";");
180 out.append("\n this.fld_").
181 append(v.getName()).append(initField(v));
184 out.append("\n return this;");
186 out.append("\n return arguments[0] ? new CLS() : CLS.prototype;");
188 StringBuilder sb = new StringBuilder();
189 for (String init : toInitilize.toArray()) {
190 sb.append("\n").append(init).append("();");
192 return sb.toString();
194 private String generateStaticMethod(String prefix, MethodData m, StringArray toInitilize) throws IOException {
195 String jsb = javaScriptBody(prefix, m, true);
199 final String mn = findMethodName(m, new StringBuilder());
200 if (mn.equals("class__V")) {
201 toInitilize.add(accessClass(className(jc)) + "(false)." + mn);
203 generateMethod(prefix, mn, m);
207 private String generateInstanceMethod(String prefix, MethodData m) throws IOException {
208 String jsb = javaScriptBody(prefix, m, false);
212 final String mn = findMethodName(m, new StringBuilder());
213 generateMethod(prefix, mn, m);
217 private void generateMethod(String prefix, String name, MethodData m)
219 final StackMapIterator stackMapIterator = m.createStackMapIterator();
220 final LocalsMapper lmapper =
221 new LocalsMapper(stackMapIterator.getArguments());
223 out.append(prefix).append(name).append(" = function(");
224 lmapper.outputArguments(out);
225 out.append(") {").append("\n");
227 final byte[] byteCodes = m.getCode();
228 if (byteCodes == null) {
229 out.append(" throw 'no code found for ")
230 .append(m.getInternalSig()).append("';\n");
235 final StackMapper smapper = new StackMapper();
237 final int maxLocals = m.getMaxLocals();
239 // TODO: generate only used local variables
240 for (int j = 0; j <= VarType.LAST; ++j) {
241 out.append("\n var ").append(Variable.getLocalVariable(j, 0));
242 for (int i = 1; i < maxLocals; ++i) {
244 out.append(Variable.getLocalVariable(j, i));
250 // maxStack includes two stack positions for every pushed long / double
251 // so this might generate more stack variables than we need
252 final int maxStack = m.getMaxStack();
254 // TODO: generate only used stack variables
255 for (int j = 0; j <= VarType.LAST; ++j) {
256 out.append("\n var ").append(Variable.getStackVariable(j, 0));
257 for (int i = 1; i < maxStack; ++i) {
259 out.append(Variable.getStackVariable(j, i));
265 int lastStackFrame = -1;
267 out.append("\n var gt = 0;\n for(;;) switch(gt) {\n");
268 for (int i = 0; i < byteCodes.length; i++) {
270 stackMapIterator.advanceTo(i);
271 if (lastStackFrame != stackMapIterator.getFrameIndex()) {
272 lastStackFrame = stackMapIterator.getFrameIndex();
273 lmapper.syncWithFrameLocals(stackMapIterator.getFrameLocals());
274 smapper.syncWithFrameStack(stackMapIterator.getFrameStack());
275 out.append(" case " + i).append(": ");
277 out.append(" /* " + i).append(" */ ");
279 final int c = readByte(byteCodes, i);
282 emit(out, "@1 = @2;", smapper.pushA(), lmapper.getA(0));
285 emit(out, "@1 = @2;", smapper.pushI(), lmapper.getI(0));
288 emit(out, "@1 = @2;", smapper.pushL(), lmapper.getL(0));
291 emit(out, "@1 = @2;", smapper.pushF(), lmapper.getF(0));
294 emit(out, "@1 = @2;", smapper.pushD(), lmapper.getD(0));
297 emit(out, "@1 = @2;", smapper.pushA(), lmapper.getA(1));
300 emit(out, "@1 = @2;", smapper.pushI(), lmapper.getI(1));
303 emit(out, "@1 = @2;", smapper.pushL(), lmapper.getL(1));
306 emit(out, "@1 = @2;", smapper.pushF(), lmapper.getF(1));
309 emit(out, "@1 = @2;", smapper.pushD(), lmapper.getD(1));
312 emit(out, "@1 = @2;", smapper.pushA(), lmapper.getA(2));
315 emit(out, "@1 = @2;", smapper.pushI(), lmapper.getI(2));
318 emit(out, "@1 = @2;", smapper.pushL(), lmapper.getL(2));
321 emit(out, "@1 = @2;", smapper.pushF(), lmapper.getF(2));
324 emit(out, "@1 = @2;", smapper.pushD(), lmapper.getD(2));
327 emit(out, "@1 = @2;", smapper.pushA(), lmapper.getA(3));
330 emit(out, "@1 = @2;", smapper.pushI(), lmapper.getI(3));
333 emit(out, "@1 = @2;", smapper.pushL(), lmapper.getL(3));
336 emit(out, "@1 = @2;", smapper.pushF(), lmapper.getF(3));
339 emit(out, "@1 = @2;", smapper.pushD(), lmapper.getD(3));
342 final int indx = readByte(byteCodes, ++i);
343 emit(out, "@1 = @2;", smapper.pushI(), lmapper.getI(indx));
347 final int indx = readByte(byteCodes, ++i);
348 emit(out, "@1 = @2;", smapper.pushL(), lmapper.getL(indx));
352 final int indx = readByte(byteCodes, ++i);
353 emit(out, "@1 = @2;", smapper.pushF(), lmapper.getF(indx));
357 final int indx = readByte(byteCodes, ++i);
358 emit(out, "@1 = @2;", smapper.pushD(), lmapper.getD(indx));
362 final int indx = readByte(byteCodes, ++i);
363 emit(out, "@1 = @2;", smapper.pushA(), lmapper.getA(indx));
367 final int indx = readByte(byteCodes, ++i);
368 emit(out, "@1 = @2;", lmapper.setI(indx), smapper.popI());
372 final int indx = readByte(byteCodes, ++i);
373 emit(out, "@1 = @2;", lmapper.setL(indx), smapper.popL());
377 final int indx = readByte(byteCodes, ++i);
378 emit(out, "@1 = @2;", lmapper.setF(indx), smapper.popF());
382 final int indx = readByte(byteCodes, ++i);
383 emit(out, "@1 = @2;", lmapper.setD(indx), smapper.popD());
387 final int indx = readByte(byteCodes, ++i);
388 emit(out, "@1 = @2;", lmapper.setA(indx), smapper.popA());
392 emit(out, "@1 = @2;", lmapper.setA(0), smapper.popA());
395 emit(out, "@1 = @2;", lmapper.setI(0), smapper.popI());
398 emit(out, "@1 = @2;", lmapper.setL(0), smapper.popL());
401 emit(out, "@1 = @2;", lmapper.setF(0), smapper.popF());
404 emit(out, "@1 = @2;", lmapper.setD(0), smapper.popD());
407 emit(out, "@1 = @2;", lmapper.setA(1), smapper.popA());
410 emit(out, "@1 = @2;", lmapper.setI(1), smapper.popI());
413 emit(out, "@1 = @2;", lmapper.setL(1), smapper.popL());
416 emit(out, "@1 = @2;", lmapper.setF(1), smapper.popF());
419 emit(out, "@1 = @2;", lmapper.setD(1), smapper.popD());
422 emit(out, "@1 = @2;", lmapper.setA(2), smapper.popA());
425 emit(out, "@1 = @2;", lmapper.setI(2), smapper.popI());
428 emit(out, "@1 = @2;", lmapper.setL(2), smapper.popL());
431 emit(out, "@1 = @2;", lmapper.setF(2), smapper.popF());
434 emit(out, "@1 = @2;", lmapper.setD(2), smapper.popD());
437 emit(out, "@1 = @2;", lmapper.setA(3), smapper.popA());
440 emit(out, "@1 = @2;", lmapper.setI(3), smapper.popI());
443 emit(out, "@1 = @2;", lmapper.setL(3), smapper.popL());
446 emit(out, "@1 = @2;", lmapper.setF(3), smapper.popF());
449 emit(out, "@1 = @2;", lmapper.setD(3), smapper.popD());
452 emit(out, "@1 += @2;", smapper.getI(1), smapper.popI());
455 emit(out, "@1 += @2;", smapper.getL(1), smapper.popL());
458 emit(out, "@1 += @2;", smapper.getF(1), smapper.popF());
461 emit(out, "@1 += @2;", smapper.getD(1), 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 = Math.floor(@1 / @2);",
489 smapper.getI(1), smapper.popI());
492 emit(out, "@1 = Math.floor(@1 / @2);",
493 smapper.getL(1), smapper.popL());
496 emit(out, "@1 /= @2;", smapper.getF(1), smapper.popF());
499 emit(out, "@1 /= @2;", smapper.getD(1), smapper.popD());
502 emit(out, "@1 %= @2;", smapper.getI(1), smapper.popI());
505 emit(out, "@1 %= @2;", 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.getI(1), smapper.popI());
523 emit(out, "@1 |= @2;", smapper.getL(1), smapper.popL());
526 emit(out, "@1 ^= @2;", smapper.getI(1), smapper.popI());
529 emit(out, "@1 ^= @2;", smapper.getL(1), smapper.popL());
532 emit(out, "@1 = -@1;", smapper.getI(0));
535 emit(out, "@1 = -@1;", smapper.getL(0));
538 emit(out, "@1 = -@1;", smapper.getF(0));
541 emit(out, "@1 = -@1;", smapper.getD(0));
544 emit(out, "@1 <<= @2;", smapper.getI(1), smapper.popI());
547 emit(out, "@1 <<= @2;", smapper.getL(1), smapper.popI());
550 emit(out, "@1 >>= @2;", smapper.getI(1), smapper.popI());
553 emit(out, "@1 >>= @2;", smapper.getL(1), smapper.popI());
556 emit(out, "@1 >>>= @2;", smapper.getI(1), smapper.popI());
559 emit(out, "@1 >>>= @2;", smapper.getL(1), smapper.popI());
562 final int varIndx = readByte(byteCodes, ++i);
563 final int incrBy = byteCodes[++i];
565 emit(out, "@1++;", lmapper.getI(varIndx));
567 emit(out, "@1 += @2;",
568 lmapper.getI(varIndx),
569 Integer.toString(incrBy));
574 emit(out, "return;");
577 emit(out, "return @1;", smapper.popI());
580 emit(out, "return @1;", smapper.popL());
583 emit(out, "return @1;", smapper.popF());
586 emit(out, "return @1;", smapper.popD());
589 emit(out, "return @1;", smapper.popA());
592 emit(out, "@2 = @1;", smapper.popI(), smapper.pushL());
595 emit(out, "@2 = @1;", smapper.popI(), smapper.pushF());
598 emit(out, "@2 = @1;", smapper.popI(), smapper.pushD());
601 emit(out, "@2 = @1;", smapper.popL(), smapper.pushI());
605 emit(out, "@2 = @1;", smapper.popL(), smapper.pushF());
608 emit(out, "@2 = @1;", smapper.popL(), smapper.pushD());
611 emit(out, "@2 = @1;", smapper.popF(), smapper.pushD());
614 emit(out, "@2 = @1;", smapper.popD(), smapper.pushF());
617 emit(out, "@2 = Math.floor(@1);",
618 smapper.popF(), smapper.pushI());
621 emit(out, "@2 = Math.floor(@1);",
622 smapper.popF(), smapper.pushL());
625 emit(out, "@2 = Math.floor(@1);",
626 smapper.popD(), smapper.pushI());
629 emit(out, "@2 = Math.floor(@1);",
630 smapper.popD(), smapper.pushL());
635 out.append("/* number conversion */");
637 case opc_aconst_null:
638 emit(out, "@1 = null;", smapper.pushA());
641 emit(out, "@1 = -1;", smapper.pushI());
644 emit(out, "@1 = 0;", smapper.pushI());
647 emit(out, "@1 = 0;", smapper.pushD());
650 emit(out, "@1 = 0;", smapper.pushL());
653 emit(out, "@1 = 0;", smapper.pushF());
656 emit(out, "@1 = 1;", smapper.pushI());
659 emit(out, "@1 = 1;", smapper.pushL());
662 emit(out, "@1 = 1;", smapper.pushF());
665 emit(out, "@1 = 1;", smapper.pushD());
668 emit(out, "@1 = 2;", smapper.pushI());
671 emit(out, "@1 = 2;", smapper.pushF());
674 emit(out, "@1 = 3;", smapper.pushI());
677 emit(out, "@1 = 4;", smapper.pushI());
680 emit(out, "@1 = 5;", smapper.pushI());
683 int indx = readByte(byteCodes, ++i);
684 String v = encodeConstant(indx);
685 int type = VarType.fromConstantType(jc.getTag(indx));
686 emit(out, "@1 = @2;", smapper.pushT(type), v);
691 int indx = readIntArg(byteCodes, i);
693 String v = encodeConstant(indx);
694 int type = VarType.fromConstantType(jc.getTag(indx));
695 emit(out, "@1 = @2;", smapper.pushT(type), v);
699 emit(out, "@3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
700 smapper.popL(), smapper.popL(), smapper.pushI());
704 emit(out, "@3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
705 smapper.popF(), smapper.popF(), smapper.pushI());
709 emit(out, "@3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
710 smapper.popD(), smapper.popD(), smapper.pushI());
713 i = generateIf(byteCodes, i, smapper.popA(), smapper.popA(),
717 i = generateIf(byteCodes, i, smapper.popA(), smapper.popA(),
721 i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
725 int indx = i + readIntArg(byteCodes, i);
726 emit(out, "if (@1 == 0) { gt = @2; continue; }",
727 smapper.popI(), Integer.toString(indx));
732 int indx = i + readIntArg(byteCodes, i);
733 emit(out, "if (@1 != 0) { gt = @2; continue; }",
734 smapper.popI(), Integer.toString(indx));
739 int indx = i + readIntArg(byteCodes, i);
740 emit(out, "if (@1 < 0) { gt = @2; continue; }",
741 smapper.popI(), Integer.toString(indx));
746 int indx = i + readIntArg(byteCodes, i);
747 emit(out, "if (@1 <= 0) { gt = @2; continue; }",
748 smapper.popI(), Integer.toString(indx));
753 int indx = i + readIntArg(byteCodes, i);
754 emit(out, "if (@1 > 0) { gt = @2; continue; }",
755 smapper.popI(), Integer.toString(indx));
760 int indx = i + readIntArg(byteCodes, i);
761 emit(out, "if (@1 >= 0) { gt = @2; continue; }",
762 smapper.popI(), Integer.toString(indx));
766 case opc_ifnonnull: {
767 int indx = i + readIntArg(byteCodes, i);
768 emit(out, "if (@1 !== null) { gt = @2; continue; }",
769 smapper.popA(), Integer.toString(indx));
774 int indx = i + readIntArg(byteCodes, i);
775 emit(out, "if (@1 === null) { gt = @2; continue; }",
776 smapper.popA(), Integer.toString(indx));
781 i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
785 i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
789 i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
793 i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
797 i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
801 int indx = i + readIntArg(byteCodes, i);
802 emit(out, "gt = @1; continue;", Integer.toString(indx));
806 case opc_lookupswitch: {
807 int table = i / 4 * 4 + 4;
808 int dflt = i + readInt4(byteCodes, table);
810 int n = readInt4(byteCodes, table);
812 out.append("switch (").append(smapper.popI()).append(") {\n");
814 int cnstnt = readInt4(byteCodes, table);
816 int offset = i + readInt4(byteCodes, table);
818 out.append(" case " + cnstnt).append(": gt = " + offset).append("; continue;\n");
820 out.append(" default: gt = " + dflt).append("; continue;\n}");
824 case opc_tableswitch: {
825 int table = i / 4 * 4 + 4;
826 int dflt = i + readInt4(byteCodes, table);
828 int low = readInt4(byteCodes, table);
830 int high = readInt4(byteCodes, table);
832 out.append("switch (").append(smapper.popI()).append(") {\n");
833 while (low <= high) {
834 int offset = i + readInt4(byteCodes, table);
836 out.append(" case " + low).append(": gt = " + offset).append("; continue;\n");
839 out.append(" default: gt = " + dflt).append("; continue;\n}");
843 case opc_invokeinterface: {
844 i = invokeVirtualMethod(byteCodes, i, smapper) + 2;
847 case opc_invokevirtual:
848 i = invokeVirtualMethod(byteCodes, i, smapper);
850 case opc_invokespecial:
851 i = invokeStaticMethod(byteCodes, i, smapper, false);
853 case opc_invokestatic:
854 i = invokeStaticMethod(byteCodes, i, smapper, true);
857 int indx = readIntArg(byteCodes, i);
858 String ci = jc.getClassName(indx);
859 emit(out, "@1 = new @2;",
860 smapper.pushA(), accessClass(ci.replace('/', '_')));
866 ++i; // skip type of array
867 emit(out, "@2 = new Array(@1).fillNulls();",
868 smapper.popI(), smapper.pushA());
871 i += 2; // skip type of array
872 emit(out, "@2 = new Array(@1).fillNulls();",
873 smapper.popI(), smapper.pushA());
875 case opc_multianewarray: {
877 int dim = readByte(byteCodes, ++i);
878 out.append("{ var a0 = new Array(").append(smapper.popI())
879 .append(").fillNulls();");
880 for (int d = 1; d < dim; d++) {
881 out.append("\n var l" + d).append(" = ")
882 .append(smapper.popI()).append(';');
883 out.append("\n for (var i" + d).append (" = 0; i" + d).
884 append(" < a" + (d - 1)).
885 append(".length; i" + d).append("++) {");
886 out.append("\n var a" + d).
887 append (" = new Array(l" + d).append(").fillNulls();");
888 out.append("\n a" + (d - 1)).append("[i" + d).append("] = a" + d).
891 for (int d = 1; d < dim; d++) {
894 out.append("\n").append(smapper.pushA()).append(" = a0; }");
897 case opc_arraylength:
898 emit(out, "@2 = @1.length;", smapper.popA(), smapper.pushI());
901 emit(out, "@3[@2] = @1;",
902 smapper.popL(), smapper.popI(), smapper.popA());
905 emit(out, "@3[@2] = @1;",
906 smapper.popF(), smapper.popI(), smapper.popA());
909 emit(out, "@3[@2] = @1;",
910 smapper.popD(), smapper.popI(), smapper.popA());
913 emit(out, "@3[@2] = @1;",
914 smapper.popA(), smapper.popI(), smapper.popA());
920 emit(out, "@3[@2] = @1;",
921 smapper.popI(), smapper.popI(), smapper.popA());
924 emit(out, "@3 = @2[@1];",
925 smapper.popI(), smapper.popA(), smapper.pushL());
928 emit(out, "@3 = @2[@1];",
929 smapper.popI(), smapper.popA(), smapper.pushF());
932 emit(out, "@3 = @2[@1];",
933 smapper.popI(), smapper.popA(), smapper.pushD());
936 emit(out, "@3 = @2[@1];",
937 smapper.popI(), smapper.popA(), smapper.pushA());
943 emit(out, "@3 = @2[@1];",
944 smapper.popI(), smapper.popA(), smapper.pushI());
949 out.append("/* pop */");
952 final Variable v = smapper.get(0);
953 emit(out, "@1 = @2;", smapper.pushT(v.getType()), v);
957 if (smapper.get(0).isCategory2()) {
958 final Variable v = smapper.get(0);
959 emit(out, "@1 = @2;", smapper.pushT(v.getType()), v);
961 final Variable v1 = smapper.get(0);
962 final Variable v2 = smapper.get(1);
963 emit(out, "{ @1 = @2; @3 = @4; }",
964 smapper.pushT(v2.getType()), v2,
965 smapper.pushT(v1.getType()), v1);
970 final Variable vi1 = smapper.pop();
971 final Variable vi2 = smapper.pop();
972 final Variable vo3 = smapper.pushT(vi1.getType());
973 final Variable vo2 = smapper.pushT(vi2.getType());
974 final Variable vo1 = smapper.pushT(vi1.getType());
976 emit(out, "{ @1 = @2; @3 = @4; @5 = @6; }",
977 vo1, vi1, vo2, vi2, vo3, vo1);
981 if (smapper.get(1).isCategory2()) {
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);
991 final Variable vi1 = smapper.pop();
992 final Variable vi2 = smapper.pop();
993 final Variable vi3 = smapper.pop();
994 final Variable vo4 = smapper.pushT(vi1.getType());
995 final Variable vo3 = smapper.pushT(vi3.getType());
996 final Variable vo2 = smapper.pushT(vi2.getType());
997 final Variable vo1 = smapper.pushT(vi1.getType());
999 emit(out, "{ @1 = @2; @3 = @4; @5 = @6; @7 = @8; }",
1000 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1005 emit(out, "@1 = @2;",
1006 smapper.pushI(), Integer.toString(byteCodes[++i]));
1009 emit(out, "@1 = @2;",
1011 Integer.toString(readIntArg(byteCodes, i)));
1014 case opc_getfield: {
1015 int indx = readIntArg(byteCodes, i);
1016 String[] fi = jc.getFieldInfoName(indx);
1017 final int type = VarType.fromFieldType(fi[2].charAt(0));
1018 emit(out, "@2 = @1.fld_@3;",
1019 smapper.popA(), smapper.pushT(type), fi[1]);
1023 case opc_getstatic: {
1024 int indx = readIntArg(byteCodes, i);
1025 String[] fi = jc.getFieldInfoName(indx);
1026 final int type = VarType.fromFieldType(fi[2].charAt(0));
1027 emit(out, "@1 = @2.@3;",
1028 smapper.pushT(type),
1029 accessClass(fi[0].replace('/', '_')), fi[1]);
1031 addReference(fi[0]);
1034 case opc_putfield: {
1035 int indx = readIntArg(byteCodes, i);
1036 String[] fi = jc.getFieldInfoName(indx);
1037 final int type = VarType.fromFieldType(fi[2].charAt(0));
1038 emit(out, "@2.fld_@3 = @1;",
1039 smapper.popT(type), smapper.popA(), fi[1]);
1043 case opc_putstatic: {
1044 int indx = readIntArg(byteCodes, i);
1045 String[] fi = jc.getFieldInfoName(indx);
1046 final int type = VarType.fromFieldType(fi[2].charAt(0));
1047 emit(out, "@1.@2 = @3;",
1048 accessClass(fi[0].replace('/', '_')), fi[1],
1049 smapper.popT(type));
1051 addReference(fi[0]);
1054 case opc_checkcast: {
1055 int indx = readIntArg(byteCodes, i);
1056 final String type = jc.getClassName(indx);
1057 if (!type.startsWith("[")) {
1058 // no way to check arrays right now
1059 // XXX proper exception
1061 "if (@1 !== null && !@1.$instOf_@2) throw {};",
1062 smapper.getA(0), type.replace('/', '_'));
1067 case opc_instanceof: {
1068 int indx = readIntArg(byteCodes, i);
1069 final String type = jc.getClassName(indx);
1070 emit(out, "@2 = @1.$instOf_@3 ? 1 : 0;",
1071 smapper.popA(), smapper.pushI(),
1072 type.replace('/', '_'));
1077 final Variable v = smapper.popA();
1080 emit(out, "{ @1 = @2; throw @2; }",
1081 smapper.pushA(), v);
1085 case opc_monitorenter: {
1086 out.append("/* monitor enter */");
1091 case opc_monitorexit: {
1092 out.append("/* monitor exit */");
1098 emit(out, "throw 'unknown bytecode @1';",
1099 Integer.toString(c));
1103 for (int j = prev; j <= i; j++) {
1105 final int cc = readByte(byteCodes, j);
1106 out.append(Integer.toString(cc));
1114 private int generateIf(byte[] byteCodes, int i,
1115 final Variable v2, final Variable v1,
1116 final String test) throws IOException {
1117 int indx = i + readIntArg(byteCodes, i);
1118 out.append("if (").append(v1)
1119 .append(' ').append(test).append(' ')
1120 .append(v2).append(") { gt = " + indx)
1121 .append("; continue; }");
1125 private int readIntArg(byte[] byteCodes, int offsetInstruction) {
1126 final int indxHi = byteCodes[offsetInstruction + 1] << 8;
1127 final int indxLo = byteCodes[offsetInstruction + 2];
1128 return (indxHi & 0xffffff00) | (indxLo & 0xff);
1130 private int readInt4(byte[] byteCodes, int offsetInstruction) {
1131 final int d = byteCodes[offsetInstruction + 0] << 24;
1132 final int c = byteCodes[offsetInstruction + 1] << 16;
1133 final int b = byteCodes[offsetInstruction + 2] << 8;
1134 final int a = byteCodes[offsetInstruction + 3];
1135 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
1137 private int readByte(byte[] byteCodes, int offsetInstruction) {
1138 return byteCodes[offsetInstruction] & 0xff;
1141 private static void countArgs(String descriptor, char[] returnType, StringBuilder sig, StringBuilder cnt) {
1143 Boolean count = null;
1144 boolean array = false;
1146 int firstPos = sig.length();
1147 while (i < descriptor.length()) {
1148 char ch = descriptor.charAt(i++);
1169 if (ch == 'J' || ch == 'D') {
1175 sig.insert(firstPos, ch);
1177 returnType[0] = '[';
1178 sig.insert(firstPos, "_3");
1187 returnType[0] = 'V';
1188 sig.insert(firstPos, 'V');
1191 int next = descriptor.indexOf(';', i);
1192 String realSig = mangleSig(descriptor, i - 1, next + 1);
1197 sig.append(realSig);
1200 sig.insert(firstPos, realSig);
1202 sig.insert(firstPos, "_3");
1204 returnType[0] = 'L';
1212 throw new IllegalStateException("Invalid char: " + ch);
1217 private static String mangleSig(String txt, int first, int last) {
1218 StringBuilder sb = new StringBuilder();
1219 for (int i = first; i < last; i++) {
1220 final char ch = txt.charAt(i);
1222 case '/': sb.append('_'); break;
1223 case '_': sb.append("_1"); break;
1224 case ';': sb.append("_2"); break;
1225 case '[': sb.append("_3"); break;
1226 default: sb.append(ch); break;
1229 return sb.toString();
1232 private static String findMethodName(MethodData m, StringBuilder cnt) {
1233 StringBuilder name = new StringBuilder();
1234 if ("<init>".equals(m.getName())) { // NOI18N
1235 name.append("cons"); // NOI18N
1236 } else if ("<clinit>".equals(m.getName())) { // NOI18N
1237 name.append("class"); // NOI18N
1239 name.append(m.getName());
1242 countArgs(m.getInternalSig(), new char[1], name, cnt);
1243 return name.toString();
1246 static String findMethodName(String[] mi, StringBuilder cnt, char[] returnType) {
1247 StringBuilder name = new StringBuilder();
1248 String descr = mi[2];//mi.getDescriptor();
1250 if ("<init>".equals(nm)) { // NOI18N
1251 name.append("cons"); // NOI18N
1255 countArgs(descr, returnType, name, cnt);
1256 return name.toString();
1259 private int invokeStaticMethod(byte[] byteCodes, int i, final StackMapper mapper, boolean isStatic)
1260 throws IOException {
1261 int methodIndex = readIntArg(byteCodes, i);
1262 String[] mi = jc.getFieldInfoName(methodIndex);
1263 char[] returnType = { 'V' };
1264 StringBuilder cnt = new StringBuilder();
1265 String mn = findMethodName(mi, cnt, returnType);
1267 final int numArguments = isStatic ? cnt.length() : cnt.length() + 1;
1268 final Variable[] vars = new Variable[numArguments];
1270 for (int j = numArguments - 1; j >= 0; --j) {
1271 vars[j] = mapper.pop();
1274 if (returnType[0] != 'V') {
1275 out.append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1279 final String in = mi[0];
1280 out.append(accessClass(in.replace('/', '_')));
1281 out.append("(false).");
1284 if (numArguments > 0) {
1285 out.append(vars[0]);
1286 for (int j = 1; j < numArguments; ++j) {
1288 out.append(vars[j]);
1296 private int invokeVirtualMethod(byte[] byteCodes, int i, final StackMapper mapper)
1297 throws IOException {
1298 int methodIndex = readIntArg(byteCodes, i);
1299 String[] mi = jc.getFieldInfoName(methodIndex);
1300 char[] returnType = { 'V' };
1301 StringBuilder cnt = new StringBuilder();
1302 String mn = findMethodName(mi, cnt, returnType);
1304 final int numArguments = cnt.length() + 1;
1305 final Variable[] vars = new Variable[numArguments];
1307 for (int j = numArguments - 1; j >= 0; --j) {
1308 vars[j] = mapper.pop();
1311 if (returnType[0] != 'V') {
1312 out.append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1316 out.append(vars[0]).append('.');
1319 out.append(vars[0]);
1320 for (int j = 1; j < numArguments; ++j) {
1322 out.append(vars[j]);
1329 private void addReference(String cn) throws IOException {
1330 if (requireReference(cn)) {
1331 out.append(" /* needs ").append(cn).append(" */");
1335 private void outType(String d, StringBuilder out) {
1337 while (d.charAt(0) == '[') {
1341 if (d.charAt(0) == 'L') {
1342 assert d.charAt(d.length() - 1) == ';';
1343 out.append(d.replace('/', '_').substring(0, d.length() - 1));
1349 private String encodeConstant(int entryIndex) throws IOException {
1350 String[] classRef = { null };
1351 String s = jc.stringValue(entryIndex, classRef);
1352 if (classRef[0] != null) {
1353 addReference(classRef[0]);
1354 s = accessClass(s.replace('/', '_')) + "(false).constructor.$class";
1359 private String javaScriptBody(String prefix, MethodData m, boolean isStatic) throws IOException {
1360 byte[] arr = m.findAnnotationData(true);
1364 final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
1365 class P extends AnnotationParser {
1371 String[] args = new String[30];
1375 protected void visitAttr(String type, String attr, String at, String value) {
1376 if (type.equals(jvmType)) {
1377 if ("body".equals(attr)) {
1379 } else if ("args".equals(attr)) {
1380 args[cnt++] = value;
1382 throw new IllegalArgumentException(attr);
1389 if (p.body == null) {
1392 StringBuilder cnt = new StringBuilder();
1393 final String mn = findMethodName(m, cnt);
1394 out.append(prefix).append(mn);
1395 out.append(" = function(");
1399 space = outputArg(out, p.args, 0);
1405 for (int i = 0; i < cnt.length(); i++) {
1407 space = outputArg(out, p.args, index);
1410 out.append(") {").append("\n");
1412 out.append("\n}\n");
1415 private static String className(ClassData jc) {
1416 //return jc.getName().getInternalName().replace('/', '_');
1417 return jc.getClassName().replace('/', '_');
1420 private static String[] findAnnotation(
1421 byte[] arr, ClassData cd, final String className,
1422 final String... attrNames
1423 ) throws IOException {
1427 final String[] values = new String[attrNames.length];
1428 final boolean[] found = { false };
1429 final String jvmType = "L" + className.replace('.', '/') + ";";
1430 AnnotationParser ap = new AnnotationParser(false) {
1432 protected void visitAttr(String type, String attr, String at, String value) {
1433 if (type.equals(jvmType)) {
1435 for (int i = 0; i < attrNames.length; i++) {
1436 if (attrNames[i].equals(attr)) {
1445 return found[0] ? values : null;
1448 private CharSequence initField(FieldData v) {
1449 final String is = v.getInternalSig();
1450 if (is.length() == 1) {
1451 switch (is.charAt(0)) {
1457 case 'I': return " = 0;";
1459 case 'D': return " = 0.0;";
1461 throw new IllegalStateException(is);
1467 private static void generateAnno(ClassData cd, final Appendable out, byte[] data) throws IOException {
1468 AnnotationParser ap = new AnnotationParser(true) {
1473 protected void visitAnnotationStart(String type) throws IOException {
1477 out.append('"').append(type).append("\" : {\n");
1482 protected void visitAnnotationEnd(String type) throws IOException {
1483 out.append("\n}\n");
1487 protected void visitAttr(String type, String attr, String attrType, String value)
1488 throws IOException {
1495 out.append(attr).append("__").append(attrType).append(" : ").append(value);
1501 private static String outputArg(Appendable out, String[] args, int indx) throws IOException {
1502 final String name = args[indx];
1506 if (name.contains(",")) {
1507 throw new IOException("Wrong parameter with ',': " + name);
1513 private static void emit(final Appendable out,
1514 final String format,
1515 final CharSequence... params) throws IOException {
1516 final int length = format.length();
1519 int paramOffset = format.indexOf('@');
1520 while ((paramOffset != -1) && (paramOffset < (length - 1))) {
1521 final char paramChar = format.charAt(paramOffset + 1);
1522 if ((paramChar >= '1') && (paramChar <= '9')) {
1523 final int paramIndex = paramChar - '0' - 1;
1525 out.append(format, processed, paramOffset);
1526 out.append(params[paramIndex]);
1529 processed = paramOffset + 1;
1532 paramOffset = format.indexOf('@', paramOffset + 1);
1535 out.append(format, processed, length);