2 * Back 2 Browser Bytecode Translator
3 * Copyright (C) 2012 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, version 2 of the License.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. Look for COPYING file in the top folder.
16 * If not, see http://opensource.org/licenses/GPL-2.0.
18 package org.apidesign.vm4brwsr;
20 import java.io.IOException;
21 import java.io.InputStream;
22 import org.apidesign.javap.AnnotationParser;
23 import org.apidesign.javap.ClassData;
24 import org.apidesign.javap.FieldData;
25 import org.apidesign.javap.MethodData;
26 import org.apidesign.javap.StackMapIterator;
27 import static org.apidesign.javap.RuntimeConstants.*;
28 import org.apidesign.javap.TrapData;
29 import org.apidesign.javap.TrapDataIterator;
31 /** Translator of the code inside class files to JavaScript.
33 * @author Jaroslav Tulach <jtulach@netbeans.org>
35 abstract class ByteCodeToJavaScript {
39 protected ByteCodeToJavaScript(Appendable out) {
43 /* Collects additional required resources.
45 * @param internalClassName classes that were referenced and should be loaded in order the
46 * generated JavaScript code works properly. The names are in internal
47 * JVM form so String is <code>java/lang/String</code>.
49 protected abstract boolean requireReference(String internalClassName);
52 * @param resourcePath name of resources to read
54 protected abstract void requireScript(String resourcePath);
56 /** Allows subclasses to redefine what field a function representing a
57 * class gets assigned. By default it returns the suggested name followed
58 * by <code>" = "</code>;
60 * @param className suggested name of the class
62 /* protected */ String assignClass(String className) {
63 return className + " = ";
65 /* protected */ String accessClass(String classOperation) {
66 return classOperation;
69 /** Prints out a debug message.
71 * @param msg the message
72 * @return true if the message has been printed
75 boolean debug(String msg) throws IOException {
81 * Converts a given class file to a JavaScript version.
83 * @param classFile input stream with code of the .class file
84 * @return the initialization code for this class, if any. Otherwise <code>null</code>
86 * @throws IOException if something goes wrong during read or write or translating
89 public String compile(InputStream classFile) throws IOException {
90 this.jc = new ClassData(classFile);
91 if (jc.getMajor_version() < 50) {
92 throw new IOException("Can't compile " + jc.getClassName() + ". Class file version " + jc.getMajor_version() + "."
93 + jc.getMinor_version() + " - recompile with -target 1.6 (at least)."
96 byte[] arrData = jc.findAnnotationData(true);
97 String[] arr = findAnnotation(arrData, jc,
98 "org.apidesign.bck2brwsr.core.ExtraJavaScript",
99 "resource", "processByteCode"
102 requireScript(arr[0]);
103 if ("0".equals(arr[1])) {
107 String[] proto = findAnnotation(arrData, jc,
108 "org.apidesign.bck2brwsr.core.JavaScriptPrototype",
109 "container", "prototype"
111 StringArray toInitilize = new StringArray();
112 final String className = className(jc);
113 out.append("\n\n").append(assignClass(className));
114 out.append("function CLS() {");
115 out.append("\n if (!CLS.prototype.$instOf_").append(className).append(") {");
116 for (FieldData v : jc.getFields()) {
118 out.append("\n CLS.").append(v.getName()).append(initField(v));
122 String sc = jc.getSuperClassName(); // with _
123 out.append("\n var pp = ").
124 append(accessClass(sc.replace('/', '_'))).append("(true);");
125 out.append("\n var p = CLS.prototype = pp;");
126 out.append("\n var c = p;");
127 out.append("\n var sprcls = pp.constructor.$class;");
129 out.append("\n var p = CLS.prototype = ").append(proto[1]).append(";");
130 if (proto[0] == null) {
133 out.append("\n var c = ").append(proto[0]).append(";");
134 out.append("\n var sprcls = null;");
136 for (MethodData m : jc.getMethods()) {
137 byte[] onlyArr = m.findAnnotationData(true);
138 String[] only = findAnnotation(onlyArr, jc,
139 "org.apidesign.bck2brwsr.core.JavaScriptOnly",
143 if (only[0] != null && only[1] != null) {
144 out.append("\n p.").append(only[0]).append(" = ")
145 .append(only[1]).append(";");
153 mn = generateStaticMethod(prefix, m, toInitilize);
155 if (m.isConstructor()) {
157 mn = generateInstanceMethod(prefix, m);
160 mn = generateInstanceMethod(prefix, m);
163 byte[] runAnno = m.findAnnotationData(false);
164 if (runAnno != null) {
165 out.append(prefix).append(mn).append(".anno = {");
166 generateAnno(jc, out, runAnno);
169 out.append(prefix).append(mn).append(".access = " + m.getAccess()).append(";");
171 out.append("\n c.constructor = CLS;");
172 out.append("\n c.$instOf_").append(className).append(" = true;");
173 for (String superInterface : jc.getSuperInterfaces()) {
174 out.append("\n c.$instOf_").append(superInterface.replace('/', '_')).append(" = true;");
176 out.append("\n CLS.$class = ");
177 out.append(accessClass("java_lang_Class(true);"));
178 out.append("\n CLS.$class.jvmName = '").append(jc.getClassName()).append("';");
179 out.append("\n CLS.$class.superclass = sprcls;");
180 out.append("\n CLS.$class.access = ").append(jc.getAccessFlags()+";");
181 out.append("\n CLS.$class.cnstr = CLS;");
182 byte[] classAnno = jc.findAnnotationData(false);
183 if (classAnno != null) {
184 out.append("\n CLS.$class.anno = {");
185 generateAnno(jc, out, classAnno);
189 out.append("\n if (arguments.length === 0) {");
190 out.append("\n if (!(this instanceof CLS)) {");
191 out.append("\n return new CLS();");
193 for (FieldData v : jc.getFields()) {
194 byte[] onlyArr = v.findAnnotationData(true);
195 String[] only = findAnnotation(onlyArr, jc,
196 "org.apidesign.bck2brwsr.core.JavaScriptOnly",
200 if (only[0] != null && only[1] != null) {
201 out.append("\n p.").append(only[0]).append(" = ")
202 .append(only[1]).append(";");
207 out.append("\n this.fld_").
208 append(v.getName()).append(initField(v));
211 out.append("\n return this;");
213 out.append("\n return arguments[0] ? new CLS() : CLS.prototype;");
215 StringBuilder sb = new StringBuilder();
216 for (String init : toInitilize.toArray()) {
217 sb.append("\n").append(init).append("();");
219 return sb.toString();
221 private String generateStaticMethod(String prefix, MethodData m, StringArray toInitilize) throws IOException {
222 String jsb = javaScriptBody(prefix, m, true);
226 final String mn = findMethodName(m, new StringBuilder());
227 if (mn.equals("class__V")) {
228 toInitilize.add(accessClass(className(jc)) + "(false)." + mn);
230 generateMethod(prefix, mn, m);
234 private String generateInstanceMethod(String prefix, MethodData m) throws IOException {
235 String jsb = javaScriptBody(prefix, m, false);
239 final String mn = findMethodName(m, new StringBuilder());
240 generateMethod(prefix, mn, m);
244 private void generateMethod(String prefix, String name, MethodData m)
246 final StackMapIterator stackMapIterator = m.createStackMapIterator();
247 TrapDataIterator trap = m.getTrapDataIterator();
248 final LocalsMapper lmapper =
249 new LocalsMapper(stackMapIterator.getArguments());
251 out.append(prefix).append(name).append(" = function(");
252 lmapper.outputArguments(out, m.isStatic());
253 out.append(") {").append("\n");
255 final byte[] byteCodes = m.getCode();
256 if (byteCodes == null) {
257 out.append(" throw 'no code found for ")
258 .append(jc.getClassName()).append('.')
259 .append(m.getName()).append("';\n");
264 final StackMapper smapper = new StackMapper();
266 final int maxLocals = m.getMaxLocals();
268 // TODO: generate only used local variables
269 for (int j = 0; j <= VarType.LAST; ++j) {
270 out.append("\n var ").append(Variable.getLocalVariable(j, 0));
271 for (int i = 1; i < maxLocals; ++i) {
273 out.append(Variable.getLocalVariable(j, i));
279 out.append(" var ").append(" lcA0 = this;\n");
282 // maxStack includes two stack positions for every pushed long / double
283 // so this might generate more stack variables than we need
284 final int maxStack = m.getMaxStack();
286 // TODO: generate only used stack variables
287 for (int j = 0; j <= VarType.LAST; ++j) {
288 out.append("\n var ").append(Variable.getStackVariable(j, 0));
289 for (int i = 1; i < maxStack; ++i) {
291 out.append(Variable.getStackVariable(j, i));
297 int lastStackFrame = -1;
298 TrapData[] previousTrap = null;
300 out.append("\n var gt = 0;\n for(;;) switch(gt) {\n");
301 for (int i = 0; i < byteCodes.length; i++) {
303 stackMapIterator.advanceTo(i);
304 boolean changeInCatch = trap.advanceTo(i);
305 if (changeInCatch || lastStackFrame != stackMapIterator.getFrameIndex()) {
306 if (previousTrap != null) {
307 generateCatch(previousTrap);
311 if (lastStackFrame != stackMapIterator.getFrameIndex()) {
312 lastStackFrame = stackMapIterator.getFrameIndex();
313 lmapper.syncWithFrameLocals(stackMapIterator.getFrameLocals());
314 smapper.syncWithFrameStack(stackMapIterator.getFrameStack());
315 out.append(" case " + i).append(": ");
316 changeInCatch = true;
318 debug(" /* " + i + " */ ");
320 if (changeInCatch && trap.useTry()) {
322 previousTrap = trap.current();
324 final int c = readByte(byteCodes, i);
327 emit(out, "@1 = @2;", smapper.pushA(), lmapper.getA(0));
330 emit(out, "@1 = @2;", smapper.pushI(), lmapper.getI(0));
333 emit(out, "@1 = @2;", smapper.pushL(), lmapper.getL(0));
336 emit(out, "@1 = @2;", smapper.pushF(), lmapper.getF(0));
339 emit(out, "@1 = @2;", smapper.pushD(), lmapper.getD(0));
342 emit(out, "@1 = @2;", smapper.pushA(), lmapper.getA(1));
345 emit(out, "@1 = @2;", smapper.pushI(), lmapper.getI(1));
348 emit(out, "@1 = @2;", smapper.pushL(), lmapper.getL(1));
351 emit(out, "@1 = @2;", smapper.pushF(), lmapper.getF(1));
354 emit(out, "@1 = @2;", smapper.pushD(), lmapper.getD(1));
357 emit(out, "@1 = @2;", smapper.pushA(), lmapper.getA(2));
360 emit(out, "@1 = @2;", smapper.pushI(), lmapper.getI(2));
363 emit(out, "@1 = @2;", smapper.pushL(), lmapper.getL(2));
366 emit(out, "@1 = @2;", smapper.pushF(), lmapper.getF(2));
369 emit(out, "@1 = @2;", smapper.pushD(), lmapper.getD(2));
372 emit(out, "@1 = @2;", smapper.pushA(), lmapper.getA(3));
375 emit(out, "@1 = @2;", smapper.pushI(), lmapper.getI(3));
378 emit(out, "@1 = @2;", smapper.pushL(), lmapper.getL(3));
381 emit(out, "@1 = @2;", smapper.pushF(), lmapper.getF(3));
384 emit(out, "@1 = @2;", smapper.pushD(), lmapper.getD(3));
387 final int indx = readByte(byteCodes, ++i);
388 emit(out, "@1 = @2;", smapper.pushI(), lmapper.getI(indx));
392 final int indx = readByte(byteCodes, ++i);
393 emit(out, "@1 = @2;", smapper.pushL(), lmapper.getL(indx));
397 final int indx = readByte(byteCodes, ++i);
398 emit(out, "@1 = @2;", smapper.pushF(), lmapper.getF(indx));
402 final int indx = readByte(byteCodes, ++i);
403 emit(out, "@1 = @2;", smapper.pushD(), lmapper.getD(indx));
407 final int indx = readByte(byteCodes, ++i);
408 emit(out, "@1 = @2;", smapper.pushA(), lmapper.getA(indx));
412 final int indx = readByte(byteCodes, ++i);
413 emit(out, "@1 = @2;", lmapper.setI(indx), smapper.popI());
417 final int indx = readByte(byteCodes, ++i);
418 emit(out, "@1 = @2;", lmapper.setL(indx), smapper.popL());
422 final int indx = readByte(byteCodes, ++i);
423 emit(out, "@1 = @2;", lmapper.setF(indx), smapper.popF());
427 final int indx = readByte(byteCodes, ++i);
428 emit(out, "@1 = @2;", lmapper.setD(indx), smapper.popD());
432 final int indx = readByte(byteCodes, ++i);
433 emit(out, "@1 = @2;", lmapper.setA(indx), smapper.popA());
437 emit(out, "@1 = @2;", lmapper.setA(0), smapper.popA());
440 emit(out, "@1 = @2;", lmapper.setI(0), smapper.popI());
443 emit(out, "@1 = @2;", lmapper.setL(0), smapper.popL());
446 emit(out, "@1 = @2;", lmapper.setF(0), smapper.popF());
449 emit(out, "@1 = @2;", lmapper.setD(0), smapper.popD());
452 emit(out, "@1 = @2;", lmapper.setA(1), smapper.popA());
455 emit(out, "@1 = @2;", lmapper.setI(1), smapper.popI());
458 emit(out, "@1 = @2;", lmapper.setL(1), smapper.popL());
461 emit(out, "@1 = @2;", lmapper.setF(1), smapper.popF());
464 emit(out, "@1 = @2;", lmapper.setD(1), smapper.popD());
467 emit(out, "@1 = @2;", lmapper.setA(2), smapper.popA());
470 emit(out, "@1 = @2;", lmapper.setI(2), smapper.popI());
473 emit(out, "@1 = @2;", lmapper.setL(2), smapper.popL());
476 emit(out, "@1 = @2;", lmapper.setF(2), smapper.popF());
479 emit(out, "@1 = @2;", lmapper.setD(2), smapper.popD());
482 emit(out, "@1 = @2;", lmapper.setA(3), smapper.popA());
485 emit(out, "@1 = @2;", lmapper.setI(3), smapper.popI());
488 emit(out, "@1 = @2;", lmapper.setL(3), smapper.popL());
491 emit(out, "@1 = @2;", lmapper.setF(3), smapper.popF());
494 emit(out, "@1 = @2;", lmapper.setD(3), smapper.popD());
497 emit(out, "@1 = @1.add32(@2);", smapper.getI(1), smapper.popI());
500 emit(out, "@1 += @2;", smapper.getL(1), smapper.popL());
503 emit(out, "@1 += @2;", smapper.getF(1), smapper.popF());
506 emit(out, "@1 += @2;", smapper.getD(1), smapper.popD());
509 emit(out, "@1 = @1.sub32(@2);", smapper.getI(1), smapper.popI());
512 emit(out, "@1 -= @2;", smapper.getL(1), smapper.popL());
515 emit(out, "@1 -= @2;", smapper.getF(1), smapper.popF());
518 emit(out, "@1 -= @2;", smapper.getD(1), smapper.popD());
521 emit(out, "@1 = @1.mul32(@2);", smapper.getI(1), smapper.popI());
524 emit(out, "@1 *= @2;", smapper.getL(1), smapper.popL());
527 emit(out, "@1 *= @2;", smapper.getF(1), smapper.popF());
530 emit(out, "@1 *= @2;", smapper.getD(1), smapper.popD());
533 emit(out, "@1 = Math.floor(@1 / @2);",
534 smapper.getI(1), smapper.popI());
537 emit(out, "@1 = Math.floor(@1 / @2);",
538 smapper.getL(1), smapper.popL());
541 emit(out, "@1 /= @2;", smapper.getF(1), smapper.popF());
544 emit(out, "@1 /= @2;", smapper.getD(1), smapper.popD());
547 emit(out, "@1 %= @2;", smapper.getI(1), smapper.popI());
550 emit(out, "@1 %= @2;", smapper.getL(1), smapper.popL());
553 emit(out, "@1 %= @2;", smapper.getF(1), smapper.popF());
556 emit(out, "@1 %= @2;", smapper.getD(1), smapper.popD());
559 emit(out, "@1 &= @2;", smapper.getI(1), smapper.popI());
562 emit(out, "@1 &= @2;", smapper.getL(1), smapper.popL());
565 emit(out, "@1 |= @2;", smapper.getI(1), smapper.popI());
568 emit(out, "@1 |= @2;", smapper.getL(1), smapper.popL());
571 emit(out, "@1 ^= @2;", smapper.getI(1), smapper.popI());
574 emit(out, "@1 ^= @2;", smapper.getL(1), smapper.popL());
577 emit(out, "@1 = -@1;", smapper.getI(0));
580 emit(out, "@1 = -@1;", smapper.getL(0));
583 emit(out, "@1 = -@1;", smapper.getF(0));
586 emit(out, "@1 = -@1;", smapper.getD(0));
589 emit(out, "@1 <<= @2;", smapper.getI(1), smapper.popI());
592 emit(out, "@1 <<= @2;", smapper.getL(1), smapper.popI());
595 emit(out, "@1 >>= @2;", smapper.getI(1), smapper.popI());
598 emit(out, "@1 >>= @2;", smapper.getL(1), smapper.popI());
601 emit(out, "@1 >>>= @2;", smapper.getI(1), smapper.popI());
604 emit(out, "@1 >>>= @2;", smapper.getL(1), smapper.popI());
607 final int varIndx = readByte(byteCodes, ++i);
608 final int incrBy = byteCodes[++i];
610 emit(out, "@1++;", lmapper.getI(varIndx));
612 emit(out, "@1 += @2;",
613 lmapper.getI(varIndx),
614 Integer.toString(incrBy));
619 emit(out, "return;");
622 emit(out, "return @1;", smapper.popI());
625 emit(out, "return @1;", smapper.popL());
628 emit(out, "return @1;", smapper.popF());
631 emit(out, "return @1;", smapper.popD());
634 emit(out, "return @1;", smapper.popA());
637 emit(out, "@2 = @1;", smapper.popI(), smapper.pushL());
640 emit(out, "@2 = @1;", smapper.popI(), smapper.pushF());
643 emit(out, "@2 = @1;", smapper.popI(), smapper.pushD());
646 emit(out, "@2 = @1;", smapper.popL(), smapper.pushI());
650 emit(out, "@2 = @1;", smapper.popL(), smapper.pushF());
653 emit(out, "@2 = @1;", smapper.popL(), smapper.pushD());
656 emit(out, "@2 = @1;", smapper.popF(), smapper.pushD());
659 emit(out, "@2 = @1;", smapper.popD(), smapper.pushF());
662 emit(out, "@2 = Math.floor(@1);",
663 smapper.popF(), smapper.pushI());
666 emit(out, "@2 = Math.floor(@1);",
667 smapper.popF(), smapper.pushL());
670 emit(out, "@2 = Math.floor(@1);",
671 smapper.popD(), smapper.pushI());
674 emit(out, "@2 = Math.floor(@1);",
675 smapper.popD(), smapper.pushL());
678 emit(out, "@1 = @1.toInt8();", smapper.getI(0));
681 out.append("{ /* number conversion */ }");
684 emit(out, "@1 = @1.toInt16();", smapper.getI(0));
686 case opc_aconst_null:
687 emit(out, "@1 = null;", smapper.pushA());
690 emit(out, "@1 = -1;", smapper.pushI());
693 emit(out, "@1 = 0;", smapper.pushI());
696 emit(out, "@1 = 0;", smapper.pushD());
699 emit(out, "@1 = 0;", smapper.pushL());
702 emit(out, "@1 = 0;", smapper.pushF());
705 emit(out, "@1 = 1;", smapper.pushI());
708 emit(out, "@1 = 1;", smapper.pushL());
711 emit(out, "@1 = 1;", smapper.pushF());
714 emit(out, "@1 = 1;", smapper.pushD());
717 emit(out, "@1 = 2;", smapper.pushI());
720 emit(out, "@1 = 2;", smapper.pushF());
723 emit(out, "@1 = 3;", smapper.pushI());
726 emit(out, "@1 = 4;", smapper.pushI());
729 emit(out, "@1 = 5;", smapper.pushI());
732 int indx = readByte(byteCodes, ++i);
733 String v = encodeConstant(indx);
734 int type = VarType.fromConstantType(jc.getTag(indx));
735 emit(out, "@1 = @2;", smapper.pushT(type), v);
740 int indx = readIntArg(byteCodes, i);
742 String v = encodeConstant(indx);
743 int type = VarType.fromConstantType(jc.getTag(indx));
744 emit(out, "@1 = @2;", smapper.pushT(type), v);
748 emit(out, "@3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
749 smapper.popL(), smapper.popL(), smapper.pushI());
753 emit(out, "@3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
754 smapper.popF(), smapper.popF(), smapper.pushI());
758 emit(out, "@3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
759 smapper.popD(), smapper.popD(), smapper.pushI());
762 i = generateIf(byteCodes, i, smapper.popA(), smapper.popA(),
766 i = generateIf(byteCodes, i, smapper.popA(), smapper.popA(),
770 i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
774 int indx = i + readIntArg(byteCodes, i);
775 emit(out, "if (@1 == 0) { gt = @2; continue; }",
776 smapper.popI(), Integer.toString(indx));
781 int indx = i + readIntArg(byteCodes, i);
782 emit(out, "if (@1 != 0) { gt = @2; continue; }",
783 smapper.popI(), Integer.toString(indx));
788 int indx = i + readIntArg(byteCodes, i);
789 emit(out, "if (@1 < 0) { gt = @2; continue; }",
790 smapper.popI(), Integer.toString(indx));
795 int indx = i + readIntArg(byteCodes, i);
796 emit(out, "if (@1 <= 0) { gt = @2; continue; }",
797 smapper.popI(), Integer.toString(indx));
802 int indx = i + readIntArg(byteCodes, i);
803 emit(out, "if (@1 > 0) { gt = @2; continue; }",
804 smapper.popI(), Integer.toString(indx));
809 int indx = i + readIntArg(byteCodes, i);
810 emit(out, "if (@1 >= 0) { gt = @2; continue; }",
811 smapper.popI(), Integer.toString(indx));
815 case opc_ifnonnull: {
816 int indx = i + readIntArg(byteCodes, i);
817 emit(out, "if (@1 !== null) { gt = @2; continue; }",
818 smapper.popA(), Integer.toString(indx));
823 int indx = i + readIntArg(byteCodes, i);
824 emit(out, "if (@1 === null) { gt = @2; continue; }",
825 smapper.popA(), Integer.toString(indx));
830 i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
834 i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
838 i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
842 i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
846 i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
850 int indx = i + readIntArg(byteCodes, i);
851 emit(out, "gt = @1; continue;", Integer.toString(indx));
855 case opc_lookupswitch: {
856 int table = i / 4 * 4 + 4;
857 int dflt = i + readInt4(byteCodes, table);
859 int n = readInt4(byteCodes, table);
861 out.append("switch (").append(smapper.popI()).append(") {\n");
863 int cnstnt = readInt4(byteCodes, table);
865 int offset = i + readInt4(byteCodes, table);
867 out.append(" case " + cnstnt).append(": gt = " + offset).append("; continue;\n");
869 out.append(" default: gt = " + dflt).append("; continue;\n}");
873 case opc_tableswitch: {
874 int table = i / 4 * 4 + 4;
875 int dflt = i + readInt4(byteCodes, table);
877 int low = readInt4(byteCodes, table);
879 int high = readInt4(byteCodes, table);
881 out.append("switch (").append(smapper.popI()).append(") {\n");
882 while (low <= high) {
883 int offset = i + readInt4(byteCodes, table);
885 out.append(" case " + low).append(": gt = " + offset).append("; continue;\n");
888 out.append(" default: gt = " + dflt).append("; continue;\n}");
892 case opc_invokeinterface: {
893 i = invokeVirtualMethod(byteCodes, i, smapper) + 2;
896 case opc_invokevirtual:
897 i = invokeVirtualMethod(byteCodes, i, smapper);
899 case opc_invokespecial:
900 i = invokeStaticMethod(byteCodes, i, smapper, false);
902 case opc_invokestatic:
903 i = invokeStaticMethod(byteCodes, i, smapper, true);
906 int indx = readIntArg(byteCodes, i);
907 String ci = jc.getClassName(indx);
908 emit(out, "@1 = new @2;",
909 smapper.pushA(), accessClass(ci.replace('/', '_')));
915 int atype = readByte(byteCodes, ++i);
918 case 4: jvmType = "[Z"; break;
919 case 5: jvmType = "[C"; break;
920 case 6: jvmType = "[F"; break;
921 case 7: jvmType = "[D"; break;
922 case 8: jvmType = "[B"; break;
923 case 9: jvmType = "[S"; break;
924 case 10: jvmType = "[I"; break;
925 case 11: jvmType = "[J"; break;
926 default: throw new IllegalStateException("Array type: " + atype);
928 emit(out, "@2 = new Array(@1).initWith('@3', 0);",
929 smapper.popI(), smapper.pushA(), jvmType);
931 case opc_anewarray: {
932 int type = readIntArg(byteCodes, i);
934 String typeName = jc.getClassName(type);
935 if (typeName.startsWith("[")) {
936 typeName = "[" + typeName;
938 typeName = "[L" + typeName + ";";
940 emit(out, "@2 = new Array(@1).initWith('@3', null);",
941 smapper.popI(), smapper.pushA(), typeName);
944 case opc_multianewarray: {
945 int type = readIntArg(byteCodes, i);
947 String typeName = jc.getClassName(type);
948 int dim = readByte(byteCodes, ++i);
949 out.append("{ var a0 = new Array(").append(smapper.popI())
950 .append(").initWith('").append(typeName).append("', null);");
951 for (int d = 1; d < dim; d++) {
952 typeName = typeName.substring(1);
953 out.append("\n var l" + d).append(" = ")
954 .append(smapper.popI()).append(';');
955 out.append("\n for (var i" + d).append (" = 0; i" + d).
956 append(" < a" + (d - 1)).
957 append(".length; i" + d).append("++) {");
958 out.append("\n var a" + d).
959 append (" = new Array(l" + d).append(").initWith('")
960 .append(typeName).append("', null);");
961 out.append("\n a" + (d - 1)).append("[i" + d).append("] = a" + d).
964 for (int d = 1; d < dim; d++) {
967 out.append("\n").append(smapper.pushA()).append(" = a0; }");
970 case opc_arraylength:
971 emit(out, "@2 = @1.length;", smapper.popA(), smapper.pushI());
974 emit(out, "@3[@2] = @1;",
975 smapper.popL(), smapper.popI(), smapper.popA());
978 emit(out, "@3[@2] = @1;",
979 smapper.popF(), smapper.popI(), smapper.popA());
982 emit(out, "@3[@2] = @1;",
983 smapper.popD(), smapper.popI(), smapper.popA());
986 emit(out, "@3[@2] = @1;",
987 smapper.popA(), smapper.popI(), smapper.popA());
993 emit(out, "@3[@2] = @1;",
994 smapper.popI(), smapper.popI(), smapper.popA());
997 emit(out, "@3 = @2[@1];",
998 smapper.popI(), smapper.popA(), smapper.pushL());
1001 emit(out, "@3 = @2[@1];",
1002 smapper.popI(), smapper.popA(), smapper.pushF());
1005 emit(out, "@3 = @2[@1];",
1006 smapper.popI(), smapper.popA(), smapper.pushD());
1009 emit(out, "@3 = @2[@1];",
1010 smapper.popI(), smapper.popA(), smapper.pushA());
1016 emit(out, "@3 = @2[@1];",
1017 smapper.popI(), smapper.popA(), smapper.pushI());
1025 final Variable v = smapper.get(0);
1026 emit(out, "@1 = @2;", smapper.pushT(v.getType()), v);
1030 if (smapper.get(0).isCategory2()) {
1031 final Variable v = smapper.get(0);
1032 emit(out, "@1 = @2;", smapper.pushT(v.getType()), v);
1034 final Variable v1 = smapper.get(0);
1035 final Variable v2 = smapper.get(1);
1036 emit(out, "{ @1 = @2; @3 = @4; }",
1037 smapper.pushT(v2.getType()), v2,
1038 smapper.pushT(v1.getType()), v1);
1043 final Variable vi1 = smapper.pop();
1044 final Variable vi2 = smapper.pop();
1045 final Variable vo3 = smapper.pushT(vi1.getType());
1046 final Variable vo2 = smapper.pushT(vi2.getType());
1047 final Variable vo1 = smapper.pushT(vi1.getType());
1049 emit(out, "{ @1 = @2; @3 = @4; @5 = @6; }",
1050 vo1, vi1, vo2, vi2, vo3, vo1);
1054 if (smapper.get(1).isCategory2()) {
1055 final Variable vi1 = smapper.pop();
1056 final Variable vi2 = smapper.pop();
1057 final Variable vo3 = smapper.pushT(vi1.getType());
1058 final Variable vo2 = smapper.pushT(vi2.getType());
1059 final Variable vo1 = smapper.pushT(vi1.getType());
1061 emit(out, "{ @1 = @2; @3 = @4; @5 = @6; }",
1062 vo1, vi1, vo2, vi2, vo3, vo1);
1064 final Variable vi1 = smapper.pop();
1065 final Variable vi2 = smapper.pop();
1066 final Variable vi3 = smapper.pop();
1067 final Variable vo4 = smapper.pushT(vi1.getType());
1068 final Variable vo3 = smapper.pushT(vi3.getType());
1069 final Variable vo2 = smapper.pushT(vi2.getType());
1070 final Variable vo1 = smapper.pushT(vi1.getType());
1072 emit(out, "{ @1 = @2; @3 = @4; @5 = @6; @7 = @8; }",
1073 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1078 emit(out, "@1 = @2;",
1079 smapper.pushI(), Integer.toString(byteCodes[++i]));
1082 emit(out, "@1 = @2;",
1084 Integer.toString(readIntArg(byteCodes, i)));
1087 case opc_getfield: {
1088 int indx = readIntArg(byteCodes, i);
1089 String[] fi = jc.getFieldInfoName(indx);
1090 final int type = VarType.fromFieldType(fi[2].charAt(0));
1091 emit(out, "@2 = @1.fld_@3;",
1092 smapper.popA(), smapper.pushT(type), fi[1]);
1096 case opc_getstatic: {
1097 int indx = readIntArg(byteCodes, i);
1098 String[] fi = jc.getFieldInfoName(indx);
1099 final int type = VarType.fromFieldType(fi[2].charAt(0));
1100 emit(out, "@1 = @2(false).constructor.@3;",
1101 smapper.pushT(type),
1102 accessClass(fi[0].replace('/', '_')), fi[1]);
1104 addReference(fi[0]);
1107 case opc_putfield: {
1108 int indx = readIntArg(byteCodes, i);
1109 String[] fi = jc.getFieldInfoName(indx);
1110 final int type = VarType.fromFieldType(fi[2].charAt(0));
1111 emit(out, "@2.fld_@3 = @1;",
1112 smapper.popT(type), smapper.popA(), fi[1]);
1116 case opc_putstatic: {
1117 int indx = readIntArg(byteCodes, i);
1118 String[] fi = jc.getFieldInfoName(indx);
1119 final int type = VarType.fromFieldType(fi[2].charAt(0));
1120 emit(out, "@1(false).constructor.@2 = @3;",
1121 accessClass(fi[0].replace('/', '_')), fi[1],
1122 smapper.popT(type));
1124 addReference(fi[0]);
1127 case opc_checkcast: {
1128 int indx = readIntArg(byteCodes, i);
1129 final String type = jc.getClassName(indx);
1130 if (!type.startsWith("[")) {
1131 // no way to check arrays right now
1132 // XXX proper exception
1134 "if (@1 !== null && !@1.$instOf_@2) throw {};",
1135 smapper.getA(0), type.replace('/', '_'));
1140 case opc_instanceof: {
1141 int indx = readIntArg(byteCodes, i);
1142 final String type = jc.getClassName(indx);
1143 emit(out, "@2 = @1.$instOf_@3 ? 1 : 0;",
1144 smapper.popA(), smapper.pushI(),
1145 type.replace('/', '_'));
1150 final Variable v = smapper.popA();
1153 emit(out, "{ @1 = @2; throw @2; }",
1154 smapper.pushA(), v);
1158 case opc_monitorenter: {
1159 out.append("/* monitor enter */");
1164 case opc_monitorexit: {
1165 out.append("/* monitor exit */");
1171 emit(out, "throw 'unknown bytecode @1';",
1172 Integer.toString(c));
1176 for (int j = prev; j <= i; j++) {
1178 final int cc = readByte(byteCodes, j);
1179 out.append(Integer.toString(cc));
1184 if (previousTrap != null) {
1185 generateCatch(previousTrap);
1191 private int generateIf(byte[] byteCodes, int i,
1192 final Variable v2, final Variable v1,
1193 final String test) throws IOException {
1194 int indx = i + readIntArg(byteCodes, i);
1195 out.append("if (").append(v1)
1196 .append(' ').append(test).append(' ')
1197 .append(v2).append(") { gt = " + indx)
1198 .append("; continue; }");
1202 private int readIntArg(byte[] byteCodes, int offsetInstruction) {
1203 final int indxHi = byteCodes[offsetInstruction + 1] << 8;
1204 final int indxLo = byteCodes[offsetInstruction + 2];
1205 return (indxHi & 0xffffff00) | (indxLo & 0xff);
1207 private int readInt4(byte[] byteCodes, int offsetInstruction) {
1208 final int d = byteCodes[offsetInstruction + 0] << 24;
1209 final int c = byteCodes[offsetInstruction + 1] << 16;
1210 final int b = byteCodes[offsetInstruction + 2] << 8;
1211 final int a = byteCodes[offsetInstruction + 3];
1212 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
1214 private int readByte(byte[] byteCodes, int offsetInstruction) {
1215 return byteCodes[offsetInstruction] & 0xff;
1218 private static void countArgs(String descriptor, char[] returnType, StringBuilder sig, StringBuilder cnt) {
1220 Boolean count = null;
1221 boolean array = false;
1223 int firstPos = sig.length();
1224 while (i < descriptor.length()) {
1225 char ch = descriptor.charAt(i++);
1246 if (ch == 'J' || ch == 'D') {
1252 sig.insert(firstPos, ch);
1254 returnType[0] = '[';
1255 sig.insert(firstPos, "_3");
1264 returnType[0] = 'V';
1265 sig.insert(firstPos, 'V');
1268 int next = descriptor.indexOf(';', i);
1269 String realSig = mangleSig(descriptor, i - 1, next + 1);
1274 sig.append(realSig);
1277 sig.insert(firstPos, realSig);
1279 sig.insert(firstPos, "_3");
1281 returnType[0] = 'L';
1290 throw new IllegalStateException("Invalid char: " + ch);
1295 private static String mangleSig(String txt, int first, int last) {
1296 StringBuilder sb = new StringBuilder();
1297 for (int i = first; i < last; i++) {
1298 final char ch = txt.charAt(i);
1300 case '/': sb.append('_'); break;
1301 case '_': sb.append("_1"); break;
1302 case ';': sb.append("_2"); break;
1303 case '[': sb.append("_3"); break;
1304 default: sb.append(ch); break;
1307 return sb.toString();
1310 private static String findMethodName(MethodData m, StringBuilder cnt) {
1311 StringBuilder name = new StringBuilder();
1312 if ("<init>".equals(m.getName())) { // NOI18N
1313 name.append("cons"); // NOI18N
1314 } else if ("<clinit>".equals(m.getName())) { // NOI18N
1315 name.append("class"); // NOI18N
1317 name.append(m.getName());
1320 countArgs(m.getInternalSig(), new char[1], name, cnt);
1321 return name.toString();
1324 static String findMethodName(String[] mi, StringBuilder cnt, char[] returnType) {
1325 StringBuilder name = new StringBuilder();
1326 String descr = mi[2];//mi.getDescriptor();
1328 if ("<init>".equals(nm)) { // NOI18N
1329 name.append("cons"); // NOI18N
1333 countArgs(descr, returnType, name, cnt);
1334 return name.toString();
1337 private int invokeStaticMethod(byte[] byteCodes, int i, final StackMapper mapper, boolean isStatic)
1338 throws IOException {
1339 int methodIndex = readIntArg(byteCodes, i);
1340 String[] mi = jc.getFieldInfoName(methodIndex);
1341 char[] returnType = { 'V' };
1342 StringBuilder cnt = new StringBuilder();
1343 String mn = findMethodName(mi, cnt, returnType);
1345 final int numArguments = isStatic ? cnt.length() : cnt.length() + 1;
1346 final Variable[] vars = new Variable[numArguments];
1348 for (int j = numArguments - 1; j >= 0; --j) {
1349 vars[j] = mapper.pop();
1352 if (returnType[0] != 'V') {
1353 out.append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1357 final String in = mi[0];
1358 out.append(accessClass(in.replace('/', '_')));
1359 out.append("(false).");
1360 if (mn.startsWith("cons_")) {
1361 out.append("constructor.");
1367 out.append(".call(");
1369 if (numArguments > 0) {
1370 out.append(vars[0]);
1371 for (int j = 1; j < numArguments; ++j) {
1373 out.append(vars[j]);
1381 private int invokeVirtualMethod(byte[] byteCodes, int i, final StackMapper mapper)
1382 throws IOException {
1383 int methodIndex = readIntArg(byteCodes, i);
1384 String[] mi = jc.getFieldInfoName(methodIndex);
1385 char[] returnType = { 'V' };
1386 StringBuilder cnt = new StringBuilder();
1387 String mn = findMethodName(mi, cnt, returnType);
1389 final int numArguments = cnt.length() + 1;
1390 final Variable[] vars = new Variable[numArguments];
1392 for (int j = numArguments - 1; j >= 0; --j) {
1393 vars[j] = mapper.pop();
1396 if (returnType[0] != 'V') {
1397 out.append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1401 out.append(vars[0]).append('.');
1405 for (int j = 1; j < numArguments; ++j) {
1407 out.append(vars[j]);
1415 private void addReference(String cn) throws IOException {
1416 if (requireReference(cn)) {
1417 debug(" /* needs " + cn + " */");
1421 private void outType(String d, StringBuilder out) {
1423 while (d.charAt(0) == '[') {
1427 if (d.charAt(0) == 'L') {
1428 assert d.charAt(d.length() - 1) == ';';
1429 out.append(d.replace('/', '_').substring(0, d.length() - 1));
1435 private String encodeConstant(int entryIndex) throws IOException {
1436 String[] classRef = { null };
1437 String s = jc.stringValue(entryIndex, classRef);
1438 if (classRef[0] != null) {
1439 addReference(classRef[0]);
1440 s = accessClass(s.replace('/', '_')) + "(false).constructor.$class";
1445 private String javaScriptBody(String prefix, MethodData m, boolean isStatic) throws IOException {
1446 byte[] arr = m.findAnnotationData(true);
1450 final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
1451 class P extends AnnotationParser {
1457 String[] args = new String[30];
1461 protected void visitAttr(String type, String attr, String at, String value) {
1462 if (type.equals(jvmType)) {
1463 if ("body".equals(attr)) {
1465 } else if ("args".equals(attr)) {
1466 args[cnt++] = value;
1468 throw new IllegalArgumentException(attr);
1475 if (p.body == null) {
1478 StringBuilder cnt = new StringBuilder();
1479 final String mn = findMethodName(m, cnt);
1480 out.append(prefix).append(mn);
1481 out.append(" = function(");
1484 for (int i = 0; i < cnt.length(); i++) {
1486 space = outputArg(out, p.args, index);
1489 out.append(") {").append("\n");
1491 out.append("\n}\n");
1494 private static String className(ClassData jc) {
1495 //return jc.getName().getInternalName().replace('/', '_');
1496 return jc.getClassName().replace('/', '_');
1499 private static String[] findAnnotation(
1500 byte[] arr, ClassData cd, final String className,
1501 final String... attrNames
1502 ) throws IOException {
1506 final String[] values = new String[attrNames.length];
1507 final boolean[] found = { false };
1508 final String jvmType = "L" + className.replace('.', '/') + ";";
1509 AnnotationParser ap = new AnnotationParser(false) {
1511 protected void visitAttr(String type, String attr, String at, String value) {
1512 if (type.equals(jvmType)) {
1514 for (int i = 0; i < attrNames.length; i++) {
1515 if (attrNames[i].equals(attr)) {
1524 return found[0] ? values : null;
1527 private CharSequence initField(FieldData v) {
1528 final String is = v.getInternalSig();
1529 if (is.length() == 1) {
1530 switch (is.charAt(0)) {
1536 case 'I': return " = 0;";
1538 case 'D': return " = 0.0;";
1540 throw new IllegalStateException(is);
1546 private static void generateAnno(ClassData cd, final Appendable out, byte[] data) throws IOException {
1547 AnnotationParser ap = new AnnotationParser(true) {
1552 protected void visitAnnotationStart(String type) throws IOException {
1556 out.append('"').append(type).append("\" : {\n");
1561 protected void visitAnnotationEnd(String type) throws IOException {
1562 out.append("\n}\n");
1566 protected void visitAttr(String type, String attr, String attrType, String value)
1567 throws IOException {
1574 out.append(attr).append("__").append(attrType).append(" : ").append(value);
1580 private static String outputArg(Appendable out, String[] args, int indx) throws IOException {
1581 final String name = args[indx];
1585 if (name.contains(",")) {
1586 throw new IOException("Wrong parameter with ',': " + name);
1592 private static void emit(final Appendable out,
1593 final String format,
1594 final CharSequence... params) throws IOException {
1595 final int length = format.length();
1598 int paramOffset = format.indexOf('@');
1599 while ((paramOffset != -1) && (paramOffset < (length - 1))) {
1600 final char paramChar = format.charAt(paramOffset + 1);
1601 if ((paramChar >= '1') && (paramChar <= '9')) {
1602 final int paramIndex = paramChar - '0' - 1;
1604 out.append(format, processed, paramOffset);
1605 out.append(params[paramIndex]);
1608 processed = paramOffset + 1;
1611 paramOffset = format.indexOf('@', paramOffset + 1);
1614 out.append(format, processed, length);
1617 private void generateCatch(TrapData[] traps) throws IOException {
1618 out.append("} catch (e) {\n");
1620 for (TrapData e : traps) {
1624 if (e.catch_cpx != 0) { //not finally
1625 final String classInternalName = jc.getClassName(e.catch_cpx);
1626 addReference(classInternalName);
1627 if ("java/lang/Throwable".equals(classInternalName)) {
1628 out.append("if (e.$instOf_java_lang_Throwable) {");
1629 out.append(" stA0 = e;");
1630 out.append("} else {");
1631 out.append(" stA0 = vm.java_lang_Throwable(true);");
1632 out.append(" vm.java_lang_Throwable.cons__VLjava_lang_String_2.call(stA0, e.toString());");
1634 out.append("gt=" + e.handler_pc + "; continue;");
1636 out.append("if (e.$instOf_" + classInternalName.replace('/', '_') + ") {");
1637 out.append("gt=" + e.handler_pc + "; stA0 = e; continue;");
1641 finallyPC = e.handler_pc;
1644 if (finallyPC == -1) {
1645 out.append("throw e;");
1647 out.append("gt=" + finallyPC + "; stA0 = e; continue;");