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 out.append(mapper.pushA()).append(" = arg0;");
298 out.append(mapper.pushI()).append(" = arg0;");
301 out.append(mapper.pushL()).append(" = arg0;");
304 out.append(mapper.pushF()).append(" = arg0;");
307 out.append(mapper.pushD()).append(" = arg0;");
310 out.append(mapper.pushA()).append(" = arg1;");
313 out.append(mapper.pushI()).append(" = arg1;");
316 out.append(mapper.pushL()).append(" = arg1;");
319 out.append(mapper.pushF()).append(" = arg1;");
322 out.append(mapper.pushD()).append(" = arg1;");
325 out.append(mapper.pushA()).append(" = arg2;");
328 out.append(mapper.pushI()).append(" = arg2;");
331 out.append(mapper.pushL()).append(" = arg2;");
334 out.append(mapper.pushF()).append(" = arg2;");
337 out.append(mapper.pushD()).append(" = arg2;");
340 out.append(mapper.pushA()).append(" = arg3;");
343 out.append(mapper.pushI()).append(" = arg3;");
346 out.append(mapper.pushL()).append(" = arg3;");
349 out.append(mapper.pushF()).append(" = arg3;");
352 out.append(mapper.pushD()).append(" = arg3;");
355 final int indx = readByte(byteCodes, ++i);
356 out.append(mapper.pushI()).append(" = ")
357 .append("arg").append(indx + ";");
361 final int indx = readByte(byteCodes, ++i);
362 out.append(mapper.pushL()).append(" = ")
363 .append("arg").append(indx + ";");
367 final int indx = readByte(byteCodes, ++i);
368 out.append(mapper.pushF()).append(" = ")
369 .append("arg").append(indx + ";");
373 final int indx = readByte(byteCodes, ++i);
374 out.append(mapper.pushD()).append(" = ")
375 .append("arg").append(indx + ";");
379 final int indx = readByte(byteCodes, ++i);
380 out.append(mapper.pushA()).append(" = ")
381 .append("arg").append(indx + ";");
385 final int indx = readByte(byteCodes, ++i);
386 out.append("arg" + indx).append(" = ")
387 .append(mapper.popI()).append(';');
391 final int indx = readByte(byteCodes, ++i);
392 out.append("arg" + indx).append(" = ")
393 .append(mapper.popL()).append(';');
397 final int indx = readByte(byteCodes, ++i);
398 out.append("arg" + indx).append(" = ")
399 .append(mapper.popF()).append(';');
403 final int indx = readByte(byteCodes, ++i);
404 out.append("arg" + indx).append(" = ")
405 .append(mapper.popD()).append(';');
409 final int indx = readByte(byteCodes, ++i);
410 out.append("arg" + indx).append(" = ")
411 .append(mapper.popA()).append(';');
415 out.append("arg0 = ").append(mapper.popA()).append(';');
418 out.append("arg0 = ").append(mapper.popI()).append(';');
421 out.append("arg0 = ").append(mapper.popL()).append(';');
424 out.append("arg0 = ").append(mapper.popF()).append(';');
427 out.append("arg0 = ").append(mapper.popD()).append(';');
430 out.append("arg1 = ").append(mapper.popA()).append(';');
433 out.append("arg1 = ").append(mapper.popI()).append(';');
436 out.append("arg1 = ").append(mapper.popL()).append(';');
439 out.append("arg1 = ").append(mapper.popF()).append(';');
442 out.append("arg1 = ").append(mapper.popD()).append(';');
445 out.append("arg2 = ").append(mapper.popA()).append(';');
448 out.append("arg2 = ").append(mapper.popI()).append(';');
451 out.append("arg2 = ").append(mapper.popL()).append(';');
454 out.append("arg2 = ").append(mapper.popF()).append(';');
457 out.append("arg2 = ").append(mapper.popD()).append(';');
460 out.append("arg3 = ").append(mapper.popA()).append(';');
463 out.append("arg3 = ").append(mapper.popI()).append(';');
466 out.append("arg3 = ").append(mapper.popL()).append(';');
469 out.append("arg3 = ").append(mapper.popF()).append(';');
472 out.append("arg3 = ").append(mapper.popD()).append(';');
475 out.append(mapper.getI(1)).append(" += ")
476 .append(mapper.popI()).append(';');
479 out.append(mapper.getL(1)).append(" += ")
480 .append(mapper.popL()).append(';');
483 out.append(mapper.getF(1)).append(" += ")
484 .append(mapper.popF()).append(';');
487 out.append(mapper.getD(1)).append(" += ")
488 .append(mapper.popD()).append(';');
491 out.append(mapper.getI(1)).append(" -= ")
492 .append(mapper.popI()).append(';');
495 out.append(mapper.getL(1)).append(" -= ")
496 .append(mapper.popL()).append(';');
499 out.append(mapper.getF(1)).append(" -= ")
500 .append(mapper.popF()).append(';');
503 out.append(mapper.getD(1)).append(" -= ")
504 .append(mapper.popD()).append(';');
507 out.append(mapper.getI(1)).append(" *= ")
508 .append(mapper.popI()).append(';');
511 out.append(mapper.getL(1)).append(" *= ")
512 .append(mapper.popL()).append(';');
515 out.append(mapper.getF(1)).append(" *= ")
516 .append(mapper.popF()).append(';');
519 out.append(mapper.getD(1)).append(" *= ")
520 .append(mapper.popD()).append(';');
523 out.append(mapper.getI(1)).append(" = ")
524 .append("Math.floor(").append(mapper.getI(1))
525 .append(" / ").append(mapper.popI()).append(");");
528 out.append(mapper.getL(1)).append(" = ")
529 .append("Math.floor(").append(mapper.getL(1))
530 .append(" / ").append(mapper.popL()).append(");");
533 out.append(mapper.getF(1)).append(" /= ")
534 .append(mapper.popF()).append(';');
537 out.append(mapper.getD(1)).append(" /= ")
538 .append(mapper.popD()).append(';');
541 out.append(mapper.getI(1)).append(" %= ")
542 .append(mapper.popI()).append(';');
545 out.append(mapper.getL(1)).append(" %= ")
546 .append(mapper.popL()).append(';');
549 out.append(mapper.getF(1)).append(" %= ")
550 .append(mapper.popF()).append(';');
553 out.append(mapper.getD(1)).append(" %= ")
554 .append(mapper.popD()).append(';');
557 out.append(mapper.getI(1)).append(" &= ")
558 .append(mapper.popI()).append(';');
561 out.append(mapper.getL(1)).append(" &= ")
562 .append(mapper.popL()).append(';');
565 out.append(mapper.getI(1)).append(" |= ")
566 .append(mapper.popI()).append(';');
569 out.append(mapper.getL(1)).append(" |= ")
570 .append(mapper.popL()).append(';');
573 out.append(mapper.getI(1)).append(" ^= ")
574 .append(mapper.popI()).append(';');
577 out.append(mapper.getL(1)).append(" ^= ")
578 .append(mapper.popL()).append(';');
581 out.append(mapper.getI(0)).append(" = -")
582 .append(mapper.getI(0)).append(';');
585 out.append(mapper.getL(0)).append(" = -")
586 .append(mapper.getL(0)).append(';');
589 out.append(mapper.getF(0)).append(" = -")
590 .append(mapper.getF(0)).append(';');
593 out.append(mapper.getD(0)).append(" = -")
594 .append(mapper.getD(0)).append(';');
597 out.append(mapper.getI(1)).append(" <<= ")
598 .append(mapper.popI()).append(';');
601 out.append(mapper.getL(1)).append(" <<= ")
602 .append(mapper.popI()).append(';');
605 out.append(mapper.getI(1)).append(" >>= ")
606 .append(mapper.popI()).append(';');
609 out.append(mapper.getL(1)).append(" >>= ")
610 .append(mapper.popI()).append(';');
613 out.append(mapper.getI(1)).append(" >>>= ")
614 .append(mapper.popI()).append(';');
617 out.append(mapper.getL(1)).append(" >>>= ")
618 .append(mapper.popI()).append(';');
621 final int varIndx = readByte(byteCodes, ++i);
622 final int incrBy = byteCodes[++i];
624 out.append("arg" + varIndx).append("++;");
626 out.append("arg" + varIndx).append(" += " + incrBy).append(";");
631 out.append("return;");
634 out.append("return ").append(mapper.popI()).append(';');
637 out.append("return ").append(mapper.popL()).append(';');
640 out.append("return ").append(mapper.popF()).append(';');
643 out.append("return ").append(mapper.popD()).append(';');
646 out.append("return ").append(mapper.popA()).append(';');
649 final Variable v = mapper.popI();
650 out.append(mapper.pushL()).append(" = ")
651 .append(v).append(';');
655 final Variable v = mapper.popI();
656 out.append(mapper.pushF()).append(" = ")
657 .append(v).append(';');
661 final Variable v = mapper.popI();
662 out.append(mapper.pushD()).append(" = ")
663 .append(v).append(';');
667 final Variable v = mapper.popL();
668 out.append(mapper.pushI()).append(" = ")
669 .append(v).append(';');
674 final Variable v = mapper.popL();
675 out.append(mapper.pushF()).append(" = ")
676 .append(v).append(';');
680 final Variable v = mapper.popL();
681 out.append(mapper.pushD()).append(" = ")
682 .append(v).append(';');
686 final Variable v = mapper.popF();
687 out.append(mapper.pushD()).append(" = ")
688 .append(v).append(';');
692 final Variable v = mapper.popD();
693 out.append(mapper.pushF()).append(" = ")
694 .append(v).append(';');
698 final Variable v = mapper.popF();
699 out.append(mapper.pushI()).append(" = ")
700 .append("Math.floor(").append(v).append(");");
704 final Variable v = mapper.popF();
705 out.append(mapper.pushL()).append(" = ")
706 .append("Math.floor(").append(v).append(");");
710 final Variable v = mapper.popD();
711 out.append(mapper.pushI()).append(" = ")
712 .append("Math.floor(").append(v).append(");");
716 final Variable v = mapper.popD();
717 out.append(mapper.pushL()).append(" = ")
718 .append("Math.floor(").append(v).append(");");
724 out.append("/* number conversion */");
726 case opc_aconst_null:
727 out.append(mapper.pushA()).append(" = null;");
730 out.append(mapper.pushI()).append(" = -1;");
733 out.append(mapper.pushI()).append(" = 0;");
736 out.append(mapper.pushD()).append(" = 0;");
739 out.append(mapper.pushL()).append(" = 0;");
742 out.append(mapper.pushF()).append(" = 0;");
745 out.append(mapper.pushI()).append(" = 1;");
748 out.append(mapper.pushL()).append(" = 1;");
751 out.append(mapper.pushF()).append(" = 1;");
754 out.append(mapper.pushD()).append(" = 1;");
757 out.append(mapper.pushI()).append(" = 2;");
760 out.append(mapper.pushF()).append(" = 2;");
763 out.append(mapper.pushI()).append(" = 3;");
766 out.append(mapper.pushI()).append(" = 4;");
769 out.append(mapper.pushI()).append(" = 5;");
772 int indx = readByte(byteCodes, ++i);
773 String v = encodeConstant(indx);
774 int type = constantToVariableType(jc.getTag(indx));
775 out.append(mapper.pushT(type)).append(" = ")
776 .append(v).append(';');
781 int indx = readIntArg(byteCodes, i);
783 String v = encodeConstant(indx);
784 int type = constantToVariableType(jc.getTag(indx));
785 out.append(mapper.pushT(type)).append(" = ")
786 .append(v).append(';');
790 generateCmp(mapper.popL(), mapper.popL(), mapper.pushI());
794 generateCmp(mapper.popF(), mapper.popF(), mapper.pushI());
798 generateCmp(mapper.popD(), mapper.popD(), mapper.pushI());
801 i = generateIf(byteCodes, i, mapper.popA(), mapper.popA(),
805 i = generateIf(byteCodes, i, mapper.popA(), mapper.popA(),
808 case opc_if_icmpeq: {
809 i = generateIf(byteCodes, i, mapper.popI(), mapper.popI(),
814 int indx = i + readIntArg(byteCodes, i);
815 out.append("if (").append(mapper.popI())
816 .append(" == 0) { gt = " + indx);
817 out.append("; continue; }");
822 int indx = i + readIntArg(byteCodes, i);
823 out.append("if (").append(mapper.popI())
824 .append(" != 0) { gt = " + indx);
825 out.append("; continue; }");
830 int indx = i + readIntArg(byteCodes, i);
831 out.append("if (").append(mapper.popI())
832 .append(" < 0) { gt = " + indx);
833 out.append("; continue; }");
838 int indx = i + readIntArg(byteCodes, i);
839 out.append("if (").append(mapper.popI())
840 .append(" <= 0) { gt = " + indx);
841 out.append("; continue; }");
846 int indx = i + readIntArg(byteCodes, i);
847 out.append("if (").append(mapper.popI())
848 .append(" > 0) { gt = " + indx);
849 out.append("; continue; }");
854 int indx = i + readIntArg(byteCodes, i);
855 out.append("if (").append(mapper.popI())
856 .append(" >= 0) { gt = " + indx);
857 out.append("; continue; }");
861 case opc_ifnonnull: {
862 int indx = i + readIntArg(byteCodes, i);
863 out.append("if (").append(mapper.popA())
864 .append(" !== null) { gt = " + indx);
865 out.append("; continue; }");
870 int indx = i + readIntArg(byteCodes, i);
871 out.append("if (").append(mapper.popA())
872 .append(" === null) { gt = " + indx);
873 out.append("; continue; }");
878 i = generateIf(byteCodes, i, mapper.popI(), mapper.popI(),
882 i = generateIf(byteCodes, i, mapper.popI(), mapper.popI(),
886 i = generateIf(byteCodes, i, mapper.popI(), mapper.popI(),
890 i = generateIf(byteCodes, i, mapper.popI(), mapper.popI(),
894 i = generateIf(byteCodes, i, mapper.popI(), mapper.popI(),
898 int indx = i + readIntArg(byteCodes, i);
899 out.append("gt = " + indx).append("; continue;");
903 case opc_lookupswitch: {
904 int table = i / 4 * 4 + 4;
905 int dflt = i + readInt4(byteCodes, table);
907 int n = readInt4(byteCodes, table);
909 out.append("switch (").append(mapper.popI()).append(") {\n");
911 int cnstnt = readInt4(byteCodes, table);
913 int offset = i + readInt4(byteCodes, table);
915 out.append(" case " + cnstnt).append(": gt = " + offset).append("; continue;\n");
917 out.append(" default: gt = " + dflt).append("; continue;\n}");
921 case opc_tableswitch: {
922 int table = i / 4 * 4 + 4;
923 int dflt = i + readInt4(byteCodes, table);
925 int low = readInt4(byteCodes, table);
927 int high = readInt4(byteCodes, table);
929 out.append("switch (").append(mapper.popI()).append(") {\n");
930 while (low <= high) {
931 int offset = i + readInt4(byteCodes, table);
933 out.append(" case " + low).append(": gt = " + offset).append("; continue;\n");
936 out.append(" default: gt = " + dflt).append("; continue;\n}");
940 case opc_invokeinterface: {
941 i = invokeVirtualMethod(byteCodes, i, mapper) + 2;
944 case opc_invokevirtual:
945 i = invokeVirtualMethod(byteCodes, i, mapper);
947 case opc_invokespecial:
948 i = invokeStaticMethod(byteCodes, i, mapper, false);
950 case opc_invokestatic:
951 i = invokeStaticMethod(byteCodes, i, mapper, true);
954 int indx = readIntArg(byteCodes, i);
955 String ci = jc.getClassName(indx);
956 out.append(mapper.pushA()).append(" = ");
957 out.append("new ").append(ci.replace('/','_'));
964 ++i; // skip type of array
965 final Variable v = mapper.popI();
966 out.append(mapper.pushA()).append(" = ")
967 .append("new Array(").append(v).append(").fillNulls();");
970 case opc_anewarray: {
971 i += 2; // skip type of array
972 final Variable v = mapper.popI();
973 out.append(mapper.pushA()).append(" = ")
974 .append("new Array(").append(v).append(").fillNulls();");
977 case opc_multianewarray: {
979 int dim = readByte(byteCodes, ++i);
980 out.append("{ var a0 = new Array(").append(mapper.popI())
981 .append(").fillNulls();");
982 for (int d = 1; d < dim; d++) {
983 out.append("\n var l" + d).append(" = ")
984 .append(mapper.popI()).append(';');
985 out.append("\n for (var i" + d).append (" = 0; i" + d).
986 append(" < a" + (d - 1)).
987 append(".length; i" + d).append("++) {");
988 out.append("\n var a" + d).
989 append (" = new Array(l" + d).append(").fillNulls();");
990 out.append("\n a" + (d - 1)).append("[i" + d).append("] = a" + d).
993 for (int d = 1; d < dim; d++) {
996 out.append("\n").append(mapper.pushA()).append(" = a0; }");
999 case opc_arraylength: {
1000 final Variable v = mapper.popA();
1001 out.append(mapper.pushI()).append(" = ")
1002 .append(v).append(".length;");
1006 out.append(mapper.getA(2)).append('[')
1007 .append(mapper.getI(1))
1009 .append(" = ").append(mapper.getL(0)).append(';');
1014 out.append(mapper.getA(2)).append('[')
1015 .append(mapper.getI(1))
1017 .append(" = ").append(mapper.getF(0)).append(';');
1022 out.append(mapper.getA(2)).append('[')
1023 .append(mapper.getI(1))
1025 .append(" = ").append(mapper.getD(0)).append(';');
1030 out.append(mapper.getA(2)).append('[')
1031 .append(mapper.getI(1))
1033 .append(" = ").append(mapper.getA(0)).append(';');
1041 out.append(mapper.getA(2)).append('[')
1042 .append(mapper.getI(1))
1044 .append(" = ").append(mapper.getI(0)).append(';');
1049 final Variable vidx = mapper.popI();
1050 final Variable varr = mapper.popA();
1051 out.append(mapper.pushL()).append(" = ")
1052 .append(varr).append('[').append(vidx).append("];");
1056 final Variable vidx = mapper.popI();
1057 final Variable varr = mapper.popA();
1058 out.append(mapper.pushF()).append(" = ")
1059 .append(varr).append('[').append(vidx).append("];");
1063 final Variable vidx = mapper.popI();
1064 final Variable varr = mapper.popA();
1065 out.append(mapper.pushD()).append(" = ")
1066 .append(varr).append('[').append(vidx).append("];");
1070 final Variable vidx = mapper.popI();
1071 final Variable varr = mapper.popA();
1072 out.append(mapper.pushA()).append(" = ")
1073 .append(varr).append('[').append(vidx).append("];");
1080 final Variable vidx = mapper.popI();
1081 final Variable varr = mapper.popA();
1082 out.append(mapper.pushI()).append(" = ")
1083 .append(varr).append('[').append(vidx).append("];");
1089 out.append("/* pop */");
1092 final Variable v = mapper.get(0);
1093 out.append(mapper.pushT(v.getType())).append(" = ")
1094 .append(v).append(';');
1098 if (mapper.get(0).isCategory2()) {
1099 final Variable v = mapper.get(0);
1100 out.append(mapper.pushT(v.getType())).append(" = ")
1101 .append(v).append(';');
1103 final Variable v1 = mapper.get(0);
1104 final Variable v2 = mapper.get(1);
1106 out.append(mapper.pushT(v2.getType())).append(" = ")
1107 .append(v2).append("; ");
1108 out.append(mapper.pushT(v1.getType())).append(" = ")
1109 .append(v1).append("; ");
1115 final Variable vi1 = mapper.pop();
1116 final Variable vi2 = mapper.pop();
1117 final Variable vo3 = mapper.pushT(vi1.getType());
1118 final Variable vo2 = mapper.pushT(vi2.getType());
1119 final Variable vo1 = mapper.pushT(vi1.getType());
1122 out.append(vo1).append(" = ").append(vi1).append("; ");
1123 out.append(vo2).append(" = ").append(vi2).append("; ");
1124 out.append(vo3).append(" = ").append(vo1).append("; ");
1129 if (mapper.get(1).isCategory2()) {
1130 final Variable vi1 = mapper.pop();
1131 final Variable vi2 = mapper.pop();
1132 final Variable vo3 = mapper.pushT(vi1.getType());
1133 final Variable vo2 = mapper.pushT(vi2.getType());
1134 final Variable vo1 = mapper.pushT(vi1.getType());
1137 out.append(vo1).append(" = ").append(vi1).append("; ");
1138 out.append(vo2).append(" = ").append(vi2).append("; ");
1139 out.append(vo3).append(" = ").append(vo1).append("; ");
1142 final Variable vi1 = mapper.pop();
1143 final Variable vi2 = mapper.pop();
1144 final Variable vi3 = mapper.pop();
1145 final Variable vo4 = mapper.pushT(vi1.getType());
1146 final Variable vo3 = mapper.pushT(vi3.getType());
1147 final Variable vo2 = mapper.pushT(vi2.getType());
1148 final Variable vo1 = mapper.pushT(vi1.getType());
1151 out.append(vo1).append(" = ").append(vi1).append("; ");
1152 out.append(vo2).append(" = ").append(vi2).append("; ");
1153 out.append(vo3).append(" = ").append(vi3).append("; ");
1154 out.append(vo4).append(" = ").append(vo1).append("; ");
1160 out.append(mapper.pushI()).append(" = ")
1161 .append(Integer.toString(byteCodes[++i])).append(';');
1164 out.append(mapper.pushI()).append(" = ")
1165 .append(Integer.toString(readIntArg(byteCodes, i)))
1169 case opc_getfield: {
1170 int indx = readIntArg(byteCodes, i);
1171 String[] fi = jc.getFieldInfoName(indx);
1172 final int type = fieldToVariableType(fi[2].charAt(0));
1173 final Variable v = mapper.popA();
1174 out.append(mapper.pushT(type)).append(" = ")
1175 .append(v).append(".fld_").append(fi[1]).append(';');
1179 case opc_getstatic: {
1180 int indx = readIntArg(byteCodes, i);
1181 String[] fi = jc.getFieldInfoName(indx);
1182 final int type = fieldToVariableType(fi[2].charAt(0));
1183 out.append(mapper.pushT(type)).append(" = ")
1184 .append(fi[0].replace('/', '_'))
1185 .append('.').append(fi[1]).append(';');
1187 addReference(fi[0]);
1190 case opc_putfield: {
1191 int indx = readIntArg(byteCodes, i);
1192 String[] fi = jc.getFieldInfoName(indx);
1193 final int type = fieldToVariableType(fi[2].charAt(0));
1194 final Variable v = mapper.popT(type);
1195 out.append(mapper.popA()).append(".fld_").append(fi[1])
1196 .append(" = ").append(v).append(';');
1200 case opc_putstatic: {
1201 int indx = readIntArg(byteCodes, i);
1202 String[] fi = jc.getFieldInfoName(indx);
1203 final int type = fieldToVariableType(fi[2].charAt(0));
1204 out.append(fi[0].replace('/', '_'));
1205 out.append('.').append(fi[1]).append(" = ")
1206 .append(mapper.popT(type)).append(';');
1208 addReference(fi[0]);
1211 case opc_checkcast: {
1212 int indx = readIntArg(byteCodes, i);
1213 final String type = jc.getClassName(indx);
1214 if (!type.startsWith("[")) {
1215 // no way to check arrays right now
1216 out.append("if (").append(mapper.getA(0))
1217 .append(".$instOf_").append(type.replace('/', '_'))
1218 .append(" != 1) throw {};"); // XXX proper exception
1223 case opc_instanceof: {
1224 int indx = readIntArg(byteCodes, i);
1225 final String type = jc.getClassName(indx);
1226 final Variable v = mapper.popA();
1227 out.append(mapper.pushI()).append(" = ")
1228 .append(v).append(".$instOf_")
1229 .append(type.replace('/', '_'))
1230 .append(" ? 1 : 0;");
1235 final Variable v = mapper.popA();
1239 out.append(mapper.pushA()).append(" = ")
1240 .append(v).append("; ");
1241 out.append("throw ").append(v).append("; ");
1247 case opc_monitorenter: {
1248 out.append("/* monitor enter */");
1253 case opc_monitorexit: {
1254 out.append("/* monitor exit */");
1260 out.append("throw 'unknown bytecode " + c + "';");
1265 for (int j = prev; j <= i; j++) {
1267 final int cc = readByte(byteCodes, j);
1268 out.append(Integer.toString(cc));
1275 private int generateIf(byte[] byteCodes, int i,
1276 final Variable v2, final Variable v1,
1277 final String test) throws IOException {
1278 int indx = i + readIntArg(byteCodes, i);
1279 out.append("if (").append(v1)
1280 .append(' ').append(test).append(' ')
1281 .append(v2).append(") { gt = " + indx)
1282 .append("; continue; }");
1286 private void generateCmp(Variable v2, Variable v1, Variable vr)
1287 throws IOException {
1288 out.append(vr).append(" = ")
1289 .append('(').append(v1).append(" == ").append(v2).append(')')
1291 .append(" : ((").append(v1).append(" < ").append(v2).append(')')
1292 .append(" ? -1 : 1);");
1295 private int readIntArg(byte[] byteCodes, int offsetInstruction) {
1296 final int indxHi = byteCodes[offsetInstruction + 1] << 8;
1297 final int indxLo = byteCodes[offsetInstruction + 2];
1298 return (indxHi & 0xffffff00) | (indxLo & 0xff);
1300 private int readInt4(byte[] byteCodes, int offsetInstruction) {
1301 final int d = byteCodes[offsetInstruction + 0] << 24;
1302 final int c = byteCodes[offsetInstruction + 1] << 16;
1303 final int b = byteCodes[offsetInstruction + 2] << 8;
1304 final int a = byteCodes[offsetInstruction + 3];
1305 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
1307 private int readByte(byte[] byteCodes, int offsetInstruction) {
1308 return byteCodes[offsetInstruction] & 0xff;
1311 private static void countArgs(String descriptor, char[] returnType, StringBuilder sig, StringBuilder cnt) {
1313 Boolean count = null;
1314 boolean array = false;
1316 int firstPos = sig.length();
1317 while (i < descriptor.length()) {
1318 char ch = descriptor.charAt(i++);
1339 if (ch == 'J' || ch == 'D') {
1345 sig.insert(firstPos, ch);
1347 returnType[0] = '[';
1348 sig.insert(firstPos, "_3");
1357 returnType[0] = 'V';
1358 sig.insert(firstPos, 'V');
1361 int next = descriptor.indexOf(';', i);
1362 String realSig = mangleSig(descriptor, i - 1, next + 1);
1367 sig.append(realSig);
1370 sig.insert(firstPos, realSig);
1372 sig.insert(firstPos, "_3");
1374 returnType[0] = 'L';
1382 throw new IllegalStateException("Invalid char: " + ch);
1387 private static String mangleSig(String txt, int first, int last) {
1388 StringBuilder sb = new StringBuilder();
1389 for (int i = first; i < last; i++) {
1390 final char ch = txt.charAt(i);
1392 case '/': sb.append('_'); break;
1393 case '_': sb.append("_1"); break;
1394 case ';': sb.append("_2"); break;
1395 case '[': sb.append("_3"); break;
1396 default: sb.append(ch); break;
1399 return sb.toString();
1402 private static String findMethodName(MethodData m, StringBuilder cnt) {
1403 StringBuilder name = new StringBuilder();
1404 if ("<init>".equals(m.getName())) { // NOI18N
1405 name.append("cons"); // NOI18N
1406 } else if ("<clinit>".equals(m.getName())) { // NOI18N
1407 name.append("class"); // NOI18N
1409 name.append(m.getName());
1412 countArgs(m.getInternalSig(), new char[1], name, cnt);
1413 return name.toString();
1416 static String findMethodName(String[] mi, StringBuilder cnt, char[] returnType) {
1417 StringBuilder name = new StringBuilder();
1418 String descr = mi[2];//mi.getDescriptor();
1420 if ("<init>".equals(nm)) { // NOI18N
1421 name.append("cons"); // NOI18N
1425 countArgs(descr, returnType, name, cnt);
1426 return name.toString();
1429 private int invokeStaticMethod(byte[] byteCodes, int i, final StackToVariableMapper mapper, boolean isStatic)
1430 throws IOException {
1431 int methodIndex = readIntArg(byteCodes, i);
1432 String[] mi = jc.getFieldInfoName(methodIndex);
1433 char[] returnType = { 'V' };
1434 StringBuilder cnt = new StringBuilder();
1435 String mn = findMethodName(mi, cnt, returnType);
1437 final int numArguments = isStatic ? cnt.length() : cnt.length() + 1;
1438 final Variable[] vars = new Variable[numArguments];
1440 for (int j = numArguments - 1; j >= 0; --j) {
1441 vars[j] = mapper.pop();
1444 if (returnType[0] != 'V') {
1445 out.append(mapper.pushT(fieldToVariableType(returnType[0])))
1449 final String in = mi[0];
1450 out.append(in.replace('/', '_'));
1451 out.append("(false).");
1454 if (numArguments > 0) {
1455 out.append(vars[0]);
1456 for (int j = 1; j < numArguments; ++j) {
1458 out.append(vars[j]);
1466 private int invokeVirtualMethod(byte[] byteCodes, int i, final StackToVariableMapper mapper)
1467 throws IOException {
1468 int methodIndex = readIntArg(byteCodes, i);
1469 String[] mi = jc.getFieldInfoName(methodIndex);
1470 char[] returnType = { 'V' };
1471 StringBuilder cnt = new StringBuilder();
1472 String mn = findMethodName(mi, cnt, returnType);
1474 final int numArguments = cnt.length() + 1;
1475 final Variable[] vars = new Variable[numArguments];
1477 for (int j = numArguments - 1; j >= 0; --j) {
1478 vars[j] = mapper.pop();
1481 if (returnType[0] != 'V') {
1482 out.append(mapper.pushT(fieldToVariableType(returnType[0])))
1486 out.append(vars[0]).append('.');
1489 out.append(vars[0]);
1490 for (int j = 1; j < numArguments; ++j) {
1492 out.append(vars[j]);
1499 private void addReference(String cn) throws IOException {
1500 if (requireReference(cn)) {
1501 out.append(" /* needs ").append(cn).append(" */");
1505 private void outType(String d, StringBuilder out) {
1507 while (d.charAt(0) == '[') {
1511 if (d.charAt(0) == 'L') {
1512 assert d.charAt(d.length() - 1) == ';';
1513 out.append(d.replace('/', '_').substring(0, d.length() - 1));
1519 private String encodeConstant(int entryIndex) throws IOException {
1520 String[] classRef = { null };
1521 String s = jc.stringValue(entryIndex, classRef);
1522 if (classRef[0] != null) {
1523 addReference(classRef[0]);
1528 private String javaScriptBody(String prefix, MethodData m, boolean isStatic) throws IOException {
1529 byte[] arr = m.findAnnotationData(true);
1533 final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
1534 class P extends AnnotationParser {
1540 String[] args = new String[30];
1544 protected void visitAttr(String type, String attr, String at, String value) {
1545 if (type.equals(jvmType)) {
1546 if ("body".equals(attr)) {
1548 } else if ("args".equals(attr)) {
1549 args[cnt++] = value;
1551 throw new IllegalArgumentException(attr);
1558 if (p.body == null) {
1561 StringBuilder cnt = new StringBuilder();
1562 final String mn = findMethodName(m, cnt);
1563 out.append(prefix).append(mn);
1564 out.append(" = function(");
1568 out.append(p.args[0]);
1575 for (int i = 0; i < cnt.length(); i++) {
1577 out.append(p.args[index]);
1581 out.append(") {").append("\n");
1583 out.append("\n}\n");
1586 private static String className(ClassData jc) {
1587 //return jc.getName().getInternalName().replace('/', '_');
1588 return jc.getClassName().replace('/', '_');
1591 private static String[] findAnnotation(
1592 byte[] arr, ClassData cd, final String className,
1593 final String... attrNames
1594 ) throws IOException {
1598 final String[] values = new String[attrNames.length];
1599 final boolean[] found = { false };
1600 final String jvmType = "L" + className.replace('.', '/') + ";";
1601 AnnotationParser ap = new AnnotationParser(false) {
1603 protected void visitAttr(String type, String attr, String at, String value) {
1604 if (type.equals(jvmType)) {
1606 for (int i = 0; i < attrNames.length; i++) {
1607 if (attrNames[i].equals(attr)) {
1616 return found[0] ? values : null;
1619 private CharSequence initField(FieldData v) {
1620 final String is = v.getInternalSig();
1621 if (is.length() == 1) {
1622 switch (is.charAt(0)) {
1628 case 'I': return " = 0;";
1630 case 'D': return " = 0.0;";
1632 throw new IllegalStateException(is);
1638 private static void generateAnno(ClassData cd, final Appendable out, byte[] data) throws IOException {
1639 AnnotationParser ap = new AnnotationParser(true) {
1644 protected void visitAnnotationStart(String type) throws IOException {
1648 out.append('"').append(type).append("\" : {\n");
1653 protected void visitAnnotationEnd(String type) throws IOException {
1654 out.append("\n}\n");
1658 protected void visitAttr(String type, String attr, String attrType, String value)
1659 throws IOException {
1666 out.append(attr).append("__").append(attrType).append(" : ").append(value);
1672 private static int constantToVariableType(final byte constantTag) {
1673 switch (constantTag) {
1674 case CONSTANT_INTEGER:
1675 return Variable.TYPE_INT;
1676 case CONSTANT_FLOAT:
1677 return Variable.TYPE_FLOAT;
1679 return Variable.TYPE_LONG;
1680 case CONSTANT_DOUBLE:
1681 return Variable.TYPE_DOUBLE;
1683 case CONSTANT_CLASS:
1685 case CONSTANT_UNICODE:
1686 case CONSTANT_STRING:
1687 return Variable.TYPE_REF;
1689 case CONSTANT_FIELD:
1690 case CONSTANT_METHOD:
1691 case CONSTANT_INTERFACEMETHOD:
1692 case CONSTANT_NAMEANDTYPE:
1693 /* unclear how to handle for now */
1695 throw new IllegalStateException("Unhandled constant tag");
1699 private static int fieldToVariableType(final char fieldType) {
1700 switch (fieldType) {
1706 return Variable.TYPE_INT;
1708 return Variable.TYPE_LONG;
1710 return Variable.TYPE_FLOAT;
1712 return Variable.TYPE_DOUBLE;
1715 return Variable.TYPE_REF;
1718 throw new IllegalStateException("Unhandled field type");