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);
150 out.append("\n c.").append(mn).append(".access = " + m.getAccess()).append(";");
152 out.append("\n c.constructor = CLS;");
153 out.append("\n c.$instOf_").append(className).append(" = true;");
154 for (String superInterface : jc.getSuperInterfaces()) {
155 out.append("\n c.$instOf_").append(superInterface.replace('/', '_')).append(" = true;");
157 out.append("\n CLS.$class = ");
158 out.append(accessClass("java_lang_Class(true);"));
159 out.append("\n CLS.$class.jvmName = '").append(jc.getClassName()).append("';");
160 out.append("\n CLS.$class.superclass = sprcls;");
161 out.append("\n CLS.$class.access = ").append(jc.getAccessFlags()+";");
162 out.append("\n CLS.$class.cnstr = CLS;");
163 byte[] classAnno = jc.findAnnotationData(false);
164 if (classAnno != null) {
165 out.append("\n CLS.$class.anno = {");
166 generateAnno(jc, out, classAnno);
170 out.append("\n if (arguments.length === 0) {");
171 out.append("\n if (!(this instanceof CLS)) {");
172 out.append("\n return new CLS();");
174 for (FieldData v : jc.getFields()) {
175 byte[] onlyArr = v.findAnnotationData(true);
176 String[] only = findAnnotation(onlyArr, jc,
177 "org.apidesign.bck2brwsr.core.JavaScriptOnly",
181 if (only[0] != null && only[1] != null) {
182 out.append("\n p.").append(only[0]).append(" = ")
183 .append(only[1]).append(";");
188 out.append("\n this.fld_").
189 append(v.getName()).append(initField(v));
192 out.append("\n return this;");
194 out.append("\n return arguments[0] ? new CLS() : CLS.prototype;");
196 StringBuilder sb = new StringBuilder();
197 for (String init : toInitilize.toArray()) {
198 sb.append("\n").append(init).append("();");
200 return sb.toString();
202 private String generateStaticMethod(String prefix, MethodData m, StringArray toInitilize) throws IOException {
203 String jsb = javaScriptBody(prefix, m, true);
207 final String mn = findMethodName(m, new StringBuilder());
208 if (mn.equals("class__V")) {
209 toInitilize.add(accessClass(className(jc)) + "(false)." + mn);
211 generateMethod(prefix, mn, m);
215 private String generateInstanceMethod(String prefix, MethodData m) throws IOException {
216 String jsb = javaScriptBody(prefix, m, false);
220 final String mn = findMethodName(m, new StringBuilder());
221 generateMethod(prefix, mn, m);
225 private void generateMethod(String prefix, String name, MethodData m)
227 final StackMapIterator stackMapIterator = m.createStackMapIterator();
228 TrapDataIterator trap = m.getTrapDataIterator();
229 final LocalsMapper lmapper =
230 new LocalsMapper(stackMapIterator.getArguments());
232 out.append(prefix).append(name).append(" = function(");
233 lmapper.outputArguments(out);
234 out.append(") {").append("\n");
236 final byte[] byteCodes = m.getCode();
237 if (byteCodes == null) {
238 out.append(" throw 'no code found for ")
239 .append(m.getInternalSig()).append("';\n");
244 final StackMapper smapper = new StackMapper();
246 final int maxLocals = m.getMaxLocals();
248 // TODO: generate only used local variables
249 for (int j = 0; j <= VarType.LAST; ++j) {
250 out.append("\n var ").append(Variable.getLocalVariable(j, 0));
251 for (int i = 1; i < maxLocals; ++i) {
253 out.append(Variable.getLocalVariable(j, i));
259 // maxStack includes two stack positions for every pushed long / double
260 // so this might generate more stack variables than we need
261 final int maxStack = m.getMaxStack();
263 // TODO: generate only used stack variables
264 for (int j = 0; j <= VarType.LAST; ++j) {
265 out.append("\n var ").append(Variable.getStackVariable(j, 0));
266 for (int i = 1; i < maxStack; ++i) {
268 out.append(Variable.getStackVariable(j, i));
274 int lastStackFrame = -1;
276 out.append("\n var gt = 0;\n for(;;) switch(gt) {\n");
277 for (int i = 0; i < byteCodes.length; i++) {
279 stackMapIterator.advanceTo(i);
281 if (lastStackFrame != stackMapIterator.getFrameIndex()) {
282 lastStackFrame = stackMapIterator.getFrameIndex();
283 lmapper.syncWithFrameLocals(stackMapIterator.getFrameLocals());
284 smapper.syncWithFrameStack(stackMapIterator.getFrameStack());
285 out.append(" case " + i).append(": ");
287 out.append(" /* " + i).append(" */ ");
292 final int c = readByte(byteCodes, i);
295 emit(out, "@1 = @2;", smapper.pushA(), lmapper.getA(0));
298 emit(out, "@1 = @2;", smapper.pushI(), lmapper.getI(0));
301 emit(out, "@1 = @2;", smapper.pushL(), lmapper.getL(0));
304 emit(out, "@1 = @2;", smapper.pushF(), lmapper.getF(0));
307 emit(out, "@1 = @2;", smapper.pushD(), lmapper.getD(0));
310 emit(out, "@1 = @2;", smapper.pushA(), lmapper.getA(1));
313 emit(out, "@1 = @2;", smapper.pushI(), lmapper.getI(1));
316 emit(out, "@1 = @2;", smapper.pushL(), lmapper.getL(1));
319 emit(out, "@1 = @2;", smapper.pushF(), lmapper.getF(1));
322 emit(out, "@1 = @2;", smapper.pushD(), lmapper.getD(1));
325 emit(out, "@1 = @2;", smapper.pushA(), lmapper.getA(2));
328 emit(out, "@1 = @2;", smapper.pushI(), lmapper.getI(2));
331 emit(out, "@1 = @2;", smapper.pushL(), lmapper.getL(2));
334 emit(out, "@1 = @2;", smapper.pushF(), lmapper.getF(2));
337 emit(out, "@1 = @2;", smapper.pushD(), lmapper.getD(2));
340 emit(out, "@1 = @2;", smapper.pushA(), lmapper.getA(3));
343 emit(out, "@1 = @2;", smapper.pushI(), lmapper.getI(3));
346 emit(out, "@1 = @2;", smapper.pushL(), lmapper.getL(3));
349 emit(out, "@1 = @2;", smapper.pushF(), lmapper.getF(3));
352 emit(out, "@1 = @2;", smapper.pushD(), lmapper.getD(3));
355 final int indx = readByte(byteCodes, ++i);
356 emit(out, "@1 = @2;", smapper.pushI(), lmapper.getI(indx));
360 final int indx = readByte(byteCodes, ++i);
361 emit(out, "@1 = @2;", smapper.pushL(), lmapper.getL(indx));
365 final int indx = readByte(byteCodes, ++i);
366 emit(out, "@1 = @2;", smapper.pushF(), lmapper.getF(indx));
370 final int indx = readByte(byteCodes, ++i);
371 emit(out, "@1 = @2;", smapper.pushD(), lmapper.getD(indx));
375 final int indx = readByte(byteCodes, ++i);
376 emit(out, "@1 = @2;", smapper.pushA(), lmapper.getA(indx));
380 final int indx = readByte(byteCodes, ++i);
381 emit(out, "@1 = @2;", lmapper.setI(indx), smapper.popI());
385 final int indx = readByte(byteCodes, ++i);
386 emit(out, "@1 = @2;", lmapper.setL(indx), smapper.popL());
390 final int indx = readByte(byteCodes, ++i);
391 emit(out, "@1 = @2;", lmapper.setF(indx), smapper.popF());
395 final int indx = readByte(byteCodes, ++i);
396 emit(out, "@1 = @2;", lmapper.setD(indx), smapper.popD());
400 final int indx = readByte(byteCodes, ++i);
401 emit(out, "@1 = @2;", lmapper.setA(indx), smapper.popA());
405 emit(out, "@1 = @2;", lmapper.setA(0), smapper.popA());
408 emit(out, "@1 = @2;", lmapper.setI(0), smapper.popI());
411 emit(out, "@1 = @2;", lmapper.setL(0), smapper.popL());
414 emit(out, "@1 = @2;", lmapper.setF(0), smapper.popF());
417 emit(out, "@1 = @2;", lmapper.setD(0), smapper.popD());
420 emit(out, "@1 = @2;", lmapper.setA(1), smapper.popA());
423 emit(out, "@1 = @2;", lmapper.setI(1), smapper.popI());
426 emit(out, "@1 = @2;", lmapper.setL(1), smapper.popL());
429 emit(out, "@1 = @2;", lmapper.setF(1), smapper.popF());
432 emit(out, "@1 = @2;", lmapper.setD(1), smapper.popD());
435 emit(out, "@1 = @2;", lmapper.setA(2), smapper.popA());
438 emit(out, "@1 = @2;", lmapper.setI(2), smapper.popI());
441 emit(out, "@1 = @2;", lmapper.setL(2), smapper.popL());
444 emit(out, "@1 = @2;", lmapper.setF(2), smapper.popF());
447 emit(out, "@1 = @2;", lmapper.setD(2), smapper.popD());
450 emit(out, "@1 = @2;", lmapper.setA(3), smapper.popA());
453 emit(out, "@1 = @2;", lmapper.setI(3), smapper.popI());
456 emit(out, "@1 = @2;", lmapper.setL(3), smapper.popL());
459 emit(out, "@1 = @2;", lmapper.setF(3), smapper.popF());
462 emit(out, "@1 = @2;", lmapper.setD(3), smapper.popD());
465 emit(out, "@1 += @2;", smapper.getI(1), smapper.popI());
468 emit(out, "@1 += @2;", smapper.getL(1), smapper.popL());
471 emit(out, "@1 += @2;", smapper.getF(1), smapper.popF());
474 emit(out, "@1 += @2;", smapper.getD(1), smapper.popD());
477 emit(out, "@1 -= @2;", smapper.getI(1), smapper.popI());
480 emit(out, "@1 -= @2;", smapper.getL(1), smapper.popL());
483 emit(out, "@1 -= @2;", smapper.getF(1), smapper.popF());
486 emit(out, "@1 -= @2;", smapper.getD(1), smapper.popD());
489 emit(out, "@1 *= @2;", smapper.getI(1), smapper.popI());
492 emit(out, "@1 *= @2;", smapper.getL(1), smapper.popL());
495 emit(out, "@1 *= @2;", smapper.getF(1), smapper.popF());
498 emit(out, "@1 *= @2;", smapper.getD(1), smapper.popD());
501 emit(out, "@1 = Math.floor(@1 / @2);",
502 smapper.getI(1), smapper.popI());
505 emit(out, "@1 = Math.floor(@1 / @2);",
506 smapper.getL(1), smapper.popL());
509 emit(out, "@1 /= @2;", smapper.getF(1), smapper.popF());
512 emit(out, "@1 /= @2;", smapper.getD(1), smapper.popD());
515 emit(out, "@1 %= @2;", smapper.getI(1), smapper.popI());
518 emit(out, "@1 %= @2;", smapper.getL(1), smapper.popL());
521 emit(out, "@1 %= @2;", smapper.getF(1), smapper.popF());
524 emit(out, "@1 %= @2;", smapper.getD(1), smapper.popD());
527 emit(out, "@1 &= @2;", smapper.getI(1), smapper.popI());
530 emit(out, "@1 &= @2;", smapper.getL(1), smapper.popL());
533 emit(out, "@1 |= @2;", smapper.getI(1), smapper.popI());
536 emit(out, "@1 |= @2;", smapper.getL(1), smapper.popL());
539 emit(out, "@1 ^= @2;", smapper.getI(1), smapper.popI());
542 emit(out, "@1 ^= @2;", smapper.getL(1), smapper.popL());
545 emit(out, "@1 = -@1;", smapper.getI(0));
548 emit(out, "@1 = -@1;", smapper.getL(0));
551 emit(out, "@1 = -@1;", smapper.getF(0));
554 emit(out, "@1 = -@1;", smapper.getD(0));
557 emit(out, "@1 <<= @2;", smapper.getI(1), smapper.popI());
560 emit(out, "@1 <<= @2;", smapper.getL(1), smapper.popI());
563 emit(out, "@1 >>= @2;", smapper.getI(1), smapper.popI());
566 emit(out, "@1 >>= @2;", smapper.getL(1), smapper.popI());
569 emit(out, "@1 >>>= @2;", smapper.getI(1), smapper.popI());
572 emit(out, "@1 >>>= @2;", smapper.getL(1), smapper.popI());
575 final int varIndx = readByte(byteCodes, ++i);
576 final int incrBy = byteCodes[++i];
578 emit(out, "@1++;", lmapper.getI(varIndx));
580 emit(out, "@1 += @2;",
581 lmapper.getI(varIndx),
582 Integer.toString(incrBy));
587 emit(out, "return;");
590 emit(out, "return @1;", smapper.popI());
593 emit(out, "return @1;", smapper.popL());
596 emit(out, "return @1;", smapper.popF());
599 emit(out, "return @1;", smapper.popD());
602 emit(out, "return @1;", smapper.popA());
605 emit(out, "@2 = @1;", smapper.popI(), smapper.pushL());
608 emit(out, "@2 = @1;", smapper.popI(), smapper.pushF());
611 emit(out, "@2 = @1;", smapper.popI(), smapper.pushD());
614 emit(out, "@2 = @1;", smapper.popL(), smapper.pushI());
618 emit(out, "@2 = @1;", smapper.popL(), smapper.pushF());
621 emit(out, "@2 = @1;", smapper.popL(), smapper.pushD());
624 emit(out, "@2 = @1;", smapper.popF(), smapper.pushD());
627 emit(out, "@2 = @1;", smapper.popD(), smapper.pushF());
630 emit(out, "@2 = Math.floor(@1);",
631 smapper.popF(), smapper.pushI());
634 emit(out, "@2 = Math.floor(@1);",
635 smapper.popF(), smapper.pushL());
638 emit(out, "@2 = Math.floor(@1);",
639 smapper.popD(), smapper.pushI());
642 emit(out, "@2 = Math.floor(@1);",
643 smapper.popD(), smapper.pushL());
648 out.append("{ /* number conversion */ }");
650 case opc_aconst_null:
651 emit(out, "@1 = null;", smapper.pushA());
654 emit(out, "@1 = -1;", smapper.pushI());
657 emit(out, "@1 = 0;", smapper.pushI());
660 emit(out, "@1 = 0;", smapper.pushD());
663 emit(out, "@1 = 0;", smapper.pushL());
666 emit(out, "@1 = 0;", smapper.pushF());
669 emit(out, "@1 = 1;", smapper.pushI());
672 emit(out, "@1 = 1;", smapper.pushL());
675 emit(out, "@1 = 1;", smapper.pushF());
678 emit(out, "@1 = 1;", smapper.pushD());
681 emit(out, "@1 = 2;", smapper.pushI());
684 emit(out, "@1 = 2;", smapper.pushF());
687 emit(out, "@1 = 3;", smapper.pushI());
690 emit(out, "@1 = 4;", smapper.pushI());
693 emit(out, "@1 = 5;", smapper.pushI());
696 int indx = readByte(byteCodes, ++i);
697 String v = encodeConstant(indx);
698 int type = VarType.fromConstantType(jc.getTag(indx));
699 emit(out, "@1 = @2;", smapper.pushT(type), v);
704 int indx = readIntArg(byteCodes, i);
706 String v = encodeConstant(indx);
707 int type = VarType.fromConstantType(jc.getTag(indx));
708 emit(out, "@1 = @2;", smapper.pushT(type), v);
712 emit(out, "@3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
713 smapper.popL(), smapper.popL(), smapper.pushI());
717 emit(out, "@3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
718 smapper.popF(), smapper.popF(), smapper.pushI());
722 emit(out, "@3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
723 smapper.popD(), smapper.popD(), smapper.pushI());
726 i = generateIf(byteCodes, i, smapper.popA(), smapper.popA(),
730 i = generateIf(byteCodes, i, smapper.popA(), smapper.popA(),
734 i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
738 int indx = i + readIntArg(byteCodes, i);
739 emit(out, "if (@1 == 0) { gt = @2; continue; }",
740 smapper.popI(), Integer.toString(indx));
745 int indx = i + readIntArg(byteCodes, i);
746 emit(out, "if (@1 != 0) { gt = @2; continue; }",
747 smapper.popI(), Integer.toString(indx));
752 int indx = i + readIntArg(byteCodes, i);
753 emit(out, "if (@1 < 0) { gt = @2; continue; }",
754 smapper.popI(), Integer.toString(indx));
759 int indx = i + readIntArg(byteCodes, i);
760 emit(out, "if (@1 <= 0) { gt = @2; continue; }",
761 smapper.popI(), Integer.toString(indx));
766 int indx = i + readIntArg(byteCodes, i);
767 emit(out, "if (@1 > 0) { gt = @2; continue; }",
768 smapper.popI(), Integer.toString(indx));
773 int indx = i + readIntArg(byteCodes, i);
774 emit(out, "if (@1 >= 0) { gt = @2; continue; }",
775 smapper.popI(), Integer.toString(indx));
779 case opc_ifnonnull: {
780 int indx = i + readIntArg(byteCodes, i);
781 emit(out, "if (@1 !== null) { gt = @2; continue; }",
782 smapper.popA(), Integer.toString(indx));
787 int indx = i + readIntArg(byteCodes, i);
788 emit(out, "if (@1 === null) { gt = @2; continue; }",
789 smapper.popA(), Integer.toString(indx));
794 i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
798 i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
802 i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
806 i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
810 i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
814 int indx = i + readIntArg(byteCodes, i);
815 emit(out, "gt = @1; continue;", Integer.toString(indx));
819 case opc_lookupswitch: {
820 int table = i / 4 * 4 + 4;
821 int dflt = i + readInt4(byteCodes, table);
823 int n = readInt4(byteCodes, table);
825 out.append("switch (").append(smapper.popI()).append(") {\n");
827 int cnstnt = readInt4(byteCodes, table);
829 int offset = i + readInt4(byteCodes, table);
831 out.append(" case " + cnstnt).append(": gt = " + offset).append("; continue;\n");
833 out.append(" default: gt = " + dflt).append("; continue;\n}");
837 case opc_tableswitch: {
838 int table = i / 4 * 4 + 4;
839 int dflt = i + readInt4(byteCodes, table);
841 int low = readInt4(byteCodes, table);
843 int high = readInt4(byteCodes, table);
845 out.append("switch (").append(smapper.popI()).append(") {\n");
846 while (low <= high) {
847 int offset = i + readInt4(byteCodes, table);
849 out.append(" case " + low).append(": gt = " + offset).append("; continue;\n");
852 out.append(" default: gt = " + dflt).append("; continue;\n}");
856 case opc_invokeinterface: {
857 i = invokeVirtualMethod(byteCodes, i, smapper) + 2;
860 case opc_invokevirtual:
861 i = invokeVirtualMethod(byteCodes, i, smapper);
863 case opc_invokespecial:
864 i = invokeStaticMethod(byteCodes, i, smapper, false);
866 case opc_invokestatic:
867 i = invokeStaticMethod(byteCodes, i, smapper, true);
870 int indx = readIntArg(byteCodes, i);
871 String ci = jc.getClassName(indx);
872 emit(out, "@1 = new @2;",
873 smapper.pushA(), accessClass(ci.replace('/', '_')));
879 ++i; // skip type of array
880 emit(out, "@2 = new Array(@1).fillNulls();",
881 smapper.popI(), smapper.pushA());
884 i += 2; // skip type of array
885 emit(out, "@2 = new Array(@1).fillNulls();",
886 smapper.popI(), smapper.pushA());
888 case opc_multianewarray: {
890 int dim = readByte(byteCodes, ++i);
891 out.append("{ var a0 = new Array(").append(smapper.popI())
892 .append(").fillNulls();");
893 for (int d = 1; d < dim; d++) {
894 out.append("\n var l" + d).append(" = ")
895 .append(smapper.popI()).append(';');
896 out.append("\n for (var i" + d).append (" = 0; i" + d).
897 append(" < a" + (d - 1)).
898 append(".length; i" + d).append("++) {");
899 out.append("\n var a" + d).
900 append (" = new Array(l" + d).append(").fillNulls();");
901 out.append("\n a" + (d - 1)).append("[i" + d).append("] = a" + d).
904 for (int d = 1; d < dim; d++) {
907 out.append("\n").append(smapper.pushA()).append(" = a0; }");
910 case opc_arraylength:
911 emit(out, "@2 = @1.length;", smapper.popA(), smapper.pushI());
914 emit(out, "@3[@2] = @1;",
915 smapper.popL(), smapper.popI(), smapper.popA());
918 emit(out, "@3[@2] = @1;",
919 smapper.popF(), smapper.popI(), smapper.popA());
922 emit(out, "@3[@2] = @1;",
923 smapper.popD(), smapper.popI(), smapper.popA());
926 emit(out, "@3[@2] = @1;",
927 smapper.popA(), smapper.popI(), smapper.popA());
933 emit(out, "@3[@2] = @1;",
934 smapper.popI(), smapper.popI(), smapper.popA());
937 emit(out, "@3 = @2[@1];",
938 smapper.popI(), smapper.popA(), smapper.pushL());
941 emit(out, "@3 = @2[@1];",
942 smapper.popI(), smapper.popA(), smapper.pushF());
945 emit(out, "@3 = @2[@1];",
946 smapper.popI(), smapper.popA(), smapper.pushD());
949 emit(out, "@3 = @2[@1];",
950 smapper.popI(), smapper.popA(), smapper.pushA());
956 emit(out, "@3 = @2[@1];",
957 smapper.popI(), smapper.popA(), smapper.pushI());
962 out.append("/* pop */");
965 final Variable v = smapper.get(0);
966 emit(out, "@1 = @2;", smapper.pushT(v.getType()), v);
970 if (smapper.get(0).isCategory2()) {
971 final Variable v = smapper.get(0);
972 emit(out, "@1 = @2;", smapper.pushT(v.getType()), v);
974 final Variable v1 = smapper.get(0);
975 final Variable v2 = smapper.get(1);
976 emit(out, "{ @1 = @2; @3 = @4; }",
977 smapper.pushT(v2.getType()), v2,
978 smapper.pushT(v1.getType()), v1);
983 final Variable vi1 = smapper.pop();
984 final Variable vi2 = smapper.pop();
985 final Variable vo3 = smapper.pushT(vi1.getType());
986 final Variable vo2 = smapper.pushT(vi2.getType());
987 final Variable vo1 = smapper.pushT(vi1.getType());
989 emit(out, "{ @1 = @2; @3 = @4; @5 = @6; }",
990 vo1, vi1, vo2, vi2, vo3, vo1);
994 if (smapper.get(1).isCategory2()) {
995 final Variable vi1 = smapper.pop();
996 final Variable vi2 = smapper.pop();
997 final Variable vo3 = smapper.pushT(vi1.getType());
998 final Variable vo2 = smapper.pushT(vi2.getType());
999 final Variable vo1 = smapper.pushT(vi1.getType());
1001 emit(out, "{ @1 = @2; @3 = @4; @5 = @6; }",
1002 vo1, vi1, vo2, vi2, vo3, vo1);
1004 final Variable vi1 = smapper.pop();
1005 final Variable vi2 = smapper.pop();
1006 final Variable vi3 = smapper.pop();
1007 final Variable vo4 = smapper.pushT(vi1.getType());
1008 final Variable vo3 = smapper.pushT(vi3.getType());
1009 final Variable vo2 = smapper.pushT(vi2.getType());
1010 final Variable vo1 = smapper.pushT(vi1.getType());
1012 emit(out, "{ @1 = @2; @3 = @4; @5 = @6; @7 = @8; }",
1013 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1018 emit(out, "@1 = @2;",
1019 smapper.pushI(), Integer.toString(byteCodes[++i]));
1022 emit(out, "@1 = @2;",
1024 Integer.toString(readIntArg(byteCodes, i)));
1027 case opc_getfield: {
1028 int indx = readIntArg(byteCodes, i);
1029 String[] fi = jc.getFieldInfoName(indx);
1030 final int type = VarType.fromFieldType(fi[2].charAt(0));
1031 emit(out, "@2 = @1.fld_@3;",
1032 smapper.popA(), smapper.pushT(type), fi[1]);
1036 case opc_getstatic: {
1037 int indx = readIntArg(byteCodes, i);
1038 String[] fi = jc.getFieldInfoName(indx);
1039 final int type = VarType.fromFieldType(fi[2].charAt(0));
1040 emit(out, "@1 = @2(false).constructor.@3;",
1041 smapper.pushT(type),
1042 accessClass(fi[0].replace('/', '_')), fi[1]);
1044 addReference(fi[0]);
1047 case opc_putfield: {
1048 int indx = readIntArg(byteCodes, i);
1049 String[] fi = jc.getFieldInfoName(indx);
1050 final int type = VarType.fromFieldType(fi[2].charAt(0));
1051 emit(out, "@2.fld_@3 = @1;",
1052 smapper.popT(type), smapper.popA(), fi[1]);
1056 case opc_putstatic: {
1057 int indx = readIntArg(byteCodes, i);
1058 String[] fi = jc.getFieldInfoName(indx);
1059 final int type = VarType.fromFieldType(fi[2].charAt(0));
1060 emit(out, "@1(false).constructor.@2 = @3;",
1061 accessClass(fi[0].replace('/', '_')), fi[1],
1062 smapper.popT(type));
1064 addReference(fi[0]);
1067 case opc_checkcast: {
1068 int indx = readIntArg(byteCodes, i);
1069 final String type = jc.getClassName(indx);
1070 if (!type.startsWith("[")) {
1071 // no way to check arrays right now
1072 // XXX proper exception
1074 "if (@1 !== null && !@1.$instOf_@2) throw {};",
1075 smapper.getA(0), type.replace('/', '_'));
1080 case opc_instanceof: {
1081 int indx = readIntArg(byteCodes, i);
1082 final String type = jc.getClassName(indx);
1083 emit(out, "@2 = @1.$instOf_@3 ? 1 : 0;",
1084 smapper.popA(), smapper.pushI(),
1085 type.replace('/', '_'));
1090 final Variable v = smapper.popA();
1093 emit(out, "{ @1 = @2; throw @2; }",
1094 smapper.pushA(), v);
1098 case opc_monitorenter: {
1099 out.append("/* monitor enter */");
1104 case opc_monitorexit: {
1105 out.append("/* monitor exit */");
1111 emit(out, "throw 'unknown bytecode @1';",
1112 Integer.toString(c));
1115 if (trap.useTry()) {
1116 out.append("} catch (e) {");
1117 for (TrapData e : trap.current()) {
1121 if (e.catch_cpx != 0) { //not finally
1122 final String classInternalName = jc.getClassName(e.catch_cpx);
1123 addReference(classInternalName);
1124 out.append("if (e.$instOf_"+classInternalName.replace('/', '_')+") {");
1125 out.append("gt="+e.handler_pc+"; continue;");
1131 out.append("throw e;");
1135 for (int j = prev; j <= i; j++) {
1137 final int cc = readByte(byteCodes, j);
1138 out.append(Integer.toString(cc));
1146 private int generateIf(byte[] byteCodes, int i,
1147 final Variable v2, final Variable v1,
1148 final String test) throws IOException {
1149 int indx = i + readIntArg(byteCodes, i);
1150 out.append("if (").append(v1)
1151 .append(' ').append(test).append(' ')
1152 .append(v2).append(") { gt = " + indx)
1153 .append("; continue; }");
1157 private int readIntArg(byte[] byteCodes, int offsetInstruction) {
1158 final int indxHi = byteCodes[offsetInstruction + 1] << 8;
1159 final int indxLo = byteCodes[offsetInstruction + 2];
1160 return (indxHi & 0xffffff00) | (indxLo & 0xff);
1162 private int readInt4(byte[] byteCodes, int offsetInstruction) {
1163 final int d = byteCodes[offsetInstruction + 0] << 24;
1164 final int c = byteCodes[offsetInstruction + 1] << 16;
1165 final int b = byteCodes[offsetInstruction + 2] << 8;
1166 final int a = byteCodes[offsetInstruction + 3];
1167 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
1169 private int readByte(byte[] byteCodes, int offsetInstruction) {
1170 return byteCodes[offsetInstruction] & 0xff;
1173 private static void countArgs(String descriptor, char[] returnType, StringBuilder sig, StringBuilder cnt) {
1175 Boolean count = null;
1176 boolean array = false;
1178 int firstPos = sig.length();
1179 while (i < descriptor.length()) {
1180 char ch = descriptor.charAt(i++);
1201 if (ch == 'J' || ch == 'D') {
1207 sig.insert(firstPos, ch);
1209 returnType[0] = '[';
1210 sig.insert(firstPos, "_3");
1219 returnType[0] = 'V';
1220 sig.insert(firstPos, 'V');
1223 int next = descriptor.indexOf(';', i);
1224 String realSig = mangleSig(descriptor, i - 1, next + 1);
1229 sig.append(realSig);
1232 sig.insert(firstPos, realSig);
1234 sig.insert(firstPos, "_3");
1236 returnType[0] = 'L';
1244 throw new IllegalStateException("Invalid char: " + ch);
1249 private static String mangleSig(String txt, int first, int last) {
1250 StringBuilder sb = new StringBuilder();
1251 for (int i = first; i < last; i++) {
1252 final char ch = txt.charAt(i);
1254 case '/': sb.append('_'); break;
1255 case '_': sb.append("_1"); break;
1256 case ';': sb.append("_2"); break;
1257 case '[': sb.append("_3"); break;
1258 default: sb.append(ch); break;
1261 return sb.toString();
1264 private static String findMethodName(MethodData m, StringBuilder cnt) {
1265 StringBuilder name = new StringBuilder();
1266 if ("<init>".equals(m.getName())) { // NOI18N
1267 name.append("cons"); // NOI18N
1268 } else if ("<clinit>".equals(m.getName())) { // NOI18N
1269 name.append("class"); // NOI18N
1271 name.append(m.getName());
1274 countArgs(m.getInternalSig(), new char[1], name, cnt);
1275 return name.toString();
1278 static String findMethodName(String[] mi, StringBuilder cnt, char[] returnType) {
1279 StringBuilder name = new StringBuilder();
1280 String descr = mi[2];//mi.getDescriptor();
1282 if ("<init>".equals(nm)) { // NOI18N
1283 name.append("cons"); // NOI18N
1287 countArgs(descr, returnType, name, cnt);
1288 return name.toString();
1291 private int invokeStaticMethod(byte[] byteCodes, int i, final StackMapper mapper, boolean isStatic)
1292 throws IOException {
1293 int methodIndex = readIntArg(byteCodes, i);
1294 String[] mi = jc.getFieldInfoName(methodIndex);
1295 char[] returnType = { 'V' };
1296 StringBuilder cnt = new StringBuilder();
1297 String mn = findMethodName(mi, cnt, returnType);
1299 final int numArguments = isStatic ? cnt.length() : cnt.length() + 1;
1300 final Variable[] vars = new Variable[numArguments];
1302 for (int j = numArguments - 1; j >= 0; --j) {
1303 vars[j] = mapper.pop();
1306 if (returnType[0] != 'V') {
1307 out.append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1311 final String in = mi[0];
1312 out.append(accessClass(in.replace('/', '_')));
1313 out.append("(false).");
1316 if (numArguments > 0) {
1317 out.append(vars[0]);
1318 for (int j = 1; j < numArguments; ++j) {
1320 out.append(vars[j]);
1328 private int invokeVirtualMethod(byte[] byteCodes, int i, final StackMapper mapper)
1329 throws IOException {
1330 int methodIndex = readIntArg(byteCodes, i);
1331 String[] mi = jc.getFieldInfoName(methodIndex);
1332 char[] returnType = { 'V' };
1333 StringBuilder cnt = new StringBuilder();
1334 String mn = findMethodName(mi, cnt, returnType);
1336 final int numArguments = cnt.length() + 1;
1337 final Variable[] vars = new Variable[numArguments];
1339 for (int j = numArguments - 1; j >= 0; --j) {
1340 vars[j] = mapper.pop();
1343 if (returnType[0] != 'V') {
1344 out.append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1348 out.append(vars[0]).append('.');
1351 out.append(vars[0]);
1352 for (int j = 1; j < numArguments; ++j) {
1354 out.append(vars[j]);
1361 private void addReference(String cn) throws IOException {
1362 if (requireReference(cn)) {
1363 out.append(" /* needs ").append(cn).append(" */");
1367 private void outType(String d, StringBuilder out) {
1369 while (d.charAt(0) == '[') {
1373 if (d.charAt(0) == 'L') {
1374 assert d.charAt(d.length() - 1) == ';';
1375 out.append(d.replace('/', '_').substring(0, d.length() - 1));
1381 private String encodeConstant(int entryIndex) throws IOException {
1382 String[] classRef = { null };
1383 String s = jc.stringValue(entryIndex, classRef);
1384 if (classRef[0] != null) {
1385 addReference(classRef[0]);
1386 s = accessClass(s.replace('/', '_')) + "(false).constructor.$class";
1391 private String javaScriptBody(String prefix, MethodData m, boolean isStatic) throws IOException {
1392 byte[] arr = m.findAnnotationData(true);
1396 final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
1397 class P extends AnnotationParser {
1403 String[] args = new String[30];
1407 protected void visitAttr(String type, String attr, String at, String value) {
1408 if (type.equals(jvmType)) {
1409 if ("body".equals(attr)) {
1411 } else if ("args".equals(attr)) {
1412 args[cnt++] = value;
1414 throw new IllegalArgumentException(attr);
1421 if (p.body == null) {
1424 StringBuilder cnt = new StringBuilder();
1425 final String mn = findMethodName(m, cnt);
1426 out.append(prefix).append(mn);
1427 out.append(" = function(");
1431 space = outputArg(out, p.args, 0);
1437 for (int i = 0; i < cnt.length(); i++) {
1439 space = outputArg(out, p.args, index);
1442 out.append(") {").append("\n");
1444 out.append("\n}\n");
1447 private static String className(ClassData jc) {
1448 //return jc.getName().getInternalName().replace('/', '_');
1449 return jc.getClassName().replace('/', '_');
1452 private static String[] findAnnotation(
1453 byte[] arr, ClassData cd, final String className,
1454 final String... attrNames
1455 ) throws IOException {
1459 final String[] values = new String[attrNames.length];
1460 final boolean[] found = { false };
1461 final String jvmType = "L" + className.replace('.', '/') + ";";
1462 AnnotationParser ap = new AnnotationParser(false) {
1464 protected void visitAttr(String type, String attr, String at, String value) {
1465 if (type.equals(jvmType)) {
1467 for (int i = 0; i < attrNames.length; i++) {
1468 if (attrNames[i].equals(attr)) {
1477 return found[0] ? values : null;
1480 private CharSequence initField(FieldData v) {
1481 final String is = v.getInternalSig();
1482 if (is.length() == 1) {
1483 switch (is.charAt(0)) {
1489 case 'I': return " = 0;";
1491 case 'D': return " = 0.0;";
1493 throw new IllegalStateException(is);
1499 private static void generateAnno(ClassData cd, final Appendable out, byte[] data) throws IOException {
1500 AnnotationParser ap = new AnnotationParser(true) {
1505 protected void visitAnnotationStart(String type) throws IOException {
1509 out.append('"').append(type).append("\" : {\n");
1514 protected void visitAnnotationEnd(String type) throws IOException {
1515 out.append("\n}\n");
1519 protected void visitAttr(String type, String attr, String attrType, String value)
1520 throws IOException {
1527 out.append(attr).append("__").append(attrType).append(" : ").append(value);
1533 private static String outputArg(Appendable out, String[] args, int indx) throws IOException {
1534 final String name = args[indx];
1538 if (name.contains(",")) {
1539 throw new IOException("Wrong parameter with ',': " + name);
1545 private static void emit(final Appendable out,
1546 final String format,
1547 final CharSequence... params) throws IOException {
1548 final int length = format.length();
1551 int paramOffset = format.indexOf('@');
1552 while ((paramOffset != -1) && (paramOffset < (length - 1))) {
1553 final char paramChar = format.charAt(paramOffset + 1);
1554 if ((paramChar >= '1') && (paramChar <= '9')) {
1555 final int paramIndex = paramChar - '0' - 1;
1557 out.append(format, processed, paramOffset);
1558 out.append(params[paramIndex]);
1561 processed = paramOffset + 1;
1564 paramOffset = format.indexOf('@', paramOffset + 1);
1567 out.append(format, processed, length);