Constructors are not assigned to prototype, as they are not inherited. newInstance checks for access rights.
2 * Back 2 Browser Bytecode Translator
3 * Copyright (C) 2012 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, version 2 of the License.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. Look for COPYING file in the top folder.
16 * If not, see http://opensource.org/licenses/GPL-2.0.
18 package org.apidesign.vm4brwsr;
20 import java.io.IOException;
21 import java.io.InputStream;
22 import org.apidesign.javap.AnnotationParser;
23 import org.apidesign.javap.ClassData;
24 import org.apidesign.javap.FieldData;
25 import org.apidesign.javap.MethodData;
26 import org.apidesign.javap.StackMapIterator;
27 import static org.apidesign.javap.RuntimeConstants.*;
28 import org.apidesign.javap.TrapData;
29 import org.apidesign.javap.TrapDataIterator;
31 /** Translator of the code inside class files to JavaScript.
33 * @author Jaroslav Tulach <jtulach@netbeans.org>
35 abstract class ByteCodeToJavaScript {
39 protected ByteCodeToJavaScript(Appendable out) {
43 /* Collects additional required resources.
45 * @param internalClassName classes that were referenced and should be loaded in order the
46 * generated JavaScript code works properly. The names are in internal
47 * JVM form so String is <code>java/lang/String</code>.
49 protected abstract boolean requireReference(String internalClassName);
52 * @param resourcePath name of resources to read
54 protected abstract void requireScript(String resourcePath);
56 /** Allows subclasses to redefine what field a function representing a
57 * class gets assigned. By default it returns the suggested name followed
58 * by <code>" = "</code>;
60 * @param className suggested name of the class
62 /* protected */ String assignClass(String className) {
63 return className + " = ";
65 /* protected */ String accessClass(String classOperation) {
66 return classOperation;
70 * Converts a given class file to a JavaScript version.
72 * @param classFile input stream with code of the .class file
73 * @return the initialization code for this class, if any. Otherwise <code>null</code>
75 * @throws IOException if something goes wrong during read or write or translating
78 public String compile(InputStream classFile) throws IOException {
79 this.jc = new ClassData(classFile);
80 if (jc.getMajor_version() < 50) {
81 throw new IOException("Can't compile " + jc.getClassName() + ". Class file version " + jc.getMajor_version() + "."
82 + jc.getMinor_version() + " - recompile with -target 1.6 (at least)."
85 byte[] arrData = jc.findAnnotationData(true);
86 String[] arr = findAnnotation(arrData, jc,
87 "org.apidesign.bck2brwsr.core.ExtraJavaScript",
88 "resource", "processByteCode"
91 requireScript(arr[0]);
92 if ("0".equals(arr[1])) {
96 String[] proto = findAnnotation(arrData, jc,
97 "org.apidesign.bck2brwsr.core.JavaScriptPrototype",
98 "container", "prototype"
100 StringArray toInitilize = new StringArray();
101 final String className = className(jc);
102 out.append("\n\n").append(assignClass(className));
103 out.append("function CLS() {");
104 out.append("\n if (!CLS.prototype.$instOf_").append(className).append(") {");
105 for (FieldData v : jc.getFields()) {
107 out.append("\n CLS.").append(v.getName()).append(initField(v));
111 String sc = jc.getSuperClassName(); // with _
112 out.append("\n var pp = ").
113 append(accessClass(sc.replace('/', '_'))).append("(true);");
114 out.append("\n var p = CLS.prototype = pp;");
115 out.append("\n var c = p;");
116 out.append("\n var sprcls = pp.constructor.$class;");
118 out.append("\n var p = CLS.prototype = ").append(proto[1]).append(";");
119 if (proto[0] == null) {
122 out.append("\n var c = ").append(proto[0]).append(";");
123 out.append("\n var sprcls = null;");
125 for (MethodData m : jc.getMethods()) {
126 byte[] onlyArr = m.findAnnotationData(true);
127 String[] only = findAnnotation(onlyArr, jc,
128 "org.apidesign.bck2brwsr.core.JavaScriptOnly",
132 if (only[0] != null && only[1] != null) {
133 out.append("\n p.").append(only[0]).append(" = ")
134 .append(only[1]).append(";");
142 mn = generateStaticMethod(prefix, m, toInitilize);
144 if (m.isConstructor()) {
146 mn = generateInstanceMethod(prefix, m);
149 mn = generateInstanceMethod(prefix, m);
152 byte[] runAnno = m.findAnnotationData(false);
153 if (runAnno != null) {
154 out.append(prefix).append(mn).append(".anno = {");
155 generateAnno(jc, out, runAnno);
158 out.append(prefix).append(mn).append(".access = " + m.getAccess()).append(";");
160 out.append("\n c.constructor = CLS;");
161 out.append("\n c.$instOf_").append(className).append(" = true;");
162 for (String superInterface : jc.getSuperInterfaces()) {
163 out.append("\n c.$instOf_").append(superInterface.replace('/', '_')).append(" = true;");
165 out.append("\n CLS.$class = ");
166 out.append(accessClass("java_lang_Class(true);"));
167 out.append("\n CLS.$class.jvmName = '").append(jc.getClassName()).append("';");
168 out.append("\n CLS.$class.superclass = sprcls;");
169 out.append("\n CLS.$class.access = ").append(jc.getAccessFlags()+";");
170 out.append("\n CLS.$class.cnstr = CLS;");
171 byte[] classAnno = jc.findAnnotationData(false);
172 if (classAnno != null) {
173 out.append("\n CLS.$class.anno = {");
174 generateAnno(jc, out, classAnno);
178 out.append("\n if (arguments.length === 0) {");
179 out.append("\n if (!(this instanceof CLS)) {");
180 out.append("\n return new CLS();");
182 for (FieldData v : jc.getFields()) {
183 byte[] onlyArr = v.findAnnotationData(true);
184 String[] only = findAnnotation(onlyArr, jc,
185 "org.apidesign.bck2brwsr.core.JavaScriptOnly",
189 if (only[0] != null && only[1] != null) {
190 out.append("\n p.").append(only[0]).append(" = ")
191 .append(only[1]).append(";");
196 out.append("\n this.fld_").
197 append(v.getName()).append(initField(v));
200 out.append("\n return this;");
202 out.append("\n return arguments[0] ? new CLS() : CLS.prototype;");
204 StringBuilder sb = new StringBuilder();
205 for (String init : toInitilize.toArray()) {
206 sb.append("\n").append(init).append("();");
208 return sb.toString();
210 private String generateStaticMethod(String prefix, MethodData m, StringArray toInitilize) throws IOException {
211 String jsb = javaScriptBody(prefix, m, true);
215 final String mn = findMethodName(m, new StringBuilder());
216 if (mn.equals("class__V")) {
217 toInitilize.add(accessClass(className(jc)) + "(false)." + mn);
219 generateMethod(prefix, mn, m);
223 private String generateInstanceMethod(String prefix, MethodData m) throws IOException {
224 String jsb = javaScriptBody(prefix, m, false);
228 final String mn = findMethodName(m, new StringBuilder());
229 generateMethod(prefix, mn, m);
233 private void generateMethod(String prefix, String name, MethodData m)
235 final StackMapIterator stackMapIterator = m.createStackMapIterator();
236 TrapDataIterator trap = m.getTrapDataIterator();
237 final LocalsMapper lmapper =
238 new LocalsMapper(stackMapIterator.getArguments());
240 out.append(prefix).append(name).append(" = function(");
241 lmapper.outputArguments(out);
242 out.append(") {").append("\n");
244 final byte[] byteCodes = m.getCode();
245 if (byteCodes == null) {
246 out.append(" throw 'no code found for ")
247 .append(m.getInternalSig()).append("';\n");
252 final StackMapper smapper = new StackMapper();
254 final int maxLocals = m.getMaxLocals();
256 // TODO: generate only used local variables
257 for (int j = 0; j <= VarType.LAST; ++j) {
258 out.append("\n var ").append(Variable.getLocalVariable(j, 0));
259 for (int i = 1; i < maxLocals; ++i) {
261 out.append(Variable.getLocalVariable(j, i));
267 // maxStack includes two stack positions for every pushed long / double
268 // so this might generate more stack variables than we need
269 final int maxStack = m.getMaxStack();
271 // TODO: generate only used stack variables
272 for (int j = 0; j <= VarType.LAST; ++j) {
273 out.append("\n var ").append(Variable.getStackVariable(j, 0));
274 for (int i = 1; i < maxStack; ++i) {
276 out.append(Variable.getStackVariable(j, i));
282 int lastStackFrame = -1;
284 out.append("\n var gt = 0;\n for(;;) switch(gt) {\n");
285 for (int i = 0; i < byteCodes.length; i++) {
287 stackMapIterator.advanceTo(i);
289 if (lastStackFrame != stackMapIterator.getFrameIndex()) {
290 lastStackFrame = stackMapIterator.getFrameIndex();
291 lmapper.syncWithFrameLocals(stackMapIterator.getFrameLocals());
292 smapper.syncWithFrameStack(stackMapIterator.getFrameStack());
293 out.append(" case " + i).append(": ");
295 out.append(" /* " + i).append(" */ ");
300 final int c = readByte(byteCodes, i);
303 emit(out, "@1 = @2;", smapper.pushA(), lmapper.getA(0));
306 emit(out, "@1 = @2;", smapper.pushI(), lmapper.getI(0));
309 emit(out, "@1 = @2;", smapper.pushL(), lmapper.getL(0));
312 emit(out, "@1 = @2;", smapper.pushF(), lmapper.getF(0));
315 emit(out, "@1 = @2;", smapper.pushD(), lmapper.getD(0));
318 emit(out, "@1 = @2;", smapper.pushA(), lmapper.getA(1));
321 emit(out, "@1 = @2;", smapper.pushI(), lmapper.getI(1));
324 emit(out, "@1 = @2;", smapper.pushL(), lmapper.getL(1));
327 emit(out, "@1 = @2;", smapper.pushF(), lmapper.getF(1));
330 emit(out, "@1 = @2;", smapper.pushD(), lmapper.getD(1));
333 emit(out, "@1 = @2;", smapper.pushA(), lmapper.getA(2));
336 emit(out, "@1 = @2;", smapper.pushI(), lmapper.getI(2));
339 emit(out, "@1 = @2;", smapper.pushL(), lmapper.getL(2));
342 emit(out, "@1 = @2;", smapper.pushF(), lmapper.getF(2));
345 emit(out, "@1 = @2;", smapper.pushD(), lmapper.getD(2));
348 emit(out, "@1 = @2;", smapper.pushA(), lmapper.getA(3));
351 emit(out, "@1 = @2;", smapper.pushI(), lmapper.getI(3));
354 emit(out, "@1 = @2;", smapper.pushL(), lmapper.getL(3));
357 emit(out, "@1 = @2;", smapper.pushF(), lmapper.getF(3));
360 emit(out, "@1 = @2;", smapper.pushD(), lmapper.getD(3));
363 final int indx = readByte(byteCodes, ++i);
364 emit(out, "@1 = @2;", smapper.pushI(), lmapper.getI(indx));
368 final int indx = readByte(byteCodes, ++i);
369 emit(out, "@1 = @2;", smapper.pushL(), lmapper.getL(indx));
373 final int indx = readByte(byteCodes, ++i);
374 emit(out, "@1 = @2;", smapper.pushF(), lmapper.getF(indx));
378 final int indx = readByte(byteCodes, ++i);
379 emit(out, "@1 = @2;", smapper.pushD(), lmapper.getD(indx));
383 final int indx = readByte(byteCodes, ++i);
384 emit(out, "@1 = @2;", smapper.pushA(), lmapper.getA(indx));
388 final int indx = readByte(byteCodes, ++i);
389 emit(out, "@1 = @2;", lmapper.setI(indx), smapper.popI());
393 final int indx = readByte(byteCodes, ++i);
394 emit(out, "@1 = @2;", lmapper.setL(indx), smapper.popL());
398 final int indx = readByte(byteCodes, ++i);
399 emit(out, "@1 = @2;", lmapper.setF(indx), smapper.popF());
403 final int indx = readByte(byteCodes, ++i);
404 emit(out, "@1 = @2;", lmapper.setD(indx), smapper.popD());
408 final int indx = readByte(byteCodes, ++i);
409 emit(out, "@1 = @2;", lmapper.setA(indx), smapper.popA());
413 emit(out, "@1 = @2;", lmapper.setA(0), smapper.popA());
416 emit(out, "@1 = @2;", lmapper.setI(0), smapper.popI());
419 emit(out, "@1 = @2;", lmapper.setL(0), smapper.popL());
422 emit(out, "@1 = @2;", lmapper.setF(0), smapper.popF());
425 emit(out, "@1 = @2;", lmapper.setD(0), smapper.popD());
428 emit(out, "@1 = @2;", lmapper.setA(1), smapper.popA());
431 emit(out, "@1 = @2;", lmapper.setI(1), smapper.popI());
434 emit(out, "@1 = @2;", lmapper.setL(1), smapper.popL());
437 emit(out, "@1 = @2;", lmapper.setF(1), smapper.popF());
440 emit(out, "@1 = @2;", lmapper.setD(1), smapper.popD());
443 emit(out, "@1 = @2;", lmapper.setA(2), smapper.popA());
446 emit(out, "@1 = @2;", lmapper.setI(2), smapper.popI());
449 emit(out, "@1 = @2;", lmapper.setL(2), smapper.popL());
452 emit(out, "@1 = @2;", lmapper.setF(2), smapper.popF());
455 emit(out, "@1 = @2;", lmapper.setD(2), smapper.popD());
458 emit(out, "@1 = @2;", lmapper.setA(3), smapper.popA());
461 emit(out, "@1 = @2;", lmapper.setI(3), smapper.popI());
464 emit(out, "@1 = @2;", lmapper.setL(3), smapper.popL());
467 emit(out, "@1 = @2;", lmapper.setF(3), smapper.popF());
470 emit(out, "@1 = @2;", lmapper.setD(3), smapper.popD());
473 emit(out, "@1 += @2;", smapper.getI(1), smapper.popI());
476 emit(out, "@1 += @2;", smapper.getL(1), smapper.popL());
479 emit(out, "@1 += @2;", smapper.getF(1), smapper.popF());
482 emit(out, "@1 += @2;", smapper.getD(1), smapper.popD());
485 emit(out, "@1 -= @2;", smapper.getI(1), smapper.popI());
488 emit(out, "@1 -= @2;", smapper.getL(1), smapper.popL());
491 emit(out, "@1 -= @2;", smapper.getF(1), smapper.popF());
494 emit(out, "@1 -= @2;", smapper.getD(1), smapper.popD());
497 emit(out, "@1 *= @2;", smapper.getI(1), smapper.popI());
500 emit(out, "@1 *= @2;", smapper.getL(1), smapper.popL());
503 emit(out, "@1 *= @2;", smapper.getF(1), smapper.popF());
506 emit(out, "@1 *= @2;", smapper.getD(1), smapper.popD());
509 emit(out, "@1 = Math.floor(@1 / @2);",
510 smapper.getI(1), smapper.popI());
513 emit(out, "@1 = Math.floor(@1 / @2);",
514 smapper.getL(1), smapper.popL());
517 emit(out, "@1 /= @2;", smapper.getF(1), smapper.popF());
520 emit(out, "@1 /= @2;", smapper.getD(1), smapper.popD());
523 emit(out, "@1 %= @2;", smapper.getI(1), smapper.popI());
526 emit(out, "@1 %= @2;", smapper.getL(1), smapper.popL());
529 emit(out, "@1 %= @2;", smapper.getF(1), smapper.popF());
532 emit(out, "@1 %= @2;", smapper.getD(1), smapper.popD());
535 emit(out, "@1 &= @2;", smapper.getI(1), smapper.popI());
538 emit(out, "@1 &= @2;", smapper.getL(1), smapper.popL());
541 emit(out, "@1 |= @2;", smapper.getI(1), smapper.popI());
544 emit(out, "@1 |= @2;", smapper.getL(1), smapper.popL());
547 emit(out, "@1 ^= @2;", smapper.getI(1), smapper.popI());
550 emit(out, "@1 ^= @2;", smapper.getL(1), smapper.popL());
553 emit(out, "@1 = -@1;", smapper.getI(0));
556 emit(out, "@1 = -@1;", smapper.getL(0));
559 emit(out, "@1 = -@1;", smapper.getF(0));
562 emit(out, "@1 = -@1;", smapper.getD(0));
565 emit(out, "@1 <<= @2;", smapper.getI(1), smapper.popI());
568 emit(out, "@1 <<= @2;", smapper.getL(1), smapper.popI());
571 emit(out, "@1 >>= @2;", smapper.getI(1), smapper.popI());
574 emit(out, "@1 >>= @2;", smapper.getL(1), smapper.popI());
577 emit(out, "@1 >>>= @2;", smapper.getI(1), smapper.popI());
580 emit(out, "@1 >>>= @2;", smapper.getL(1), smapper.popI());
583 final int varIndx = readByte(byteCodes, ++i);
584 final int incrBy = byteCodes[++i];
586 emit(out, "@1++;", lmapper.getI(varIndx));
588 emit(out, "@1 += @2;",
589 lmapper.getI(varIndx),
590 Integer.toString(incrBy));
595 emit(out, "return;");
598 emit(out, "return @1;", smapper.popI());
601 emit(out, "return @1;", smapper.popL());
604 emit(out, "return @1;", smapper.popF());
607 emit(out, "return @1;", smapper.popD());
610 emit(out, "return @1;", smapper.popA());
613 emit(out, "@2 = @1;", smapper.popI(), smapper.pushL());
616 emit(out, "@2 = @1;", smapper.popI(), smapper.pushF());
619 emit(out, "@2 = @1;", smapper.popI(), smapper.pushD());
622 emit(out, "@2 = @1;", smapper.popL(), smapper.pushI());
626 emit(out, "@2 = @1;", smapper.popL(), smapper.pushF());
629 emit(out, "@2 = @1;", smapper.popL(), smapper.pushD());
632 emit(out, "@2 = @1;", smapper.popF(), smapper.pushD());
635 emit(out, "@2 = @1;", smapper.popD(), smapper.pushF());
638 emit(out, "@2 = Math.floor(@1);",
639 smapper.popF(), smapper.pushI());
642 emit(out, "@2 = Math.floor(@1);",
643 smapper.popF(), smapper.pushL());
646 emit(out, "@2 = Math.floor(@1);",
647 smapper.popD(), smapper.pushI());
650 emit(out, "@2 = Math.floor(@1);",
651 smapper.popD(), smapper.pushL());
656 out.append("{ /* number conversion */ }");
658 case opc_aconst_null:
659 emit(out, "@1 = null;", smapper.pushA());
662 emit(out, "@1 = -1;", smapper.pushI());
665 emit(out, "@1 = 0;", smapper.pushI());
668 emit(out, "@1 = 0;", smapper.pushD());
671 emit(out, "@1 = 0;", smapper.pushL());
674 emit(out, "@1 = 0;", smapper.pushF());
677 emit(out, "@1 = 1;", smapper.pushI());
680 emit(out, "@1 = 1;", smapper.pushL());
683 emit(out, "@1 = 1;", smapper.pushF());
686 emit(out, "@1 = 1;", smapper.pushD());
689 emit(out, "@1 = 2;", smapper.pushI());
692 emit(out, "@1 = 2;", smapper.pushF());
695 emit(out, "@1 = 3;", smapper.pushI());
698 emit(out, "@1 = 4;", smapper.pushI());
701 emit(out, "@1 = 5;", smapper.pushI());
704 int indx = readByte(byteCodes, ++i);
705 String v = encodeConstant(indx);
706 int type = VarType.fromConstantType(jc.getTag(indx));
707 emit(out, "@1 = @2;", smapper.pushT(type), v);
712 int indx = readIntArg(byteCodes, i);
714 String v = encodeConstant(indx);
715 int type = VarType.fromConstantType(jc.getTag(indx));
716 emit(out, "@1 = @2;", smapper.pushT(type), v);
720 emit(out, "@3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
721 smapper.popL(), smapper.popL(), smapper.pushI());
725 emit(out, "@3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
726 smapper.popF(), smapper.popF(), smapper.pushI());
730 emit(out, "@3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
731 smapper.popD(), smapper.popD(), smapper.pushI());
734 i = generateIf(byteCodes, i, smapper.popA(), smapper.popA(),
738 i = generateIf(byteCodes, i, smapper.popA(), smapper.popA(),
742 i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
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));
767 int indx = i + readIntArg(byteCodes, i);
768 emit(out, "if (@1 <= 0) { gt = @2; continue; }",
769 smapper.popI(), Integer.toString(indx));
774 int indx = i + readIntArg(byteCodes, i);
775 emit(out, "if (@1 > 0) { gt = @2; continue; }",
776 smapper.popI(), Integer.toString(indx));
781 int indx = i + readIntArg(byteCodes, i);
782 emit(out, "if (@1 >= 0) { gt = @2; continue; }",
783 smapper.popI(), Integer.toString(indx));
787 case opc_ifnonnull: {
788 int indx = i + readIntArg(byteCodes, i);
789 emit(out, "if (@1 !== null) { gt = @2; continue; }",
790 smapper.popA(), Integer.toString(indx));
795 int indx = i + readIntArg(byteCodes, i);
796 emit(out, "if (@1 === null) { gt = @2; continue; }",
797 smapper.popA(), Integer.toString(indx));
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 i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
818 i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
822 int indx = i + readIntArg(byteCodes, i);
823 emit(out, "gt = @1; continue;", Integer.toString(indx));
827 case opc_lookupswitch: {
828 int table = i / 4 * 4 + 4;
829 int dflt = i + readInt4(byteCodes, table);
831 int n = readInt4(byteCodes, table);
833 out.append("switch (").append(smapper.popI()).append(") {\n");
835 int cnstnt = readInt4(byteCodes, table);
837 int offset = i + readInt4(byteCodes, table);
839 out.append(" case " + cnstnt).append(": gt = " + offset).append("; continue;\n");
841 out.append(" default: gt = " + dflt).append("; continue;\n}");
845 case opc_tableswitch: {
846 int table = i / 4 * 4 + 4;
847 int dflt = i + readInt4(byteCodes, table);
849 int low = readInt4(byteCodes, table);
851 int high = readInt4(byteCodes, table);
853 out.append("switch (").append(smapper.popI()).append(") {\n");
854 while (low <= high) {
855 int offset = i + readInt4(byteCodes, table);
857 out.append(" case " + low).append(": gt = " + offset).append("; continue;\n");
860 out.append(" default: gt = " + dflt).append("; continue;\n}");
864 case opc_invokeinterface: {
865 i = invokeVirtualMethod(byteCodes, i, smapper) + 2;
868 case opc_invokevirtual:
869 i = invokeVirtualMethod(byteCodes, i, smapper);
871 case opc_invokespecial:
872 i = invokeStaticMethod(byteCodes, i, smapper, false);
874 case opc_invokestatic:
875 i = invokeStaticMethod(byteCodes, i, smapper, true);
878 int indx = readIntArg(byteCodes, i);
879 String ci = jc.getClassName(indx);
880 emit(out, "@1 = new @2;",
881 smapper.pushA(), accessClass(ci.replace('/', '_')));
887 ++i; // skip type of array
888 emit(out, "@2 = new Array(@1).fillNulls();",
889 smapper.popI(), smapper.pushA());
892 i += 2; // skip type of array
893 emit(out, "@2 = new Array(@1).fillNulls();",
894 smapper.popI(), smapper.pushA());
896 case opc_multianewarray: {
898 int dim = readByte(byteCodes, ++i);
899 out.append("{ var a0 = new Array(").append(smapper.popI())
900 .append(").fillNulls();");
901 for (int d = 1; d < dim; d++) {
902 out.append("\n var l" + d).append(" = ")
903 .append(smapper.popI()).append(';');
904 out.append("\n for (var i" + d).append (" = 0; i" + d).
905 append(" < a" + (d - 1)).
906 append(".length; i" + d).append("++) {");
907 out.append("\n var a" + d).
908 append (" = new Array(l" + d).append(").fillNulls();");
909 out.append("\n a" + (d - 1)).append("[i" + d).append("] = a" + d).
912 for (int d = 1; d < dim; d++) {
915 out.append("\n").append(smapper.pushA()).append(" = a0; }");
918 case opc_arraylength:
919 emit(out, "@2 = @1.length;", smapper.popA(), smapper.pushI());
922 emit(out, "@3[@2] = @1;",
923 smapper.popL(), smapper.popI(), smapper.popA());
926 emit(out, "@3[@2] = @1;",
927 smapper.popF(), smapper.popI(), smapper.popA());
930 emit(out, "@3[@2] = @1;",
931 smapper.popD(), smapper.popI(), smapper.popA());
934 emit(out, "@3[@2] = @1;",
935 smapper.popA(), smapper.popI(), smapper.popA());
941 emit(out, "@3[@2] = @1;",
942 smapper.popI(), smapper.popI(), smapper.popA());
945 emit(out, "@3 = @2[@1];",
946 smapper.popI(), smapper.popA(), smapper.pushL());
949 emit(out, "@3 = @2[@1];",
950 smapper.popI(), smapper.popA(), smapper.pushF());
953 emit(out, "@3 = @2[@1];",
954 smapper.popI(), smapper.popA(), smapper.pushD());
957 emit(out, "@3 = @2[@1];",
958 smapper.popI(), smapper.popA(), smapper.pushA());
964 emit(out, "@3 = @2[@1];",
965 smapper.popI(), smapper.popA(), smapper.pushI());
970 out.append("/* pop */");
973 final Variable v = smapper.get(0);
974 emit(out, "@1 = @2;", smapper.pushT(v.getType()), v);
978 if (smapper.get(0).isCategory2()) {
979 final Variable v = smapper.get(0);
980 emit(out, "@1 = @2;", smapper.pushT(v.getType()), v);
982 final Variable v1 = smapper.get(0);
983 final Variable v2 = smapper.get(1);
984 emit(out, "{ @1 = @2; @3 = @4; }",
985 smapper.pushT(v2.getType()), v2,
986 smapper.pushT(v1.getType()), v1);
991 final Variable vi1 = smapper.pop();
992 final Variable vi2 = smapper.pop();
993 final Variable vo3 = smapper.pushT(vi1.getType());
994 final Variable vo2 = smapper.pushT(vi2.getType());
995 final Variable vo1 = smapper.pushT(vi1.getType());
997 emit(out, "{ @1 = @2; @3 = @4; @5 = @6; }",
998 vo1, vi1, vo2, vi2, vo3, vo1);
1002 if (smapper.get(1).isCategory2()) {
1003 final Variable vi1 = smapper.pop();
1004 final Variable vi2 = smapper.pop();
1005 final Variable vo3 = smapper.pushT(vi1.getType());
1006 final Variable vo2 = smapper.pushT(vi2.getType());
1007 final Variable vo1 = smapper.pushT(vi1.getType());
1009 emit(out, "{ @1 = @2; @3 = @4; @5 = @6; }",
1010 vo1, vi1, vo2, vi2, vo3, vo1);
1012 final Variable vi1 = smapper.pop();
1013 final Variable vi2 = smapper.pop();
1014 final Variable vi3 = smapper.pop();
1015 final Variable vo4 = smapper.pushT(vi1.getType());
1016 final Variable vo3 = smapper.pushT(vi3.getType());
1017 final Variable vo2 = smapper.pushT(vi2.getType());
1018 final Variable vo1 = smapper.pushT(vi1.getType());
1020 emit(out, "{ @1 = @2; @3 = @4; @5 = @6; @7 = @8; }",
1021 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1026 emit(out, "@1 = @2;",
1027 smapper.pushI(), Integer.toString(byteCodes[++i]));
1030 emit(out, "@1 = @2;",
1032 Integer.toString(readIntArg(byteCodes, i)));
1035 case opc_getfield: {
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, "@2 = @1.fld_@3;",
1040 smapper.popA(), smapper.pushT(type), fi[1]);
1044 case opc_getstatic: {
1045 int indx = readIntArg(byteCodes, i);
1046 String[] fi = jc.getFieldInfoName(indx);
1047 final int type = VarType.fromFieldType(fi[2].charAt(0));
1048 emit(out, "@1 = @2(false).constructor.@3;",
1049 smapper.pushT(type),
1050 accessClass(fi[0].replace('/', '_')), fi[1]);
1052 addReference(fi[0]);
1055 case opc_putfield: {
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, "@2.fld_@3 = @1;",
1060 smapper.popT(type), smapper.popA(), fi[1]);
1064 case opc_putstatic: {
1065 int indx = readIntArg(byteCodes, i);
1066 String[] fi = jc.getFieldInfoName(indx);
1067 final int type = VarType.fromFieldType(fi[2].charAt(0));
1068 emit(out, "@1(false).constructor.@2 = @3;",
1069 accessClass(fi[0].replace('/', '_')), fi[1],
1070 smapper.popT(type));
1072 addReference(fi[0]);
1075 case opc_checkcast: {
1076 int indx = readIntArg(byteCodes, i);
1077 final String type = jc.getClassName(indx);
1078 if (!type.startsWith("[")) {
1079 // no way to check arrays right now
1080 // XXX proper exception
1082 "if (@1 !== null && !@1.$instOf_@2) throw {};",
1083 smapper.getA(0), type.replace('/', '_'));
1088 case opc_instanceof: {
1089 int indx = readIntArg(byteCodes, i);
1090 final String type = jc.getClassName(indx);
1091 emit(out, "@2 = @1.$instOf_@3 ? 1 : 0;",
1092 smapper.popA(), smapper.pushI(),
1093 type.replace('/', '_'));
1098 final Variable v = smapper.popA();
1101 emit(out, "{ @1 = @2; throw @2; }",
1102 smapper.pushA(), v);
1106 case opc_monitorenter: {
1107 out.append("/* monitor enter */");
1112 case opc_monitorexit: {
1113 out.append("/* monitor exit */");
1119 emit(out, "throw 'unknown bytecode @1';",
1120 Integer.toString(c));
1123 if (trap.useTry()) {
1124 out.append("} catch (e) {");
1125 for (TrapData e : trap.current()) {
1129 if (e.catch_cpx != 0) { //not finally
1130 final String classInternalName = jc.getClassName(e.catch_cpx);
1131 addReference(classInternalName);
1132 out.append("if (e.$instOf_"+classInternalName.replace('/', '_')+") {");
1133 out.append("gt="+e.handler_pc+"; stA0 = e; continue;");
1139 out.append("throw e;");
1143 for (int j = prev; j <= i; j++) {
1145 final int cc = readByte(byteCodes, j);
1146 out.append(Integer.toString(cc));
1154 private int generateIf(byte[] byteCodes, int i,
1155 final Variable v2, final Variable v1,
1156 final String test) throws IOException {
1157 int indx = i + readIntArg(byteCodes, i);
1158 out.append("if (").append(v1)
1159 .append(' ').append(test).append(' ')
1160 .append(v2).append(") { gt = " + indx)
1161 .append("; continue; }");
1165 private int readIntArg(byte[] byteCodes, int offsetInstruction) {
1166 final int indxHi = byteCodes[offsetInstruction + 1] << 8;
1167 final int indxLo = byteCodes[offsetInstruction + 2];
1168 return (indxHi & 0xffffff00) | (indxLo & 0xff);
1170 private int readInt4(byte[] byteCodes, int offsetInstruction) {
1171 final int d = byteCodes[offsetInstruction + 0] << 24;
1172 final int c = byteCodes[offsetInstruction + 1] << 16;
1173 final int b = byteCodes[offsetInstruction + 2] << 8;
1174 final int a = byteCodes[offsetInstruction + 3];
1175 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
1177 private int readByte(byte[] byteCodes, int offsetInstruction) {
1178 return byteCodes[offsetInstruction] & 0xff;
1181 private static void countArgs(String descriptor, char[] returnType, StringBuilder sig, StringBuilder cnt) {
1183 Boolean count = null;
1184 boolean array = false;
1186 int firstPos = sig.length();
1187 while (i < descriptor.length()) {
1188 char ch = descriptor.charAt(i++);
1209 if (ch == 'J' || ch == 'D') {
1215 sig.insert(firstPos, ch);
1217 returnType[0] = '[';
1218 sig.insert(firstPos, "_3");
1227 returnType[0] = 'V';
1228 sig.insert(firstPos, 'V');
1231 int next = descriptor.indexOf(';', i);
1232 String realSig = mangleSig(descriptor, i - 1, next + 1);
1237 sig.append(realSig);
1240 sig.insert(firstPos, realSig);
1242 sig.insert(firstPos, "_3");
1244 returnType[0] = 'L';
1252 throw new IllegalStateException("Invalid char: " + ch);
1257 private static String mangleSig(String txt, int first, int last) {
1258 StringBuilder sb = new StringBuilder();
1259 for (int i = first; i < last; i++) {
1260 final char ch = txt.charAt(i);
1262 case '/': sb.append('_'); break;
1263 case '_': sb.append("_1"); break;
1264 case ';': sb.append("_2"); break;
1265 case '[': sb.append("_3"); break;
1266 default: sb.append(ch); break;
1269 return sb.toString();
1272 private static String findMethodName(MethodData m, StringBuilder cnt) {
1273 StringBuilder name = new StringBuilder();
1274 if ("<init>".equals(m.getName())) { // NOI18N
1275 name.append("cons"); // NOI18N
1276 } else if ("<clinit>".equals(m.getName())) { // NOI18N
1277 name.append("class"); // NOI18N
1279 name.append(m.getName());
1282 countArgs(m.getInternalSig(), new char[1], name, cnt);
1283 return name.toString();
1286 static String findMethodName(String[] mi, StringBuilder cnt, char[] returnType) {
1287 StringBuilder name = new StringBuilder();
1288 String descr = mi[2];//mi.getDescriptor();
1290 if ("<init>".equals(nm)) { // NOI18N
1291 name.append("cons"); // NOI18N
1295 countArgs(descr, returnType, name, cnt);
1296 return name.toString();
1299 private int invokeStaticMethod(byte[] byteCodes, int i, final StackMapper mapper, boolean isStatic)
1300 throws IOException {
1301 int methodIndex = readIntArg(byteCodes, i);
1302 String[] mi = jc.getFieldInfoName(methodIndex);
1303 char[] returnType = { 'V' };
1304 StringBuilder cnt = new StringBuilder();
1305 String mn = findMethodName(mi, cnt, returnType);
1307 final int numArguments = isStatic ? cnt.length() : cnt.length() + 1;
1308 final Variable[] vars = new Variable[numArguments];
1310 for (int j = numArguments - 1; j >= 0; --j) {
1311 vars[j] = mapper.pop();
1314 if (returnType[0] != 'V') {
1315 out.append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1319 final String in = mi[0];
1320 out.append(accessClass(in.replace('/', '_')));
1321 out.append("(false).");
1322 if (mn.startsWith("cons_")) {
1323 out.append("constructor.");
1327 if (numArguments > 0) {
1328 out.append(vars[0]);
1329 for (int j = 1; j < numArguments; ++j) {
1331 out.append(vars[j]);
1339 private int invokeVirtualMethod(byte[] byteCodes, int i, final StackMapper mapper)
1340 throws IOException {
1341 int methodIndex = readIntArg(byteCodes, i);
1342 String[] mi = jc.getFieldInfoName(methodIndex);
1343 char[] returnType = { 'V' };
1344 StringBuilder cnt = new StringBuilder();
1345 String mn = findMethodName(mi, cnt, returnType);
1347 final int numArguments = cnt.length() + 1;
1348 final Variable[] vars = new Variable[numArguments];
1350 for (int j = numArguments - 1; j >= 0; --j) {
1351 vars[j] = mapper.pop();
1354 if (returnType[0] != 'V') {
1355 out.append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1359 out.append(vars[0]).append('.');
1362 out.append(vars[0]);
1363 for (int j = 1; j < numArguments; ++j) {
1365 out.append(vars[j]);
1372 private void addReference(String cn) throws IOException {
1373 if (requireReference(cn)) {
1374 out.append(" /* needs ").append(cn).append(" */");
1378 private void outType(String d, StringBuilder out) {
1380 while (d.charAt(0) == '[') {
1384 if (d.charAt(0) == 'L') {
1385 assert d.charAt(d.length() - 1) == ';';
1386 out.append(d.replace('/', '_').substring(0, d.length() - 1));
1392 private String encodeConstant(int entryIndex) throws IOException {
1393 String[] classRef = { null };
1394 String s = jc.stringValue(entryIndex, classRef);
1395 if (classRef[0] != null) {
1396 addReference(classRef[0]);
1397 s = accessClass(s.replace('/', '_')) + "(false).constructor.$class";
1402 private String javaScriptBody(String prefix, MethodData m, boolean isStatic) throws IOException {
1403 byte[] arr = m.findAnnotationData(true);
1407 final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
1408 class P extends AnnotationParser {
1414 String[] args = new String[30];
1418 protected void visitAttr(String type, String attr, String at, String value) {
1419 if (type.equals(jvmType)) {
1420 if ("body".equals(attr)) {
1422 } else if ("args".equals(attr)) {
1423 args[cnt++] = value;
1425 throw new IllegalArgumentException(attr);
1432 if (p.body == null) {
1435 StringBuilder cnt = new StringBuilder();
1436 final String mn = findMethodName(m, cnt);
1437 out.append(prefix).append(mn);
1438 out.append(" = function(");
1442 space = outputArg(out, p.args, 0);
1448 for (int i = 0; i < cnt.length(); i++) {
1450 space = outputArg(out, p.args, index);
1453 out.append(") {").append("\n");
1455 out.append("\n}\n");
1458 private static String className(ClassData jc) {
1459 //return jc.getName().getInternalName().replace('/', '_');
1460 return jc.getClassName().replace('/', '_');
1463 private static String[] findAnnotation(
1464 byte[] arr, ClassData cd, final String className,
1465 final String... attrNames
1466 ) throws IOException {
1470 final String[] values = new String[attrNames.length];
1471 final boolean[] found = { false };
1472 final String jvmType = "L" + className.replace('.', '/') + ";";
1473 AnnotationParser ap = new AnnotationParser(false) {
1475 protected void visitAttr(String type, String attr, String at, String value) {
1476 if (type.equals(jvmType)) {
1478 for (int i = 0; i < attrNames.length; i++) {
1479 if (attrNames[i].equals(attr)) {
1488 return found[0] ? values : null;
1491 private CharSequence initField(FieldData v) {
1492 final String is = v.getInternalSig();
1493 if (is.length() == 1) {
1494 switch (is.charAt(0)) {
1500 case 'I': return " = 0;";
1502 case 'D': return " = 0.0;";
1504 throw new IllegalStateException(is);
1510 private static void generateAnno(ClassData cd, final Appendable out, byte[] data) throws IOException {
1511 AnnotationParser ap = new AnnotationParser(true) {
1516 protected void visitAnnotationStart(String type) throws IOException {
1520 out.append('"').append(type).append("\" : {\n");
1525 protected void visitAnnotationEnd(String type) throws IOException {
1526 out.append("\n}\n");
1530 protected void visitAttr(String type, String attr, String attrType, String value)
1531 throws IOException {
1538 out.append(attr).append("__").append(attrType).append(" : ").append(value);
1544 private static String outputArg(Appendable out, String[] args, int indx) throws IOException {
1545 final String name = args[indx];
1549 if (name.contains(",")) {
1550 throw new IOException("Wrong parameter with ',': " + name);
1556 private static void emit(final Appendable out,
1557 final String format,
1558 final CharSequence... params) throws IOException {
1559 final int length = format.length();
1562 int paramOffset = format.indexOf('@');
1563 while ((paramOffset != -1) && (paramOffset < (length - 1))) {
1564 final char paramChar = format.charAt(paramOffset + 1);
1565 if ((paramChar >= '1') && (paramChar <= '9')) {
1566 final int paramIndex = paramChar - '0' - 1;
1568 out.append(format, processed, paramOffset);
1569 out.append(params[paramIndex]);
1572 processed = paramOffset + 1;
1575 paramOffset = format.indexOf('@', paramOffset + 1);
1578 out.append(format, processed, length);