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 public 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 + " = ";
65 * Converts a given class file to a JavaScript version.
67 * @param classFile input stream with code of the .class file
68 * @return the initialization code for this class, if any. Otherwise <code>null</code>
70 * @throws IOException if something goes wrong during read or write or translating
73 public String compile(InputStream classFile) throws IOException {
74 this.jc = new ClassData(classFile);
75 byte[] arrData = jc.findAnnotationData(true);
76 String[] arr = findAnnotation(arrData, jc,
77 "org.apidesign.bck2brwsr.core.ExtraJavaScript",
78 "resource", "processByteCode"
81 requireScript(arr[0]);
82 if ("0".equals(arr[1])) {
86 String[] proto = findAnnotation(arrData, jc,
87 "org.apidesign.bck2brwsr.core.JavaScriptPrototype",
88 "container", "prototype"
90 StringArray toInitilize = new StringArray();
91 final String className = className(jc);
92 out.append("\n\n").append(assignClass(className));
93 out.append("function CLS() {");
94 out.append("\n if (!CLS.prototype.$instOf_").append(className).append(") {");
95 for (FieldData v : jc.getFields()) {
97 out.append("\n CLS.").append(v.getName()).append(initField(v));
101 String sc = jc.getSuperClassName(); // with _
102 out.append("\n var pp = ").
103 append(sc.replace('/', '_')).append("(true);");
104 out.append("\n var p = CLS.prototype = pp;");
105 out.append("\n var c = p;");
106 out.append("\n var sprcls = pp.constructor.$class;");
108 out.append("\n var p = CLS.prototype = ").append(proto[1]).append(";");
109 out.append("\n var c = ").append(proto[0]).append(";");
110 out.append("\n var sprcls = null;");
112 for (MethodData m : jc.getMethods()) {
113 byte[] onlyArr = m.findAnnotationData(true);
114 String[] only = findAnnotation(onlyArr, jc,
115 "org.apidesign.bck2brwsr.core.JavaScriptOnly",
119 if (only[0] != null && only[1] != null) {
120 out.append("\n p.").append(only[0]).append(" = ")
121 .append(only[1]).append(";");
127 mn = generateStaticMethod("\n c.", m, toInitilize);
129 mn = generateInstanceMethod("\n c.", m);
131 byte[] runAnno = m.findAnnotationData(false);
132 if (runAnno != null) {
133 out.append("\n c.").append(mn).append(".anno = {");
134 generateAnno(jc, out, runAnno);
138 out.append("\n c.constructor = CLS;");
139 out.append("\n c.$instOf_").append(className).append(" = true;");
140 for (String superInterface : jc.getSuperInterfaces()) {
141 out.append("\n c.$instOf_").append(superInterface.replace('/', '_')).append(" = true;");
143 out.append("\n CLS.$class = java_lang_Class(true);");
144 out.append("\n CLS.$class.jvmName = '").append(jc.getClassName()).append("';");
145 out.append("\n CLS.$class.superclass = sprcls;");
146 out.append("\n CLS.$class.cnstr = CLS;");
147 byte[] classAnno = jc.findAnnotationData(false);
148 if (classAnno != null) {
149 out.append("\n CLS.$class.anno = {");
150 generateAnno(jc, out, classAnno);
154 out.append("\n if (arguments.length === 0) {");
155 out.append("\n if (!(this instanceof CLS)) {");
156 out.append("\n return new CLS();");
158 for (FieldData v : jc.getFields()) {
159 byte[] onlyArr = v.findAnnotationData(true);
160 String[] only = findAnnotation(onlyArr, jc,
161 "org.apidesign.bck2brwsr.core.JavaScriptOnly",
165 if (only[0] != null && only[1] != null) {
166 out.append("\n p.").append(only[0]).append(" = ")
167 .append(only[1]).append(";");
172 out.append("\n this.fld_").
173 append(v.getName()).append(initField(v));
176 out.append("\n return this;");
178 out.append("\n return arguments[0] ? new CLS() : CLS.prototype;");
180 StringBuilder sb = new StringBuilder();
181 for (String init : toInitilize.toArray()) {
182 sb.append("\n").append(init).append("();");
184 return sb.toString();
186 private String generateStaticMethod(String prefix, MethodData m, StringArray toInitilize) throws IOException {
187 String jsb = javaScriptBody(prefix, m, true);
191 StringBuilder argsCnt = new StringBuilder();
192 final String mn = findMethodName(m, argsCnt);
193 out.append(prefix).append(mn).append(" = function");
194 if (mn.equals("class__V")) {
195 toInitilize.add(className(jc) + "(false)." + mn);
199 for (int index = 0, i = 0; i < argsCnt.length(); i++) {
201 out.append("arg").append(String.valueOf(index));
203 final String desc = null;// XXX findDescriptor(args.get(i).getDescriptor());
204 if (argsCnt.charAt(i) == '1') {
210 out.append(") {").append("\n");
211 if (m.getCode() != null) {
212 int len = m.getMaxLocals();
213 for (int i = argsCnt.length(); i < len; i++) {
215 out.append("arg").append(String.valueOf(i)).append(";\n");
219 out.append(" throw 'no code found for ").append(m.getInternalSig()).append("';\n");
225 private String generateInstanceMethod(String prefix, MethodData m) throws IOException {
226 String jsb = javaScriptBody(prefix, m, false);
230 StringBuilder argsCnt = new StringBuilder();
231 final String mn = findMethodName(m, argsCnt);
232 out.append(prefix).append(mn).append(" = function");
235 for (int index = 1, i = 0; i < argsCnt.length(); i++) {
237 out.append("arg").append(String.valueOf(index));
238 if (argsCnt.charAt(i) == '1') {
244 out.append(") {").append("\n");
245 if (m.getCode() != null) {
246 int len = m.getMaxLocals();
247 for (int i = argsCnt.length(); i < len; i++) {
249 out.append("arg").append(String.valueOf(i + 1)).append(";\n");
253 out.append(" throw 'no code found for ").append(m.getInternalSig()).append("';\n");
259 private void produceCode(MethodData m) throws IOException {
260 final byte[] byteCodes = m.getCode();
261 final StackMapIterator stackMapIterator = m.createStackMapIterator();
262 final StackToVariableMapper mapper = new StackToVariableMapper();
264 // maxStack includes two stack positions for every pushed long / double
265 // so this might generate more stack variables than we need
266 final int maxStack = m.getMaxStack();
268 // TODO: generate only used stack variables
269 for (int j = 0; j <= Variable.LAST_TYPE; ++j) {
270 out.append("\n var ").append(Variable.getStackVariable(j, 0));
271 for (int i = 1; i < maxStack; ++i) {
273 out.append(Variable.getStackVariable(j, i));
279 int lastStackFrame = -1;
281 out.append("\n var gt = 0;\n for(;;) switch(gt) {\n");
282 for (int i = 0; i < byteCodes.length; i++) {
284 stackMapIterator.advanceTo(i);
285 if (lastStackFrame != stackMapIterator.getFrameIndex()) {
286 lastStackFrame = stackMapIterator.getFrameIndex();
287 mapper.syncWithFrameStack(stackMapIterator.getFrameStack());
288 out.append(" case " + i).append(": ");
290 out.append(" /* " + i).append(" */ ");
292 final int c = readByte(byteCodes, i);
295 emit(out, "@1 = arg0;", mapper.pushA());
298 emit(out, "@1 = arg0;", mapper.pushI());
301 emit(out, "@1 = arg0;", mapper.pushL());
304 emit(out, "@1 = arg0;", mapper.pushF());
307 emit(out, "@1 = arg0;", mapper.pushD());
310 emit(out, "@1 = arg1;", mapper.pushA());
313 emit(out, "@1 = arg1;", mapper.pushI());
316 emit(out, "@1 = arg1;", mapper.pushL());
319 emit(out, "@1 = arg1;", mapper.pushF());
322 emit(out, "@1 = arg1;", mapper.pushD());
325 emit(out, "@1 = arg2;", mapper.pushA());
328 emit(out, "@1 = arg2;", mapper.pushI());
331 emit(out, "@1 = arg2;", mapper.pushL());
334 emit(out, "@1 = arg2;", mapper.pushF());
337 emit(out, "@1 = arg2;", mapper.pushD());
340 emit(out, "@1 = arg3;", mapper.pushA());
343 emit(out, "@1 = arg3;", mapper.pushI());
346 emit(out, "@1 = arg3;", mapper.pushL());
349 emit(out, "@1 = arg3;", mapper.pushF());
352 emit(out, "@1 = arg3;", mapper.pushD());
355 final int indx = readByte(byteCodes, ++i);
356 emit(out, "@1 = arg@2;",
357 mapper.pushI(), Integer.toString(indx));
361 final int indx = readByte(byteCodes, ++i);
362 emit(out, "@1 = arg@2;",
363 mapper.pushL(), Integer.toString(indx));
367 final int indx = readByte(byteCodes, ++i);
368 emit(out, "@1 = arg@2;",
369 mapper.pushF(), Integer.toString(indx));
373 final int indx = readByte(byteCodes, ++i);
374 emit(out, "@1 = arg@2;",
375 mapper.pushD(), Integer.toString(indx));
379 final int indx = readByte(byteCodes, ++i);
380 emit(out, "@1 = arg@2;",
381 mapper.pushA(), Integer.toString(indx));
385 final int indx = readByte(byteCodes, ++i);
386 emit(out, "arg@1 = @2;",
387 Integer.toString(indx), mapper.popI());
391 final int indx = readByte(byteCodes, ++i);
392 emit(out, "arg@1 = @2;",
393 Integer.toString(indx), mapper.popL());
397 final int indx = readByte(byteCodes, ++i);
398 emit(out, "arg@1 = @2;",
399 Integer.toString(indx), mapper.popF());
403 final int indx = readByte(byteCodes, ++i);
404 emit(out, "arg@1 = @2;",
405 Integer.toString(indx), mapper.popD());
409 final int indx = readByte(byteCodes, ++i);
410 emit(out, "arg@1 = @2;",
411 Integer.toString(indx), mapper.popA());
415 emit(out, "arg0 = @1;", mapper.popA());
418 emit(out, "arg0 = @1;", mapper.popI());
421 emit(out, "arg0 = @1;", mapper.popL());
424 emit(out, "arg0 = @1;", mapper.popF());
427 emit(out, "arg0 = @1;", mapper.popD());
430 emit(out, "arg1 = @1;", mapper.popA());
433 emit(out, "arg1 = @1;", mapper.popI());
436 emit(out, "arg1 = @1;", mapper.popL());
439 emit(out, "arg1 = @1;", mapper.popF());
442 emit(out, "arg1 = @1;", mapper.popD());
445 emit(out, "arg2 = @1;", mapper.popA());
448 emit(out, "arg2 = @1;", mapper.popI());
451 emit(out, "arg2 = @1;", mapper.popL());
454 emit(out, "arg2 = @1;", mapper.popF());
457 emit(out, "arg2 = @1;", mapper.popD());
460 emit(out, "arg3 = @1;", mapper.popA());
463 emit(out, "arg3 = @1;", mapper.popI());
466 emit(out, "arg3 = @1;", mapper.popL());
469 emit(out, "arg3 = @1;", mapper.popF());
472 emit(out, "arg3 = @1;", mapper.popD());
475 emit(out, "@1 += @2;", mapper.getI(1), mapper.popI());
478 emit(out, "@1 += @2;", mapper.getL(1), mapper.popL());
481 emit(out, "@1 += @2;", mapper.getF(1), mapper.popF());
484 emit(out, "@1 += @2;", mapper.getD(1), mapper.popD());
487 emit(out, "@1 -= @2;", mapper.getI(1), mapper.popI());
490 emit(out, "@1 -= @2;", mapper.getL(1), mapper.popL());
493 emit(out, "@1 -= @2;", mapper.getF(1), mapper.popF());
496 emit(out, "@1 -= @2;", mapper.getD(1), mapper.popD());
499 emit(out, "@1 *= @2;", mapper.getI(1), mapper.popI());
502 emit(out, "@1 *= @2;", mapper.getL(1), mapper.popL());
505 emit(out, "@1 *= @2;", mapper.getF(1), mapper.popF());
508 emit(out, "@1 *= @2;", mapper.getD(1), mapper.popD());
511 emit(out, "@1 = Math.floor(@1 / @2);",
512 mapper.getI(1), mapper.popI());
515 emit(out, "@1 = Math.floor(@1 / @2);",
516 mapper.getL(1), mapper.popL());
519 emit(out, "@1 /= @2;", mapper.getF(1), mapper.popF());
522 emit(out, "@1 /= @2;", mapper.getD(1), mapper.popD());
525 emit(out, "@1 %= @2;", mapper.getI(1), mapper.popI());
528 emit(out, "@1 %= @2;", mapper.getL(1), mapper.popL());
531 emit(out, "@1 %= @2;", mapper.getF(1), mapper.popF());
534 emit(out, "@1 %= @2;", mapper.getD(1), mapper.popD());
537 emit(out, "@1 &= @2;", mapper.getI(1), mapper.popI());
540 emit(out, "@1 &= @2;", mapper.getL(1), mapper.popL());
543 emit(out, "@1 |= @2;", mapper.getI(1), mapper.popI());
546 emit(out, "@1 |= @2;", mapper.getL(1), mapper.popL());
549 emit(out, "@1 ^= @2;", mapper.getI(1), mapper.popI());
552 emit(out, "@1 ^= @2;", mapper.getL(1), mapper.popL());
555 emit(out, "@1 = -@1;", mapper.getI(0));
558 emit(out, "@1 = -@1;", mapper.getL(0));
561 emit(out, "@1 = -@1;", mapper.getF(0));
564 emit(out, "@1 = -@1;", mapper.getD(0));
567 emit(out, "@1 <<= @2;", mapper.getI(1), mapper.popI());
570 emit(out, "@1 <<= @2;", mapper.getL(1), mapper.popI());
573 emit(out, "@1 >>= @2;", mapper.getI(1), mapper.popI());
576 emit(out, "@1 >>= @2;", mapper.getL(1), mapper.popI());
579 emit(out, "@1 >>>= @2;", mapper.getI(1), mapper.popI());
582 emit(out, "@1 >>>= @2;", mapper.getL(1), mapper.popI());
585 final int varIndx = readByte(byteCodes, ++i);
586 final int incrBy = byteCodes[++i];
588 emit(out, "arg@1++;", Integer.toString(varIndx));
590 emit(out, "arg@1 += @2;",
591 Integer.toString(varIndx),
592 Integer.toString(incrBy));
597 emit(out, "return;");
600 emit(out, "return @1;", mapper.popI());
603 emit(out, "return @1;", mapper.popL());
606 emit(out, "return @1;", mapper.popF());
609 emit(out, "return @1;", mapper.popD());
612 emit(out, "return @1;", mapper.popA());
615 emit(out, "@2 = @1;", mapper.popI(), mapper.pushL());
618 emit(out, "@2 = @1;", mapper.popI(), mapper.pushF());
621 emit(out, "@2 = @1;", mapper.popI(), mapper.pushD());
624 emit(out, "@2 = @1;", mapper.popL(), mapper.pushI());
628 emit(out, "@2 = @1;", mapper.popL(), mapper.pushF());
631 emit(out, "@2 = @1;", mapper.popL(), mapper.pushD());
634 emit(out, "@2 = @1;", mapper.popF(), mapper.pushD());
637 emit(out, "@2 = @1;", mapper.popD(), mapper.pushF());
640 emit(out, "@2 = Math.floor(@1);",
641 mapper.popF(), mapper.pushI());
644 emit(out, "@2 = Math.floor(@1);",
645 mapper.popF(), mapper.pushL());
648 emit(out, "@2 = Math.floor(@1);",
649 mapper.popD(), mapper.pushI());
652 emit(out, "@2 = Math.floor(@1);",
653 mapper.popD(), mapper.pushL());
658 out.append("/* number conversion */");
660 case opc_aconst_null:
661 emit(out, "@1 = null;", mapper.pushA());
664 emit(out, "@1 = -1;", mapper.pushI());
667 emit(out, "@1 = 0;", mapper.pushI());
670 emit(out, "@1 = 0;", mapper.pushD());
673 emit(out, "@1 = 0;", mapper.pushL());
676 emit(out, "@1 = 0;", mapper.pushF());
679 emit(out, "@1 = 1;", mapper.pushI());
682 emit(out, "@1 = 1;", mapper.pushL());
685 emit(out, "@1 = 1;", mapper.pushF());
688 emit(out, "@1 = 1;", mapper.pushD());
691 emit(out, "@1 = 2;", mapper.pushI());
694 emit(out, "@1 = 2;", mapper.pushF());
697 emit(out, "@1 = 3;", mapper.pushI());
700 emit(out, "@1 = 4;", mapper.pushI());
703 emit(out, "@1 = 5;", mapper.pushI());
706 int indx = readByte(byteCodes, ++i);
707 String v = encodeConstant(indx);
708 int type = constantToVariableType(jc.getTag(indx));
709 emit(out, "@1 = @2;", mapper.pushT(type), v);
714 int indx = readIntArg(byteCodes, i);
716 String v = encodeConstant(indx);
717 int type = constantToVariableType(jc.getTag(indx));
718 emit(out, "@1 = @2;", mapper.pushT(type), v);
722 emit(out, "@3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
723 mapper.popL(), mapper.popL(), mapper.pushI());
727 emit(out, "@3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
728 mapper.popF(), mapper.popF(), mapper.pushI());
732 emit(out, "@3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
733 mapper.popD(), mapper.popD(), mapper.pushI());
736 i = generateIf(byteCodes, i, mapper.popA(), mapper.popA(),
740 i = generateIf(byteCodes, i, mapper.popA(), mapper.popA(),
744 i = generateIf(byteCodes, i, mapper.popI(), mapper.popI(),
748 int indx = i + readIntArg(byteCodes, i);
749 emit(out, "if (@1 == 0) { gt = @2; continue; }",
750 mapper.popI(), Integer.toString(indx));
755 int indx = i + readIntArg(byteCodes, i);
756 emit(out, "if (@1 != 0) { gt = @2; continue; }",
757 mapper.popI(), Integer.toString(indx));
762 int indx = i + readIntArg(byteCodes, i);
763 emit(out, "if (@1 < 0) { gt = @2; continue; }",
764 mapper.popI(), Integer.toString(indx));
769 int indx = i + readIntArg(byteCodes, i);
770 emit(out, "if (@1 <= 0) { gt = @2; continue; }",
771 mapper.popI(), Integer.toString(indx));
776 int indx = i + readIntArg(byteCodes, i);
777 emit(out, "if (@1 > 0) { gt = @2; continue; }",
778 mapper.popI(), Integer.toString(indx));
783 int indx = i + readIntArg(byteCodes, i);
784 emit(out, "if (@1 >= 0) { gt = @2; continue; }",
785 mapper.popI(), Integer.toString(indx));
789 case opc_ifnonnull: {
790 int indx = i + readIntArg(byteCodes, i);
791 emit(out, "if (@1 !== null) { gt = @2; continue; }",
792 mapper.popA(), Integer.toString(indx));
797 int indx = i + readIntArg(byteCodes, i);
798 emit(out, "if (@1 === null) { gt = @2; continue; }",
799 mapper.popA(), Integer.toString(indx));
804 i = generateIf(byteCodes, i, mapper.popI(), mapper.popI(),
808 i = generateIf(byteCodes, i, mapper.popI(), mapper.popI(),
812 i = generateIf(byteCodes, i, mapper.popI(), mapper.popI(),
816 i = generateIf(byteCodes, i, mapper.popI(), mapper.popI(),
820 i = generateIf(byteCodes, i, mapper.popI(), mapper.popI(),
824 int indx = i + readIntArg(byteCodes, i);
825 emit(out, "gt = @1; continue;", Integer.toString(indx));
829 case opc_lookupswitch: {
830 int table = i / 4 * 4 + 4;
831 int dflt = i + readInt4(byteCodes, table);
833 int n = readInt4(byteCodes, table);
835 out.append("switch (").append(mapper.popI()).append(") {\n");
837 int cnstnt = readInt4(byteCodes, table);
839 int offset = i + readInt4(byteCodes, table);
841 out.append(" case " + cnstnt).append(": gt = " + offset).append("; continue;\n");
843 out.append(" default: gt = " + dflt).append("; continue;\n}");
847 case opc_tableswitch: {
848 int table = i / 4 * 4 + 4;
849 int dflt = i + readInt4(byteCodes, table);
851 int low = readInt4(byteCodes, table);
853 int high = readInt4(byteCodes, table);
855 out.append("switch (").append(mapper.popI()).append(") {\n");
856 while (low <= high) {
857 int offset = i + readInt4(byteCodes, table);
859 out.append(" case " + low).append(": gt = " + offset).append("; continue;\n");
862 out.append(" default: gt = " + dflt).append("; continue;\n}");
866 case opc_invokeinterface: {
867 i = invokeVirtualMethod(byteCodes, i, mapper) + 2;
870 case opc_invokevirtual:
871 i = invokeVirtualMethod(byteCodes, i, mapper);
873 case opc_invokespecial:
874 i = invokeStaticMethod(byteCodes, i, mapper, false);
876 case opc_invokestatic:
877 i = invokeStaticMethod(byteCodes, i, mapper, true);
880 int indx = readIntArg(byteCodes, i);
881 String ci = jc.getClassName(indx);
882 emit(out, "@1 = new @2;",
883 mapper.pushA(), ci.replace('/', '_'));
889 ++i; // skip type of array
890 emit(out, "@2 = new Array(@1).fillNulls();",
891 mapper.popI(), mapper.pushA());
894 i += 2; // skip type of array
895 emit(out, "@2 = new Array(@1).fillNulls();",
896 mapper.popI(), mapper.pushA());
898 case opc_multianewarray: {
900 int dim = readByte(byteCodes, ++i);
901 out.append("{ var a0 = new Array(").append(mapper.popI())
902 .append(").fillNulls();");
903 for (int d = 1; d < dim; d++) {
904 out.append("\n var l" + d).append(" = ")
905 .append(mapper.popI()).append(';');
906 out.append("\n for (var i" + d).append (" = 0; i" + d).
907 append(" < a" + (d - 1)).
908 append(".length; i" + d).append("++) {");
909 out.append("\n var a" + d).
910 append (" = new Array(l" + d).append(").fillNulls();");
911 out.append("\n a" + (d - 1)).append("[i" + d).append("] = a" + d).
914 for (int d = 1; d < dim; d++) {
917 out.append("\n").append(mapper.pushA()).append(" = a0; }");
920 case opc_arraylength:
921 emit(out, "@2 = @1.length;", mapper.popA(), mapper.pushI());
924 emit(out, "@3[@2] = @1;",
925 mapper.popL(), mapper.popI(), mapper.popA());
928 emit(out, "@3[@2] = @1;",
929 mapper.popF(), mapper.popI(), mapper.popA());
932 emit(out, "@3[@2] = @1;",
933 mapper.popD(), mapper.popI(), mapper.popA());
936 emit(out, "@3[@2] = @1;",
937 mapper.popA(), mapper.popI(), mapper.popA());
943 emit(out, "@3[@2] = @1;",
944 mapper.popI(), mapper.popI(), mapper.popA());
947 emit(out, "@3 = @2[@1];",
948 mapper.popI(), mapper.popA(), mapper.pushL());
951 emit(out, "@3 = @2[@1];",
952 mapper.popI(), mapper.popA(), mapper.pushF());
955 emit(out, "@3 = @2[@1];",
956 mapper.popI(), mapper.popA(), mapper.pushD());
959 emit(out, "@3 = @2[@1];",
960 mapper.popI(), mapper.popA(), mapper.pushA());
966 emit(out, "@3 = @2[@1];",
967 mapper.popI(), mapper.popA(), mapper.pushI());
972 out.append("/* pop */");
975 final Variable v = mapper.get(0);
976 emit(out, "@1 = @2;", mapper.pushT(v.getType()), v);
980 if (mapper.get(0).isCategory2()) {
981 final Variable v = mapper.get(0);
982 emit(out, "@1 = @2;", mapper.pushT(v.getType()), v);
984 final Variable v1 = mapper.get(0);
985 final Variable v2 = mapper.get(1);
986 emit(out, "{ @1 = @2; @3 = @4; }",
987 mapper.pushT(v2.getType()), v2,
988 mapper.pushT(v1.getType()), v1);
993 final Variable vi1 = mapper.pop();
994 final Variable vi2 = mapper.pop();
995 final Variable vo3 = mapper.pushT(vi1.getType());
996 final Variable vo2 = mapper.pushT(vi2.getType());
997 final Variable vo1 = mapper.pushT(vi1.getType());
999 emit(out, "{ @1 = @2; @3 = @4; @5 = @6; }",
1000 vo1, vi1, vo2, vi2, vo3, vo1);
1004 if (mapper.get(1).isCategory2()) {
1005 final Variable vi1 = mapper.pop();
1006 final Variable vi2 = mapper.pop();
1007 final Variable vo3 = mapper.pushT(vi1.getType());
1008 final Variable vo2 = mapper.pushT(vi2.getType());
1009 final Variable vo1 = mapper.pushT(vi1.getType());
1011 emit(out, "{ @1 = @2; @3 = @4; @5 = @6; }",
1012 vo1, vi1, vo2, vi2, vo3, vo1);
1014 final Variable vi1 = mapper.pop();
1015 final Variable vi2 = mapper.pop();
1016 final Variable vi3 = mapper.pop();
1017 final Variable vo4 = mapper.pushT(vi1.getType());
1018 final Variable vo3 = mapper.pushT(vi3.getType());
1019 final Variable vo2 = mapper.pushT(vi2.getType());
1020 final Variable vo1 = mapper.pushT(vi1.getType());
1022 emit(out, "{ @1 = @2; @3 = @4; @5 = @6; @7 = @8; }",
1023 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1028 emit(out, "@1 = @2;",
1029 mapper.pushI(), Integer.toString(byteCodes[++i]));
1032 emit(out, "@1 = @2;",
1034 Integer.toString(readIntArg(byteCodes, i)));
1037 case opc_getfield: {
1038 int indx = readIntArg(byteCodes, i);
1039 String[] fi = jc.getFieldInfoName(indx);
1040 final int type = fieldToVariableType(fi[2].charAt(0));
1041 emit(out, "@2 = @1.fld_@3;",
1042 mapper.popA(), mapper.pushT(type), fi[1]);
1046 case opc_getstatic: {
1047 int indx = readIntArg(byteCodes, i);
1048 String[] fi = jc.getFieldInfoName(indx);
1049 final int type = fieldToVariableType(fi[2].charAt(0));
1050 emit(out, "@1 = @2.@3;",
1051 mapper.pushT(type), fi[0].replace('/', '_'), fi[1]);
1053 addReference(fi[0]);
1056 case opc_putfield: {
1057 int indx = readIntArg(byteCodes, i);
1058 String[] fi = jc.getFieldInfoName(indx);
1059 final int type = fieldToVariableType(fi[2].charAt(0));
1060 emit(out, "@2.fld_@3 = @1;",
1061 mapper.popT(type), mapper.popA(), fi[1]);
1065 case opc_putstatic: {
1066 int indx = readIntArg(byteCodes, i);
1067 String[] fi = jc.getFieldInfoName(indx);
1068 final int type = fieldToVariableType(fi[2].charAt(0));
1069 emit(out, "@1.@2 = @3;",
1070 fi[0].replace('/', '_'), fi[1], mapper.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
1081 emit(out, "if (@1.$instOf_@2 != 1) throw {};",
1082 mapper.getA(0), type.replace('/', '_'));
1087 case opc_instanceof: {
1088 int indx = readIntArg(byteCodes, i);
1089 final String type = jc.getClassName(indx);
1090 emit(out, "@2 = @1.$instOf_@3 ? 1 : 0;",
1091 mapper.popA(), mapper.pushI(), type.replace('/', '_'));
1096 final Variable v = mapper.popA();
1099 emit(out, "{ @1 = @2; throw @2; }",
1104 case opc_monitorenter: {
1105 out.append("/* monitor enter */");
1110 case opc_monitorexit: {
1111 out.append("/* monitor exit */");
1117 emit(out, "throw 'unknown bytecode @1';",
1118 Integer.toString(c));
1122 for (int j = prev; j <= i; j++) {
1124 final int cc = readByte(byteCodes, j);
1125 out.append(Integer.toString(cc));
1132 private int generateIf(byte[] byteCodes, int i,
1133 final Variable v2, final Variable v1,
1134 final String test) throws IOException {
1135 int indx = i + readIntArg(byteCodes, i);
1136 out.append("if (").append(v1)
1137 .append(' ').append(test).append(' ')
1138 .append(v2).append(") { gt = " + indx)
1139 .append("; continue; }");
1143 private int readIntArg(byte[] byteCodes, int offsetInstruction) {
1144 final int indxHi = byteCodes[offsetInstruction + 1] << 8;
1145 final int indxLo = byteCodes[offsetInstruction + 2];
1146 return (indxHi & 0xffffff00) | (indxLo & 0xff);
1148 private int readInt4(byte[] byteCodes, int offsetInstruction) {
1149 final int d = byteCodes[offsetInstruction + 0] << 24;
1150 final int c = byteCodes[offsetInstruction + 1] << 16;
1151 final int b = byteCodes[offsetInstruction + 2] << 8;
1152 final int a = byteCodes[offsetInstruction + 3];
1153 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
1155 private int readByte(byte[] byteCodes, int offsetInstruction) {
1156 return byteCodes[offsetInstruction] & 0xff;
1159 private static void countArgs(String descriptor, char[] returnType, StringBuilder sig, StringBuilder cnt) {
1161 Boolean count = null;
1162 boolean array = false;
1164 int firstPos = sig.length();
1165 while (i < descriptor.length()) {
1166 char ch = descriptor.charAt(i++);
1187 if (ch == 'J' || ch == 'D') {
1193 sig.insert(firstPos, ch);
1195 returnType[0] = '[';
1196 sig.insert(firstPos, "_3");
1205 returnType[0] = 'V';
1206 sig.insert(firstPos, 'V');
1209 int next = descriptor.indexOf(';', i);
1210 String realSig = mangleSig(descriptor, i - 1, next + 1);
1215 sig.append(realSig);
1218 sig.insert(firstPos, realSig);
1220 sig.insert(firstPos, "_3");
1222 returnType[0] = 'L';
1230 throw new IllegalStateException("Invalid char: " + ch);
1235 private static String mangleSig(String txt, int first, int last) {
1236 StringBuilder sb = new StringBuilder();
1237 for (int i = first; i < last; i++) {
1238 final char ch = txt.charAt(i);
1240 case '/': sb.append('_'); break;
1241 case '_': sb.append("_1"); break;
1242 case ';': sb.append("_2"); break;
1243 case '[': sb.append("_3"); break;
1244 default: sb.append(ch); break;
1247 return sb.toString();
1250 private static String findMethodName(MethodData m, StringBuilder cnt) {
1251 StringBuilder name = new StringBuilder();
1252 if ("<init>".equals(m.getName())) { // NOI18N
1253 name.append("cons"); // NOI18N
1254 } else if ("<clinit>".equals(m.getName())) { // NOI18N
1255 name.append("class"); // NOI18N
1257 name.append(m.getName());
1260 countArgs(m.getInternalSig(), new char[1], name, cnt);
1261 return name.toString();
1264 static String findMethodName(String[] mi, StringBuilder cnt, char[] returnType) {
1265 StringBuilder name = new StringBuilder();
1266 String descr = mi[2];//mi.getDescriptor();
1268 if ("<init>".equals(nm)) { // NOI18N
1269 name.append("cons"); // NOI18N
1273 countArgs(descr, returnType, name, cnt);
1274 return name.toString();
1277 private int invokeStaticMethod(byte[] byteCodes, int i, final StackToVariableMapper mapper, boolean isStatic)
1278 throws IOException {
1279 int methodIndex = readIntArg(byteCodes, i);
1280 String[] mi = jc.getFieldInfoName(methodIndex);
1281 char[] returnType = { 'V' };
1282 StringBuilder cnt = new StringBuilder();
1283 String mn = findMethodName(mi, cnt, returnType);
1285 final int numArguments = isStatic ? cnt.length() : cnt.length() + 1;
1286 final Variable[] vars = new Variable[numArguments];
1288 for (int j = numArguments - 1; j >= 0; --j) {
1289 vars[j] = mapper.pop();
1292 if (returnType[0] != 'V') {
1293 out.append(mapper.pushT(fieldToVariableType(returnType[0])))
1297 final String in = mi[0];
1298 out.append(in.replace('/', '_'));
1299 out.append("(false).");
1302 if (numArguments > 0) {
1303 out.append(vars[0]);
1304 for (int j = 1; j < numArguments; ++j) {
1306 out.append(vars[j]);
1314 private int invokeVirtualMethod(byte[] byteCodes, int i, final StackToVariableMapper mapper)
1315 throws IOException {
1316 int methodIndex = readIntArg(byteCodes, i);
1317 String[] mi = jc.getFieldInfoName(methodIndex);
1318 char[] returnType = { 'V' };
1319 StringBuilder cnt = new StringBuilder();
1320 String mn = findMethodName(mi, cnt, returnType);
1322 final int numArguments = cnt.length() + 1;
1323 final Variable[] vars = new Variable[numArguments];
1325 for (int j = numArguments - 1; j >= 0; --j) {
1326 vars[j] = mapper.pop();
1329 if (returnType[0] != 'V') {
1330 out.append(mapper.pushT(fieldToVariableType(returnType[0])))
1334 out.append(vars[0]).append('.');
1337 out.append(vars[0]);
1338 for (int j = 1; j < numArguments; ++j) {
1340 out.append(vars[j]);
1347 private void addReference(String cn) throws IOException {
1348 if (requireReference(cn)) {
1349 out.append(" /* needs ").append(cn).append(" */");
1353 private void outType(String d, StringBuilder out) {
1355 while (d.charAt(0) == '[') {
1359 if (d.charAt(0) == 'L') {
1360 assert d.charAt(d.length() - 1) == ';';
1361 out.append(d.replace('/', '_').substring(0, d.length() - 1));
1367 private String encodeConstant(int entryIndex) throws IOException {
1368 String[] classRef = { null };
1369 String s = jc.stringValue(entryIndex, classRef);
1370 if (classRef[0] != null) {
1371 addReference(classRef[0]);
1376 private String javaScriptBody(String prefix, MethodData m, boolean isStatic) throws IOException {
1377 byte[] arr = m.findAnnotationData(true);
1381 final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
1382 class P extends AnnotationParser {
1388 String[] args = new String[30];
1392 protected void visitAttr(String type, String attr, String at, String value) {
1393 if (type.equals(jvmType)) {
1394 if ("body".equals(attr)) {
1396 } else if ("args".equals(attr)) {
1397 args[cnt++] = value;
1399 throw new IllegalArgumentException(attr);
1406 if (p.body == null) {
1409 StringBuilder cnt = new StringBuilder();
1410 final String mn = findMethodName(m, cnt);
1411 out.append(prefix).append(mn);
1412 out.append(" = function(");
1416 out.append(p.args[0]);
1423 for (int i = 0; i < cnt.length(); i++) {
1425 out.append(p.args[index]);
1429 out.append(") {").append("\n");
1431 out.append("\n}\n");
1434 private static String className(ClassData jc) {
1435 //return jc.getName().getInternalName().replace('/', '_');
1436 return jc.getClassName().replace('/', '_');
1439 private static String[] findAnnotation(
1440 byte[] arr, ClassData cd, final String className,
1441 final String... attrNames
1442 ) throws IOException {
1446 final String[] values = new String[attrNames.length];
1447 final boolean[] found = { false };
1448 final String jvmType = "L" + className.replace('.', '/') + ";";
1449 AnnotationParser ap = new AnnotationParser(false) {
1451 protected void visitAttr(String type, String attr, String at, String value) {
1452 if (type.equals(jvmType)) {
1454 for (int i = 0; i < attrNames.length; i++) {
1455 if (attrNames[i].equals(attr)) {
1464 return found[0] ? values : null;
1467 private CharSequence initField(FieldData v) {
1468 final String is = v.getInternalSig();
1469 if (is.length() == 1) {
1470 switch (is.charAt(0)) {
1476 case 'I': return " = 0;";
1478 case 'D': return " = 0.0;";
1480 throw new IllegalStateException(is);
1486 private static void generateAnno(ClassData cd, final Appendable out, byte[] data) throws IOException {
1487 AnnotationParser ap = new AnnotationParser(true) {
1492 protected void visitAnnotationStart(String type) throws IOException {
1496 out.append('"').append(type).append("\" : {\n");
1501 protected void visitAnnotationEnd(String type) throws IOException {
1502 out.append("\n}\n");
1506 protected void visitAttr(String type, String attr, String attrType, String value)
1507 throws IOException {
1514 out.append(attr).append("__").append(attrType).append(" : ").append(value);
1520 private static int constantToVariableType(final byte constantTag) {
1521 switch (constantTag) {
1522 case CONSTANT_INTEGER:
1523 return Variable.TYPE_INT;
1524 case CONSTANT_FLOAT:
1525 return Variable.TYPE_FLOAT;
1527 return Variable.TYPE_LONG;
1528 case CONSTANT_DOUBLE:
1529 return Variable.TYPE_DOUBLE;
1531 case CONSTANT_CLASS:
1533 case CONSTANT_UNICODE:
1534 case CONSTANT_STRING:
1535 return Variable.TYPE_REF;
1537 case CONSTANT_FIELD:
1538 case CONSTANT_METHOD:
1539 case CONSTANT_INTERFACEMETHOD:
1540 case CONSTANT_NAMEANDTYPE:
1541 /* unclear how to handle for now */
1543 throw new IllegalStateException("Unhandled constant tag");
1547 private static int fieldToVariableType(final char fieldType) {
1548 switch (fieldType) {
1554 return Variable.TYPE_INT;
1556 return Variable.TYPE_LONG;
1558 return Variable.TYPE_FLOAT;
1560 return Variable.TYPE_DOUBLE;
1563 return Variable.TYPE_REF;
1566 throw new IllegalStateException("Unhandled field type");
1570 private static void emit(final Appendable out,
1571 final String format,
1572 final CharSequence... params) throws IOException {
1573 final int length = format.length();
1576 int paramOffset = format.indexOf('@');
1577 while ((paramOffset != -1) && (paramOffset < (length - 1))) {
1578 final char paramChar = format.charAt(paramOffset + 1);
1579 if ((paramChar >= '1') && (paramChar <= '9')) {
1580 final int paramIndex = paramChar - '0' - 1;
1582 out.append(format, processed, paramOffset);
1583 out.append(params[paramIndex]);
1586 processed = paramOffset + 1;
1589 paramOffset = format.indexOf('@', paramOffset + 1);
1592 out.append(format, processed, length);