Support for reflection on primitive types. All tests finish in the browser.
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.*;
29 /** Translator of the code inside class files to JavaScript.
31 * @author Jaroslav Tulach <jtulach@netbeans.org>
33 abstract class ByteCodeToJavaScript {
37 protected ByteCodeToJavaScript(Appendable out) {
41 /* Collects additional required resources.
43 * @param internalClassName classes that were referenced and should be loaded in order the
44 * generated JavaScript code works properly. The names are in internal
45 * JVM form so String is <code>java/lang/String</code>.
47 protected abstract boolean requireReference(String internalClassName);
50 * @param resourcePath name of resources to read
52 protected abstract void requireScript(String resourcePath);
54 /** Allows subclasses to redefine what field a function representing a
55 * class gets assigned. By default it returns the suggested name followed
56 * by <code>" = "</code>;
58 * @param className suggested name of the class
60 /* protected */ String assignClass(String className) {
61 return className + " = ";
63 /* protected */ String accessClass(String classOperation) {
64 return classOperation;
68 * Converts a given class file to a JavaScript version.
70 * @param classFile input stream with code of the .class file
71 * @return the initialization code for this class, if any. Otherwise <code>null</code>
73 * @throws IOException if something goes wrong during read or write or translating
76 public String compile(InputStream classFile) throws IOException {
77 this.jc = new ClassData(classFile);
78 if (jc.getMajor_version() < 50) {
79 throw new IOException("Can't compile " + jc.getClassName() + ". Class file version " + jc.getMajor_version() + "."
80 + jc.getMinor_version() + " - recompile with -target 1.6 (at least)."
83 byte[] arrData = jc.findAnnotationData(true);
84 String[] arr = findAnnotation(arrData, jc,
85 "org.apidesign.bck2brwsr.core.ExtraJavaScript",
86 "resource", "processByteCode"
89 requireScript(arr[0]);
90 if ("0".equals(arr[1])) {
94 String[] proto = findAnnotation(arrData, jc,
95 "org.apidesign.bck2brwsr.core.JavaScriptPrototype",
96 "container", "prototype"
98 StringArray toInitilize = new StringArray();
99 final String className = className(jc);
100 out.append("\n\n").append(assignClass(className));
101 out.append("function CLS() {");
102 out.append("\n if (!CLS.prototype.$instOf_").append(className).append(") {");
103 for (FieldData v : jc.getFields()) {
105 out.append("\n CLS.").append(v.getName()).append(initField(v));
109 String sc = jc.getSuperClassName(); // with _
110 out.append("\n var pp = ").
111 append(accessClass(sc.replace('/', '_'))).append("(true);");
112 out.append("\n var p = CLS.prototype = pp;");
113 out.append("\n var c = p;");
114 out.append("\n var sprcls = pp.constructor.$class;");
116 out.append("\n var p = CLS.prototype = ").append(proto[1]).append(";");
117 if (proto[0] == null) {
120 out.append("\n var c = ").append(proto[0]).append(";");
121 out.append("\n var sprcls = null;");
123 for (MethodData m : jc.getMethods()) {
124 byte[] onlyArr = m.findAnnotationData(true);
125 String[] only = findAnnotation(onlyArr, jc,
126 "org.apidesign.bck2brwsr.core.JavaScriptOnly",
130 if (only[0] != null && only[1] != null) {
131 out.append("\n p.").append(only[0]).append(" = ")
132 .append(only[1]).append(";");
138 mn = generateStaticMethod("\n c.", m, toInitilize);
140 mn = generateInstanceMethod("\n c.", m);
142 byte[] runAnno = m.findAnnotationData(false);
143 if (runAnno != null) {
144 out.append("\n c.").append(mn).append(".anno = {");
145 generateAnno(jc, out, runAnno);
149 out.append("\n c.constructor = CLS;");
150 out.append("\n c.$instOf_").append(className).append(" = true;");
151 for (String superInterface : jc.getSuperInterfaces()) {
152 out.append("\n c.$instOf_").append(superInterface.replace('/', '_')).append(" = true;");
154 out.append("\n CLS.$class = ");
155 out.append(accessClass("java_lang_Class(true);"));
156 out.append("\n CLS.$class.jvmName = '").append(jc.getClassName()).append("';");
157 out.append("\n CLS.$class.superclass = sprcls;");
158 out.append("\n CLS.$class.access = ").append(jc.getAccessFlags()+";");
159 out.append("\n CLS.$class.cnstr = CLS;");
160 byte[] classAnno = jc.findAnnotationData(false);
161 if (classAnno != null) {
162 out.append("\n CLS.$class.anno = {");
163 generateAnno(jc, out, classAnno);
167 out.append("\n if (arguments.length === 0) {");
168 out.append("\n if (!(this instanceof CLS)) {");
169 out.append("\n return new CLS();");
171 for (FieldData v : jc.getFields()) {
172 byte[] onlyArr = v.findAnnotationData(true);
173 String[] only = findAnnotation(onlyArr, jc,
174 "org.apidesign.bck2brwsr.core.JavaScriptOnly",
178 if (only[0] != null && only[1] != null) {
179 out.append("\n p.").append(only[0]).append(" = ")
180 .append(only[1]).append(";");
185 out.append("\n this.fld_").
186 append(v.getName()).append(initField(v));
189 out.append("\n return this;");
191 out.append("\n return arguments[0] ? new CLS() : CLS.prototype;");
193 StringBuilder sb = new StringBuilder();
194 for (String init : toInitilize.toArray()) {
195 sb.append("\n").append(init).append("();");
197 return sb.toString();
199 private String generateStaticMethod(String prefix, MethodData m, StringArray toInitilize) throws IOException {
200 String jsb = javaScriptBody(prefix, m, true);
204 final String mn = findMethodName(m, new StringBuilder());
205 if (mn.equals("class__V")) {
206 toInitilize.add(accessClass(className(jc)) + "(false)." + mn);
208 generateMethod(prefix, mn, m);
212 private String generateInstanceMethod(String prefix, MethodData m) throws IOException {
213 String jsb = javaScriptBody(prefix, m, false);
217 final String mn = findMethodName(m, new StringBuilder());
218 generateMethod(prefix, mn, m);
222 private void generateMethod(String prefix, String name, MethodData m)
224 final StackMapIterator stackMapIterator = m.createStackMapIterator();
225 final LocalsMapper lmapper =
226 new LocalsMapper(stackMapIterator.getArguments());
228 out.append(prefix).append(name).append(" = function(");
229 lmapper.outputArguments(out);
230 out.append(") {").append("\n");
232 final byte[] byteCodes = m.getCode();
233 if (byteCodes == null) {
234 out.append(" throw 'no code found for ")
235 .append(m.getInternalSig()).append("';\n");
240 final StackMapper smapper = new StackMapper();
242 final int maxLocals = m.getMaxLocals();
244 // TODO: generate only used local variables
245 for (int j = 0; j <= VarType.LAST; ++j) {
246 out.append("\n var ").append(Variable.getLocalVariable(j, 0));
247 for (int i = 1; i < maxLocals; ++i) {
249 out.append(Variable.getLocalVariable(j, i));
255 // maxStack includes two stack positions for every pushed long / double
256 // so this might generate more stack variables than we need
257 final int maxStack = m.getMaxStack();
259 // TODO: generate only used stack variables
260 for (int j = 0; j <= VarType.LAST; ++j) {
261 out.append("\n var ").append(Variable.getStackVariable(j, 0));
262 for (int i = 1; i < maxStack; ++i) {
264 out.append(Variable.getStackVariable(j, i));
270 int lastStackFrame = -1;
272 out.append("\n var gt = 0;\n for(;;) switch(gt) {\n");
273 for (int i = 0; i < byteCodes.length; i++) {
275 stackMapIterator.advanceTo(i);
276 if (lastStackFrame != stackMapIterator.getFrameIndex()) {
277 lastStackFrame = stackMapIterator.getFrameIndex();
278 lmapper.syncWithFrameLocals(stackMapIterator.getFrameLocals());
279 smapper.syncWithFrameStack(stackMapIterator.getFrameStack());
280 out.append(" case " + i).append(": ");
282 out.append(" /* " + i).append(" */ ");
284 final int c = readByte(byteCodes, i);
287 emit(out, "@1 = @2;", smapper.pushA(), lmapper.getA(0));
290 emit(out, "@1 = @2;", smapper.pushI(), lmapper.getI(0));
293 emit(out, "@1 = @2;", smapper.pushL(), lmapper.getL(0));
296 emit(out, "@1 = @2;", smapper.pushF(), lmapper.getF(0));
299 emit(out, "@1 = @2;", smapper.pushD(), lmapper.getD(0));
302 emit(out, "@1 = @2;", smapper.pushA(), lmapper.getA(1));
305 emit(out, "@1 = @2;", smapper.pushI(), lmapper.getI(1));
308 emit(out, "@1 = @2;", smapper.pushL(), lmapper.getL(1));
311 emit(out, "@1 = @2;", smapper.pushF(), lmapper.getF(1));
314 emit(out, "@1 = @2;", smapper.pushD(), lmapper.getD(1));
317 emit(out, "@1 = @2;", smapper.pushA(), lmapper.getA(2));
320 emit(out, "@1 = @2;", smapper.pushI(), lmapper.getI(2));
323 emit(out, "@1 = @2;", smapper.pushL(), lmapper.getL(2));
326 emit(out, "@1 = @2;", smapper.pushF(), lmapper.getF(2));
329 emit(out, "@1 = @2;", smapper.pushD(), lmapper.getD(2));
332 emit(out, "@1 = @2;", smapper.pushA(), lmapper.getA(3));
335 emit(out, "@1 = @2;", smapper.pushI(), lmapper.getI(3));
338 emit(out, "@1 = @2;", smapper.pushL(), lmapper.getL(3));
341 emit(out, "@1 = @2;", smapper.pushF(), lmapper.getF(3));
344 emit(out, "@1 = @2;", smapper.pushD(), lmapper.getD(3));
347 final int indx = readByte(byteCodes, ++i);
348 emit(out, "@1 = @2;", smapper.pushI(), lmapper.getI(indx));
352 final int indx = readByte(byteCodes, ++i);
353 emit(out, "@1 = @2;", smapper.pushL(), lmapper.getL(indx));
357 final int indx = readByte(byteCodes, ++i);
358 emit(out, "@1 = @2;", smapper.pushF(), lmapper.getF(indx));
362 final int indx = readByte(byteCodes, ++i);
363 emit(out, "@1 = @2;", smapper.pushD(), lmapper.getD(indx));
367 final int indx = readByte(byteCodes, ++i);
368 emit(out, "@1 = @2;", smapper.pushA(), lmapper.getA(indx));
372 final int indx = readByte(byteCodes, ++i);
373 emit(out, "@1 = @2;", lmapper.setI(indx), smapper.popI());
377 final int indx = readByte(byteCodes, ++i);
378 emit(out, "@1 = @2;", lmapper.setL(indx), smapper.popL());
382 final int indx = readByte(byteCodes, ++i);
383 emit(out, "@1 = @2;", lmapper.setF(indx), smapper.popF());
387 final int indx = readByte(byteCodes, ++i);
388 emit(out, "@1 = @2;", lmapper.setD(indx), smapper.popD());
392 final int indx = readByte(byteCodes, ++i);
393 emit(out, "@1 = @2;", lmapper.setA(indx), smapper.popA());
397 emit(out, "@1 = @2;", lmapper.setA(0), smapper.popA());
400 emit(out, "@1 = @2;", lmapper.setI(0), smapper.popI());
403 emit(out, "@1 = @2;", lmapper.setL(0), smapper.popL());
406 emit(out, "@1 = @2;", lmapper.setF(0), smapper.popF());
409 emit(out, "@1 = @2;", lmapper.setD(0), smapper.popD());
412 emit(out, "@1 = @2;", lmapper.setA(1), smapper.popA());
415 emit(out, "@1 = @2;", lmapper.setI(1), smapper.popI());
418 emit(out, "@1 = @2;", lmapper.setL(1), smapper.popL());
421 emit(out, "@1 = @2;", lmapper.setF(1), smapper.popF());
424 emit(out, "@1 = @2;", lmapper.setD(1), smapper.popD());
427 emit(out, "@1 = @2;", lmapper.setA(2), smapper.popA());
430 emit(out, "@1 = @2;", lmapper.setI(2), smapper.popI());
433 emit(out, "@1 = @2;", lmapper.setL(2), smapper.popL());
436 emit(out, "@1 = @2;", lmapper.setF(2), smapper.popF());
439 emit(out, "@1 = @2;", lmapper.setD(2), smapper.popD());
442 emit(out, "@1 = @2;", lmapper.setA(3), smapper.popA());
445 emit(out, "@1 = @2;", lmapper.setI(3), smapper.popI());
448 emit(out, "@1 = @2;", lmapper.setL(3), smapper.popL());
451 emit(out, "@1 = @2;", lmapper.setF(3), smapper.popF());
454 emit(out, "@1 = @2;", lmapper.setD(3), smapper.popD());
457 emit(out, "@1 += @2;", smapper.getI(1), smapper.popI());
460 emit(out, "@1 += @2;", smapper.getL(1), smapper.popL());
463 emit(out, "@1 += @2;", smapper.getF(1), smapper.popF());
466 emit(out, "@1 += @2;", smapper.getD(1), smapper.popD());
469 emit(out, "@1 -= @2;", smapper.getI(1), smapper.popI());
472 emit(out, "@1 -= @2;", smapper.getL(1), smapper.popL());
475 emit(out, "@1 -= @2;", smapper.getF(1), smapper.popF());
478 emit(out, "@1 -= @2;", smapper.getD(1), smapper.popD());
481 emit(out, "@1 *= @2;", smapper.getI(1), smapper.popI());
484 emit(out, "@1 *= @2;", smapper.getL(1), smapper.popL());
487 emit(out, "@1 *= @2;", smapper.getF(1), smapper.popF());
490 emit(out, "@1 *= @2;", smapper.getD(1), smapper.popD());
493 emit(out, "@1 = Math.floor(@1 / @2);",
494 smapper.getI(1), smapper.popI());
497 emit(out, "@1 = Math.floor(@1 / @2);",
498 smapper.getL(1), smapper.popL());
501 emit(out, "@1 /= @2;", smapper.getF(1), smapper.popF());
504 emit(out, "@1 /= @2;", smapper.getD(1), smapper.popD());
507 emit(out, "@1 %= @2;", smapper.getI(1), smapper.popI());
510 emit(out, "@1 %= @2;", smapper.getL(1), smapper.popL());
513 emit(out, "@1 %= @2;", smapper.getF(1), smapper.popF());
516 emit(out, "@1 %= @2;", smapper.getD(1), smapper.popD());
519 emit(out, "@1 &= @2;", smapper.getI(1), smapper.popI());
522 emit(out, "@1 &= @2;", smapper.getL(1), smapper.popL());
525 emit(out, "@1 |= @2;", smapper.getI(1), smapper.popI());
528 emit(out, "@1 |= @2;", smapper.getL(1), smapper.popL());
531 emit(out, "@1 ^= @2;", smapper.getI(1), smapper.popI());
534 emit(out, "@1 ^= @2;", smapper.getL(1), smapper.popL());
537 emit(out, "@1 = -@1;", smapper.getI(0));
540 emit(out, "@1 = -@1;", smapper.getL(0));
543 emit(out, "@1 = -@1;", smapper.getF(0));
546 emit(out, "@1 = -@1;", smapper.getD(0));
549 emit(out, "@1 <<= @2;", smapper.getI(1), smapper.popI());
552 emit(out, "@1 <<= @2;", smapper.getL(1), smapper.popI());
555 emit(out, "@1 >>= @2;", smapper.getI(1), smapper.popI());
558 emit(out, "@1 >>= @2;", smapper.getL(1), smapper.popI());
561 emit(out, "@1 >>>= @2;", smapper.getI(1), smapper.popI());
564 emit(out, "@1 >>>= @2;", smapper.getL(1), smapper.popI());
567 final int varIndx = readByte(byteCodes, ++i);
568 final int incrBy = byteCodes[++i];
570 emit(out, "@1++;", lmapper.getI(varIndx));
572 emit(out, "@1 += @2;",
573 lmapper.getI(varIndx),
574 Integer.toString(incrBy));
579 emit(out, "return;");
582 emit(out, "return @1;", smapper.popI());
585 emit(out, "return @1;", smapper.popL());
588 emit(out, "return @1;", smapper.popF());
591 emit(out, "return @1;", smapper.popD());
594 emit(out, "return @1;", smapper.popA());
597 emit(out, "@2 = @1;", smapper.popI(), smapper.pushL());
600 emit(out, "@2 = @1;", smapper.popI(), smapper.pushF());
603 emit(out, "@2 = @1;", smapper.popI(), smapper.pushD());
606 emit(out, "@2 = @1;", smapper.popL(), smapper.pushI());
610 emit(out, "@2 = @1;", smapper.popL(), smapper.pushF());
613 emit(out, "@2 = @1;", smapper.popL(), smapper.pushD());
616 emit(out, "@2 = @1;", smapper.popF(), smapper.pushD());
619 emit(out, "@2 = @1;", smapper.popD(), smapper.pushF());
622 emit(out, "@2 = Math.floor(@1);",
623 smapper.popF(), smapper.pushI());
626 emit(out, "@2 = Math.floor(@1);",
627 smapper.popF(), smapper.pushL());
630 emit(out, "@2 = Math.floor(@1);",
631 smapper.popD(), smapper.pushI());
634 emit(out, "@2 = Math.floor(@1);",
635 smapper.popD(), smapper.pushL());
640 out.append("{ /* number conversion */ }");
642 case opc_aconst_null:
643 emit(out, "@1 = null;", smapper.pushA());
646 emit(out, "@1 = -1;", smapper.pushI());
649 emit(out, "@1 = 0;", smapper.pushI());
652 emit(out, "@1 = 0;", smapper.pushD());
655 emit(out, "@1 = 0;", smapper.pushL());
658 emit(out, "@1 = 0;", smapper.pushF());
661 emit(out, "@1 = 1;", smapper.pushI());
664 emit(out, "@1 = 1;", smapper.pushL());
667 emit(out, "@1 = 1;", smapper.pushF());
670 emit(out, "@1 = 1;", smapper.pushD());
673 emit(out, "@1 = 2;", smapper.pushI());
676 emit(out, "@1 = 2;", smapper.pushF());
679 emit(out, "@1 = 3;", smapper.pushI());
682 emit(out, "@1 = 4;", smapper.pushI());
685 emit(out, "@1 = 5;", smapper.pushI());
688 int indx = readByte(byteCodes, ++i);
689 String v = encodeConstant(indx);
690 int type = VarType.fromConstantType(jc.getTag(indx));
691 emit(out, "@1 = @2;", smapper.pushT(type), v);
696 int indx = readIntArg(byteCodes, i);
698 String v = encodeConstant(indx);
699 int type = VarType.fromConstantType(jc.getTag(indx));
700 emit(out, "@1 = @2;", smapper.pushT(type), v);
704 emit(out, "@3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
705 smapper.popL(), smapper.popL(), smapper.pushI());
709 emit(out, "@3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
710 smapper.popF(), smapper.popF(), smapper.pushI());
714 emit(out, "@3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
715 smapper.popD(), smapper.popD(), smapper.pushI());
718 i = generateIf(byteCodes, i, smapper.popA(), smapper.popA(),
722 i = generateIf(byteCodes, i, smapper.popA(), smapper.popA(),
726 i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
730 int indx = i + readIntArg(byteCodes, i);
731 emit(out, "if (@1 == 0) { gt = @2; continue; }",
732 smapper.popI(), Integer.toString(indx));
737 int indx = i + readIntArg(byteCodes, i);
738 emit(out, "if (@1 != 0) { gt = @2; continue; }",
739 smapper.popI(), Integer.toString(indx));
744 int indx = i + readIntArg(byteCodes, i);
745 emit(out, "if (@1 < 0) { gt = @2; continue; }",
746 smapper.popI(), Integer.toString(indx));
751 int indx = i + readIntArg(byteCodes, i);
752 emit(out, "if (@1 <= 0) { gt = @2; continue; }",
753 smapper.popI(), Integer.toString(indx));
758 int indx = i + readIntArg(byteCodes, i);
759 emit(out, "if (@1 > 0) { gt = @2; continue; }",
760 smapper.popI(), Integer.toString(indx));
765 int indx = i + readIntArg(byteCodes, i);
766 emit(out, "if (@1 >= 0) { gt = @2; continue; }",
767 smapper.popI(), Integer.toString(indx));
771 case opc_ifnonnull: {
772 int indx = i + readIntArg(byteCodes, i);
773 emit(out, "if (@1 !== null) { gt = @2; continue; }",
774 smapper.popA(), Integer.toString(indx));
779 int indx = i + readIntArg(byteCodes, i);
780 emit(out, "if (@1 === null) { gt = @2; continue; }",
781 smapper.popA(), Integer.toString(indx));
786 i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
790 i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
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 int indx = i + readIntArg(byteCodes, i);
807 emit(out, "gt = @1; continue;", Integer.toString(indx));
811 case opc_lookupswitch: {
812 int table = i / 4 * 4 + 4;
813 int dflt = i + readInt4(byteCodes, table);
815 int n = readInt4(byteCodes, table);
817 out.append("switch (").append(smapper.popI()).append(") {\n");
819 int cnstnt = readInt4(byteCodes, table);
821 int offset = i + readInt4(byteCodes, table);
823 out.append(" case " + cnstnt).append(": gt = " + offset).append("; continue;\n");
825 out.append(" default: gt = " + dflt).append("; continue;\n}");
829 case opc_tableswitch: {
830 int table = i / 4 * 4 + 4;
831 int dflt = i + readInt4(byteCodes, table);
833 int low = readInt4(byteCodes, table);
835 int high = readInt4(byteCodes, table);
837 out.append("switch (").append(smapper.popI()).append(") {\n");
838 while (low <= high) {
839 int offset = i + readInt4(byteCodes, table);
841 out.append(" case " + low).append(": gt = " + offset).append("; continue;\n");
844 out.append(" default: gt = " + dflt).append("; continue;\n}");
848 case opc_invokeinterface: {
849 i = invokeVirtualMethod(byteCodes, i, smapper) + 2;
852 case opc_invokevirtual:
853 i = invokeVirtualMethod(byteCodes, i, smapper);
855 case opc_invokespecial:
856 i = invokeStaticMethod(byteCodes, i, smapper, false);
858 case opc_invokestatic:
859 i = invokeStaticMethod(byteCodes, i, smapper, true);
862 int indx = readIntArg(byteCodes, i);
863 String ci = jc.getClassName(indx);
864 emit(out, "@1 = new @2;",
865 smapper.pushA(), accessClass(ci.replace('/', '_')));
871 ++i; // skip type of array
872 emit(out, "@2 = new Array(@1).fillNulls();",
873 smapper.popI(), smapper.pushA());
876 i += 2; // skip type of array
877 emit(out, "@2 = new Array(@1).fillNulls();",
878 smapper.popI(), smapper.pushA());
880 case opc_multianewarray: {
882 int dim = readByte(byteCodes, ++i);
883 out.append("{ var a0 = new Array(").append(smapper.popI())
884 .append(").fillNulls();");
885 for (int d = 1; d < dim; d++) {
886 out.append("\n var l" + d).append(" = ")
887 .append(smapper.popI()).append(';');
888 out.append("\n for (var i" + d).append (" = 0; i" + d).
889 append(" < a" + (d - 1)).
890 append(".length; i" + d).append("++) {");
891 out.append("\n var a" + d).
892 append (" = new Array(l" + d).append(").fillNulls();");
893 out.append("\n a" + (d - 1)).append("[i" + d).append("] = a" + d).
896 for (int d = 1; d < dim; d++) {
899 out.append("\n").append(smapper.pushA()).append(" = a0; }");
902 case opc_arraylength:
903 emit(out, "@2 = @1.length;", smapper.popA(), smapper.pushI());
906 emit(out, "@3[@2] = @1;",
907 smapper.popL(), smapper.popI(), smapper.popA());
910 emit(out, "@3[@2] = @1;",
911 smapper.popF(), smapper.popI(), smapper.popA());
914 emit(out, "@3[@2] = @1;",
915 smapper.popD(), smapper.popI(), smapper.popA());
918 emit(out, "@3[@2] = @1;",
919 smapper.popA(), smapper.popI(), smapper.popA());
925 emit(out, "@3[@2] = @1;",
926 smapper.popI(), smapper.popI(), smapper.popA());
929 emit(out, "@3 = @2[@1];",
930 smapper.popI(), smapper.popA(), smapper.pushL());
933 emit(out, "@3 = @2[@1];",
934 smapper.popI(), smapper.popA(), smapper.pushF());
937 emit(out, "@3 = @2[@1];",
938 smapper.popI(), smapper.popA(), smapper.pushD());
941 emit(out, "@3 = @2[@1];",
942 smapper.popI(), smapper.popA(), smapper.pushA());
948 emit(out, "@3 = @2[@1];",
949 smapper.popI(), smapper.popA(), smapper.pushI());
954 out.append("/* pop */");
957 final Variable v = smapper.get(0);
958 emit(out, "@1 = @2;", smapper.pushT(v.getType()), v);
962 if (smapper.get(0).isCategory2()) {
963 final Variable v = smapper.get(0);
964 emit(out, "@1 = @2;", smapper.pushT(v.getType()), v);
966 final Variable v1 = smapper.get(0);
967 final Variable v2 = smapper.get(1);
968 emit(out, "{ @1 = @2; @3 = @4; }",
969 smapper.pushT(v2.getType()), v2,
970 smapper.pushT(v1.getType()), v1);
975 final Variable vi1 = smapper.pop();
976 final Variable vi2 = smapper.pop();
977 final Variable vo3 = smapper.pushT(vi1.getType());
978 final Variable vo2 = smapper.pushT(vi2.getType());
979 final Variable vo1 = smapper.pushT(vi1.getType());
981 emit(out, "{ @1 = @2; @3 = @4; @5 = @6; }",
982 vo1, vi1, vo2, vi2, vo3, vo1);
986 if (smapper.get(1).isCategory2()) {
987 final Variable vi1 = smapper.pop();
988 final Variable vi2 = smapper.pop();
989 final Variable vo3 = smapper.pushT(vi1.getType());
990 final Variable vo2 = smapper.pushT(vi2.getType());
991 final Variable vo1 = smapper.pushT(vi1.getType());
993 emit(out, "{ @1 = @2; @3 = @4; @5 = @6; }",
994 vo1, vi1, vo2, vi2, vo3, vo1);
996 final Variable vi1 = smapper.pop();
997 final Variable vi2 = smapper.pop();
998 final Variable vi3 = smapper.pop();
999 final Variable vo4 = smapper.pushT(vi1.getType());
1000 final Variable vo3 = smapper.pushT(vi3.getType());
1001 final Variable vo2 = smapper.pushT(vi2.getType());
1002 final Variable vo1 = smapper.pushT(vi1.getType());
1004 emit(out, "{ @1 = @2; @3 = @4; @5 = @6; @7 = @8; }",
1005 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1010 emit(out, "@1 = @2;",
1011 smapper.pushI(), Integer.toString(byteCodes[++i]));
1014 emit(out, "@1 = @2;",
1016 Integer.toString(readIntArg(byteCodes, i)));
1019 case opc_getfield: {
1020 int indx = readIntArg(byteCodes, i);
1021 String[] fi = jc.getFieldInfoName(indx);
1022 final int type = VarType.fromFieldType(fi[2].charAt(0));
1023 emit(out, "@2 = @1.fld_@3;",
1024 smapper.popA(), smapper.pushT(type), fi[1]);
1028 case opc_getstatic: {
1029 int indx = readIntArg(byteCodes, i);
1030 String[] fi = jc.getFieldInfoName(indx);
1031 final int type = VarType.fromFieldType(fi[2].charAt(0));
1032 emit(out, "@1 = @2.@3;",
1033 smapper.pushT(type),
1034 accessClass(fi[0].replace('/', '_')), fi[1]);
1036 addReference(fi[0]);
1039 case opc_putfield: {
1040 int indx = readIntArg(byteCodes, i);
1041 String[] fi = jc.getFieldInfoName(indx);
1042 final int type = VarType.fromFieldType(fi[2].charAt(0));
1043 emit(out, "@2.fld_@3 = @1;",
1044 smapper.popT(type), smapper.popA(), fi[1]);
1048 case opc_putstatic: {
1049 int indx = readIntArg(byteCodes, i);
1050 String[] fi = jc.getFieldInfoName(indx);
1051 final int type = VarType.fromFieldType(fi[2].charAt(0));
1052 emit(out, "@1.@2 = @3;",
1053 accessClass(fi[0].replace('/', '_')), fi[1],
1054 smapper.popT(type));
1056 addReference(fi[0]);
1059 case opc_checkcast: {
1060 int indx = readIntArg(byteCodes, i);
1061 final String type = jc.getClassName(indx);
1062 if (!type.startsWith("[")) {
1063 // no way to check arrays right now
1064 // XXX proper exception
1066 "if (@1 !== null && !@1.$instOf_@2) throw {};",
1067 smapper.getA(0), type.replace('/', '_'));
1072 case opc_instanceof: {
1073 int indx = readIntArg(byteCodes, i);
1074 final String type = jc.getClassName(indx);
1075 emit(out, "@2 = @1.$instOf_@3 ? 1 : 0;",
1076 smapper.popA(), smapper.pushI(),
1077 type.replace('/', '_'));
1082 final Variable v = smapper.popA();
1085 emit(out, "{ @1 = @2; throw @2; }",
1086 smapper.pushA(), v);
1090 case opc_monitorenter: {
1091 out.append("/* monitor enter */");
1096 case opc_monitorexit: {
1097 out.append("/* monitor exit */");
1103 emit(out, "throw 'unknown bytecode @1';",
1104 Integer.toString(c));
1108 for (int j = prev; j <= i; j++) {
1110 final int cc = readByte(byteCodes, j);
1111 out.append(Integer.toString(cc));
1119 private int generateIf(byte[] byteCodes, int i,
1120 final Variable v2, final Variable v1,
1121 final String test) throws IOException {
1122 int indx = i + readIntArg(byteCodes, i);
1123 out.append("if (").append(v1)
1124 .append(' ').append(test).append(' ')
1125 .append(v2).append(") { gt = " + indx)
1126 .append("; continue; }");
1130 private int readIntArg(byte[] byteCodes, int offsetInstruction) {
1131 final int indxHi = byteCodes[offsetInstruction + 1] << 8;
1132 final int indxLo = byteCodes[offsetInstruction + 2];
1133 return (indxHi & 0xffffff00) | (indxLo & 0xff);
1135 private int readInt4(byte[] byteCodes, int offsetInstruction) {
1136 final int d = byteCodes[offsetInstruction + 0] << 24;
1137 final int c = byteCodes[offsetInstruction + 1] << 16;
1138 final int b = byteCodes[offsetInstruction + 2] << 8;
1139 final int a = byteCodes[offsetInstruction + 3];
1140 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
1142 private int readByte(byte[] byteCodes, int offsetInstruction) {
1143 return byteCodes[offsetInstruction] & 0xff;
1146 private static void countArgs(String descriptor, char[] returnType, StringBuilder sig, StringBuilder cnt) {
1148 Boolean count = null;
1149 boolean array = false;
1151 int firstPos = sig.length();
1152 while (i < descriptor.length()) {
1153 char ch = descriptor.charAt(i++);
1174 if (ch == 'J' || ch == 'D') {
1180 sig.insert(firstPos, ch);
1182 returnType[0] = '[';
1183 sig.insert(firstPos, "_3");
1192 returnType[0] = 'V';
1193 sig.insert(firstPos, 'V');
1196 int next = descriptor.indexOf(';', i);
1197 String realSig = mangleSig(descriptor, i - 1, next + 1);
1202 sig.append(realSig);
1205 sig.insert(firstPos, realSig);
1207 sig.insert(firstPos, "_3");
1209 returnType[0] = 'L';
1217 throw new IllegalStateException("Invalid char: " + ch);
1222 private static String mangleSig(String txt, int first, int last) {
1223 StringBuilder sb = new StringBuilder();
1224 for (int i = first; i < last; i++) {
1225 final char ch = txt.charAt(i);
1227 case '/': sb.append('_'); break;
1228 case '_': sb.append("_1"); break;
1229 case ';': sb.append("_2"); break;
1230 case '[': sb.append("_3"); break;
1231 default: sb.append(ch); break;
1234 return sb.toString();
1237 private static String findMethodName(MethodData m, StringBuilder cnt) {
1238 StringBuilder name = new StringBuilder();
1239 if ("<init>".equals(m.getName())) { // NOI18N
1240 name.append("cons"); // NOI18N
1241 } else if ("<clinit>".equals(m.getName())) { // NOI18N
1242 name.append("class"); // NOI18N
1244 name.append(m.getName());
1247 countArgs(m.getInternalSig(), new char[1], name, cnt);
1248 return name.toString();
1251 static String findMethodName(String[] mi, StringBuilder cnt, char[] returnType) {
1252 StringBuilder name = new StringBuilder();
1253 String descr = mi[2];//mi.getDescriptor();
1255 if ("<init>".equals(nm)) { // NOI18N
1256 name.append("cons"); // NOI18N
1260 countArgs(descr, returnType, name, cnt);
1261 return name.toString();
1264 private int invokeStaticMethod(byte[] byteCodes, int i, final StackMapper mapper, boolean isStatic)
1265 throws IOException {
1266 int methodIndex = readIntArg(byteCodes, i);
1267 String[] mi = jc.getFieldInfoName(methodIndex);
1268 char[] returnType = { 'V' };
1269 StringBuilder cnt = new StringBuilder();
1270 String mn = findMethodName(mi, cnt, returnType);
1272 final int numArguments = isStatic ? cnt.length() : cnt.length() + 1;
1273 final Variable[] vars = new Variable[numArguments];
1275 for (int j = numArguments - 1; j >= 0; --j) {
1276 vars[j] = mapper.pop();
1279 if (returnType[0] != 'V') {
1280 out.append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1284 final String in = mi[0];
1285 out.append(accessClass(in.replace('/', '_')));
1286 out.append("(false).");
1289 if (numArguments > 0) {
1290 out.append(vars[0]);
1291 for (int j = 1; j < numArguments; ++j) {
1293 out.append(vars[j]);
1301 private int invokeVirtualMethod(byte[] byteCodes, int i, final StackMapper mapper)
1302 throws IOException {
1303 int methodIndex = readIntArg(byteCodes, i);
1304 String[] mi = jc.getFieldInfoName(methodIndex);
1305 char[] returnType = { 'V' };
1306 StringBuilder cnt = new StringBuilder();
1307 String mn = findMethodName(mi, cnt, returnType);
1309 final int numArguments = cnt.length() + 1;
1310 final Variable[] vars = new Variable[numArguments];
1312 for (int j = numArguments - 1; j >= 0; --j) {
1313 vars[j] = mapper.pop();
1316 if (returnType[0] != 'V') {
1317 out.append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1321 out.append(vars[0]).append('.');
1324 out.append(vars[0]);
1325 for (int j = 1; j < numArguments; ++j) {
1327 out.append(vars[j]);
1334 private void addReference(String cn) throws IOException {
1335 if (requireReference(cn)) {
1336 out.append(" /* needs ").append(cn).append(" */");
1340 private void outType(String d, StringBuilder out) {
1342 while (d.charAt(0) == '[') {
1346 if (d.charAt(0) == 'L') {
1347 assert d.charAt(d.length() - 1) == ';';
1348 out.append(d.replace('/', '_').substring(0, d.length() - 1));
1354 private String encodeConstant(int entryIndex) throws IOException {
1355 String[] classRef = { null };
1356 String s = jc.stringValue(entryIndex, classRef);
1357 if (classRef[0] != null) {
1358 addReference(classRef[0]);
1359 s = accessClass(s.replace('/', '_')) + "(false).constructor.$class";
1364 private String javaScriptBody(String prefix, MethodData m, boolean isStatic) throws IOException {
1365 byte[] arr = m.findAnnotationData(true);
1369 final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
1370 class P extends AnnotationParser {
1376 String[] args = new String[30];
1380 protected void visitAttr(String type, String attr, String at, String value) {
1381 if (type.equals(jvmType)) {
1382 if ("body".equals(attr)) {
1384 } else if ("args".equals(attr)) {
1385 args[cnt++] = value;
1387 throw new IllegalArgumentException(attr);
1394 if (p.body == null) {
1397 StringBuilder cnt = new StringBuilder();
1398 final String mn = findMethodName(m, cnt);
1399 out.append(prefix).append(mn);
1400 out.append(" = function(");
1404 space = outputArg(out, p.args, 0);
1410 for (int i = 0; i < cnt.length(); i++) {
1412 space = outputArg(out, p.args, index);
1415 out.append(") {").append("\n");
1417 out.append("\n}\n");
1420 private static String className(ClassData jc) {
1421 //return jc.getName().getInternalName().replace('/', '_');
1422 return jc.getClassName().replace('/', '_');
1425 private static String[] findAnnotation(
1426 byte[] arr, ClassData cd, final String className,
1427 final String... attrNames
1428 ) throws IOException {
1432 final String[] values = new String[attrNames.length];
1433 final boolean[] found = { false };
1434 final String jvmType = "L" + className.replace('.', '/') + ";";
1435 AnnotationParser ap = new AnnotationParser(false) {
1437 protected void visitAttr(String type, String attr, String at, String value) {
1438 if (type.equals(jvmType)) {
1440 for (int i = 0; i < attrNames.length; i++) {
1441 if (attrNames[i].equals(attr)) {
1450 return found[0] ? values : null;
1453 private CharSequence initField(FieldData v) {
1454 final String is = v.getInternalSig();
1455 if (is.length() == 1) {
1456 switch (is.charAt(0)) {
1462 case 'I': return " = 0;";
1464 case 'D': return " = 0.0;";
1466 throw new IllegalStateException(is);
1472 private static void generateAnno(ClassData cd, final Appendable out, byte[] data) throws IOException {
1473 AnnotationParser ap = new AnnotationParser(true) {
1478 protected void visitAnnotationStart(String type) throws IOException {
1482 out.append('"').append(type).append("\" : {\n");
1487 protected void visitAnnotationEnd(String type) throws IOException {
1488 out.append("\n}\n");
1492 protected void visitAttr(String type, String attr, String attrType, String value)
1493 throws IOException {
1500 out.append(attr).append("__").append(attrType).append(" : ").append(value);
1506 private static String outputArg(Appendable out, String[] args, int indx) throws IOException {
1507 final String name = args[indx];
1511 if (name.contains(",")) {
1512 throw new IOException("Wrong parameter with ',': " + name);
1518 private static void emit(final Appendable out,
1519 final String format,
1520 final CharSequence... params) throws IOException {
1521 final int length = format.length();
1524 int paramOffset = format.indexOf('@');
1525 while ((paramOffset != -1) && (paramOffset < (length - 1))) {
1526 final char paramChar = format.charAt(paramOffset + 1);
1527 if ((paramChar >= '1') && (paramChar <= '9')) {
1528 final int paramIndex = paramChar - '0' - 1;
1530 out.append(format, processed, paramOffset);
1531 out.append(params[paramIndex]);
1534 processed = paramOffset + 1;
1537 paramOffset = format.indexOf('@', paramOffset + 1);
1540 out.append(format, processed, length);