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.bck2brwsr.core.JavaScriptBody;
23 import org.apidesign.javap.AnnotationParser;
24 import org.apidesign.javap.ClassData;
25 import org.apidesign.javap.FieldData;
26 import org.apidesign.javap.MethodData;
27 import org.apidesign.javap.StackMapIterator;
28 import static org.apidesign.javap.RuntimeConstants.*;
29 import org.apidesign.javap.TrapData;
30 import org.apidesign.javap.TrapDataIterator;
32 /** Translator of the code inside class files to JavaScript.
34 * @author Jaroslav Tulach <jtulach@netbeans.org>
36 abstract class ByteCodeToJavaScript {
40 protected ByteCodeToJavaScript(Appendable out) {
44 /* Collects additional required resources.
46 * @param internalClassName classes that were referenced and should be loaded in order the
47 * generated JavaScript code works properly. The names are in internal
48 * JVM form so String is <code>java/lang/String</code>.
50 protected abstract boolean requireReference(String internalClassName);
53 * @param resourcePath name of resources to read
55 protected abstract void requireScript(String resourcePath);
57 /** Allows subclasses to redefine what field a function representing a
58 * class gets assigned. By default it returns the suggested name followed
59 * by <code>" = "</code>;
61 * @param className suggested name of the class
63 /* protected */ String assignClass(String className) {
64 return className + " = ";
66 /* protected */ String accessClass(String classOperation) {
67 return classOperation;
70 /** Prints out a debug message.
72 * @param msg the message
73 * @return true if the message has been printed
76 boolean debug(String msg) throws IOException {
82 * Converts a given class file to a JavaScript version.
84 * @param classFile input stream with code of the .class file
85 * @return the initialization code for this class, if any. Otherwise <code>null</code>
87 * @throws IOException if something goes wrong during read or write or translating
90 public String compile(InputStream classFile) throws IOException {
91 this.jc = new ClassData(classFile);
92 if (jc.getMajor_version() < 50) {
93 throw new IOException("Can't compile " + jc.getClassName() + ". Class file version " + jc.getMajor_version() + "."
94 + jc.getMinor_version() + " - recompile with -target 1.6 (at least)."
97 byte[] arrData = jc.findAnnotationData(true);
98 String[] arr = findAnnotation(arrData, jc,
99 "org.apidesign.bck2brwsr.core.ExtraJavaScript",
100 "resource", "processByteCode"
103 requireScript(arr[0]);
104 if ("0".equals(arr[1])) {
108 String[] proto = findAnnotation(arrData, jc,
109 "org.apidesign.bck2brwsr.core.JavaScriptPrototype",
110 "container", "prototype"
112 StringArray toInitilize = new StringArray();
113 final String className = className(jc);
114 out.append("\n\n").append(assignClass(className));
115 out.append("function CLS() {");
116 out.append("\n if (!CLS.prototype.$instOf_").append(className).append(") {");
117 for (FieldData v : jc.getFields()) {
119 out.append("\n CLS.").append(v.getName()).append(initField(v));
123 String sc = jc.getSuperClassName(); // with _
124 out.append("\n var pp = ").
125 append(accessClass(sc.replace('/', '_'))).append("(true);");
126 out.append("\n var p = CLS.prototype = pp;");
127 out.append("\n var c = p;");
128 out.append("\n var sprcls = pp.constructor.$class;");
130 out.append("\n var p = CLS.prototype = ").append(proto[1]).append(";");
131 if (proto[0] == null) {
134 out.append("\n var c = ").append(proto[0]).append(";");
135 out.append("\n var sprcls = null;");
137 for (MethodData m : jc.getMethods()) {
138 byte[] onlyArr = m.findAnnotationData(true);
139 String[] only = findAnnotation(onlyArr, jc,
140 "org.apidesign.bck2brwsr.core.JavaScriptOnly",
144 if (only[0] != null && only[1] != null) {
145 out.append("\n p.").append(only[0]).append(" = ")
146 .append(only[1]).append(";");
154 mn = generateStaticMethod(prefix, m, toInitilize);
156 if (m.isConstructor()) {
158 mn = generateInstanceMethod(prefix, m);
161 mn = generateInstanceMethod(prefix, m);
164 byte[] runAnno = m.findAnnotationData(false);
165 if (runAnno != null) {
166 out.append(prefix).append(mn).append(".anno = {");
167 generateAnno(jc, out, runAnno);
170 out.append(prefix).append(mn).append(".access = " + m.getAccess()).append(";");
172 out.append("\n c.constructor = CLS;");
173 out.append("\n c.$instOf_").append(className).append(" = true;");
174 for (String superInterface : jc.getSuperInterfaces()) {
175 out.append("\n c.$instOf_").append(superInterface.replace('/', '_')).append(" = true;");
177 out.append("\n CLS.$class = ");
178 out.append(accessClass("java_lang_Class(true);"));
179 out.append("\n CLS.$class.jvmName = '").append(jc.getClassName()).append("';");
180 out.append("\n CLS.$class.superclass = sprcls;");
181 out.append("\n CLS.$class.access = ").append(jc.getAccessFlags()+";");
182 out.append("\n CLS.$class.cnstr = CLS;");
183 byte[] classAnno = jc.findAnnotationData(false);
184 if (classAnno != null) {
185 out.append("\n CLS.$class.anno = {");
186 generateAnno(jc, out, classAnno);
190 out.append("\n if (arguments.length === 0) {");
191 out.append("\n if (!(this instanceof CLS)) {");
192 out.append("\n return new CLS();");
194 for (FieldData v : jc.getFields()) {
195 byte[] onlyArr = v.findAnnotationData(true);
196 String[] only = findAnnotation(onlyArr, jc,
197 "org.apidesign.bck2brwsr.core.JavaScriptOnly",
201 if (only[0] != null && only[1] != null) {
202 out.append("\n p.").append(only[0]).append(" = ")
203 .append(only[1]).append(";");
208 out.append("\n this.fld_").
209 append(v.getName()).append(initField(v));
212 out.append("\n return this;");
214 out.append("\n return arguments[0] ? new CLS() : CLS.prototype;");
216 StringBuilder sb = new StringBuilder();
217 for (String init : toInitilize.toArray()) {
218 sb.append("\n").append(init).append("();");
220 return sb.toString();
222 private String generateStaticMethod(String prefix, MethodData m, StringArray toInitilize) throws IOException {
223 String jsb = javaScriptBody(prefix, m, true);
227 final String mn = findMethodName(m, new StringBuilder());
228 if (mn.equals("class__V")) {
229 toInitilize.add(accessClass(className(jc)) + "(false)." + mn);
231 generateMethod(prefix, mn, m);
235 private String generateInstanceMethod(String prefix, MethodData m) throws IOException {
236 String jsb = javaScriptBody(prefix, m, false);
240 final String mn = findMethodName(m, new StringBuilder());
241 generateMethod(prefix, mn, m);
245 private void generateMethod(String prefix, String name, MethodData m)
247 final StackMapIterator stackMapIterator = m.createStackMapIterator();
248 TrapDataIterator trap = m.getTrapDataIterator();
249 final LocalsMapper lmapper =
250 new LocalsMapper(stackMapIterator.getArguments());
252 out.append(prefix).append(name).append(" = function(");
253 lmapper.outputArguments(out, m.isStatic());
254 out.append(") {").append("\n");
256 final byte[] byteCodes = m.getCode();
257 if (byteCodes == null) {
258 out.append(" throw 'no code found for ")
259 .append(jc.getClassName()).append('.')
260 .append(m.getName()).append("';\n");
265 final StackMapper smapper = new StackMapper();
267 final int maxLocals = m.getMaxLocals();
269 // TODO: generate only used local variables
270 for (int j = 0; j <= VarType.LAST; ++j) {
271 out.append("\n var ").append(Variable.getLocalVariable(j, 0));
272 for (int i = 1; i < maxLocals; ++i) {
274 out.append(Variable.getLocalVariable(j, i));
280 out.append(" var ").append(" lcA0 = this;\n");
283 // maxStack includes two stack positions for every pushed long / double
284 // so this might generate more stack variables than we need
285 final int maxStack = m.getMaxStack();
287 // TODO: generate only used stack variables
288 for (int j = 0; j <= VarType.LAST; ++j) {
289 out.append("\n var ").append(Variable.getStackVariable(j, 0));
290 for (int i = 1; i < maxStack; ++i) {
292 out.append(Variable.getStackVariable(j, i));
298 int lastStackFrame = -1;
299 TrapData[] previousTrap = null;
301 out.append("\n var gt = 0;\n for(;;) switch(gt) {\n");
302 for (int i = 0; i < byteCodes.length; i++) {
304 stackMapIterator.advanceTo(i);
305 boolean changeInCatch = trap.advanceTo(i);
306 if (changeInCatch || lastStackFrame != stackMapIterator.getFrameIndex()) {
307 if (previousTrap != null) {
308 generateCatch(previousTrap);
312 if (lastStackFrame != stackMapIterator.getFrameIndex()) {
313 lastStackFrame = stackMapIterator.getFrameIndex();
314 lmapper.syncWithFrameLocals(stackMapIterator.getFrameLocals());
315 smapper.syncWithFrameStack(stackMapIterator.getFrameStack());
316 out.append(" case " + i).append(": ");
317 changeInCatch = true;
319 debug(" /* " + i + " */ ");
321 if (changeInCatch && trap.useTry()) {
323 previousTrap = trap.current();
325 final int c = readByte(byteCodes, i);
328 emit(out, "@1 = @2;", smapper.pushA(), lmapper.getA(0));
331 emit(out, "@1 = @2;", smapper.pushI(), lmapper.getI(0));
334 emit(out, "@1 = @2;", smapper.pushL(), lmapper.getL(0));
337 emit(out, "@1 = @2;", smapper.pushF(), lmapper.getF(0));
340 emit(out, "@1 = @2;", smapper.pushD(), lmapper.getD(0));
343 emit(out, "@1 = @2;", smapper.pushA(), lmapper.getA(1));
346 emit(out, "@1 = @2;", smapper.pushI(), lmapper.getI(1));
349 emit(out, "@1 = @2;", smapper.pushL(), lmapper.getL(1));
352 emit(out, "@1 = @2;", smapper.pushF(), lmapper.getF(1));
355 emit(out, "@1 = @2;", smapper.pushD(), lmapper.getD(1));
358 emit(out, "@1 = @2;", smapper.pushA(), lmapper.getA(2));
361 emit(out, "@1 = @2;", smapper.pushI(), lmapper.getI(2));
364 emit(out, "@1 = @2;", smapper.pushL(), lmapper.getL(2));
367 emit(out, "@1 = @2;", smapper.pushF(), lmapper.getF(2));
370 emit(out, "@1 = @2;", smapper.pushD(), lmapper.getD(2));
373 emit(out, "@1 = @2;", smapper.pushA(), lmapper.getA(3));
376 emit(out, "@1 = @2;", smapper.pushI(), lmapper.getI(3));
379 emit(out, "@1 = @2;", smapper.pushL(), lmapper.getL(3));
382 emit(out, "@1 = @2;", smapper.pushF(), lmapper.getF(3));
385 emit(out, "@1 = @2;", smapper.pushD(), lmapper.getD(3));
388 final int indx = readByte(byteCodes, ++i);
389 emit(out, "@1 = @2;", smapper.pushI(), lmapper.getI(indx));
393 final int indx = readByte(byteCodes, ++i);
394 emit(out, "@1 = @2;", smapper.pushL(), lmapper.getL(indx));
398 final int indx = readByte(byteCodes, ++i);
399 emit(out, "@1 = @2;", smapper.pushF(), lmapper.getF(indx));
403 final int indx = readByte(byteCodes, ++i);
404 emit(out, "@1 = @2;", smapper.pushD(), lmapper.getD(indx));
408 final int indx = readByte(byteCodes, ++i);
409 emit(out, "@1 = @2;", smapper.pushA(), lmapper.getA(indx));
413 final int indx = readByte(byteCodes, ++i);
414 emit(out, "@1 = @2;", lmapper.setI(indx), smapper.popI());
418 final int indx = readByte(byteCodes, ++i);
419 emit(out, "@1 = @2;", lmapper.setL(indx), smapper.popL());
423 final int indx = readByte(byteCodes, ++i);
424 emit(out, "@1 = @2;", lmapper.setF(indx), smapper.popF());
428 final int indx = readByte(byteCodes, ++i);
429 emit(out, "@1 = @2;", lmapper.setD(indx), smapper.popD());
433 final int indx = readByte(byteCodes, ++i);
434 emit(out, "@1 = @2;", lmapper.setA(indx), smapper.popA());
438 emit(out, "@1 = @2;", lmapper.setA(0), smapper.popA());
441 emit(out, "@1 = @2;", lmapper.setI(0), smapper.popI());
444 emit(out, "@1 = @2;", lmapper.setL(0), smapper.popL());
447 emit(out, "@1 = @2;", lmapper.setF(0), smapper.popF());
450 emit(out, "@1 = @2;", lmapper.setD(0), smapper.popD());
453 emit(out, "@1 = @2;", lmapper.setA(1), smapper.popA());
456 emit(out, "@1 = @2;", lmapper.setI(1), smapper.popI());
459 emit(out, "@1 = @2;", lmapper.setL(1), smapper.popL());
462 emit(out, "@1 = @2;", lmapper.setF(1), smapper.popF());
465 emit(out, "@1 = @2;", lmapper.setD(1), smapper.popD());
468 emit(out, "@1 = @2;", lmapper.setA(2), smapper.popA());
471 emit(out, "@1 = @2;", lmapper.setI(2), smapper.popI());
474 emit(out, "@1 = @2;", lmapper.setL(2), smapper.popL());
477 emit(out, "@1 = @2;", lmapper.setF(2), smapper.popF());
480 emit(out, "@1 = @2;", lmapper.setD(2), smapper.popD());
483 emit(out, "@1 = @2;", lmapper.setA(3), smapper.popA());
486 emit(out, "@1 = @2;", lmapper.setI(3), smapper.popI());
489 emit(out, "@1 = @2;", lmapper.setL(3), smapper.popL());
492 emit(out, "@1 = @2;", lmapper.setF(3), smapper.popF());
495 emit(out, "@1 = @2;", lmapper.setD(3), smapper.popD());
498 emit(out, "@1 = @1.add32(@2);", smapper.getI(1), smapper.popI());
501 emit(out, "@1 += @2;", smapper.getL(1), smapper.popL());
504 emit(out, "@1 += @2;", smapper.getF(1), smapper.popF());
507 emit(out, "@1 += @2;", smapper.getD(1), smapper.popD());
510 emit(out, "@1 = @1.sub32(@2);", smapper.getI(1), smapper.popI());
513 emit(out, "@1 -= @2;", smapper.getL(1), smapper.popL());
516 emit(out, "@1 -= @2;", smapper.getF(1), smapper.popF());
519 emit(out, "@1 -= @2;", smapper.getD(1), smapper.popD());
522 emit(out, "@1 = @1.mul32(@2);", smapper.getI(1), smapper.popI());
525 emit(out, "@1 *= @2;", smapper.getL(1), smapper.popL());
528 emit(out, "@1 *= @2;", smapper.getF(1), smapper.popF());
531 emit(out, "@1 *= @2;", smapper.getD(1), smapper.popD());
534 emit(out, "@1 = Math.floor(@1 / @2);",
535 smapper.getI(1), smapper.popI());
538 emit(out, "@1 = Math.floor(@1 / @2);",
539 smapper.getL(1), smapper.popL());
542 emit(out, "@1 /= @2;", smapper.getF(1), smapper.popF());
545 emit(out, "@1 /= @2;", smapper.getD(1), smapper.popD());
548 emit(out, "@1 %= @2;", smapper.getI(1), smapper.popI());
551 emit(out, "@1 %= @2;", smapper.getL(1), smapper.popL());
554 emit(out, "@1 %= @2;", smapper.getF(1), smapper.popF());
557 emit(out, "@1 %= @2;", smapper.getD(1), smapper.popD());
560 emit(out, "@1 &= @2;", smapper.getI(1), smapper.popI());
563 emit(out, "@1 &= @2;", smapper.getL(1), smapper.popL());
566 emit(out, "@1 |= @2;", smapper.getI(1), smapper.popI());
569 emit(out, "@1 |= @2;", smapper.getL(1), smapper.popL());
572 emit(out, "@1 ^= @2;", smapper.getI(1), smapper.popI());
575 emit(out, "@1 ^= @2;", smapper.getL(1), smapper.popL());
578 emit(out, "@1 = -@1;", smapper.getI(0));
581 emit(out, "@1 = -@1;", smapper.getL(0));
584 emit(out, "@1 = -@1;", smapper.getF(0));
587 emit(out, "@1 = -@1;", smapper.getD(0));
590 emit(out, "@1 <<= @2;", smapper.getI(1), smapper.popI());
593 emit(out, "@1 <<= @2;", smapper.getL(1), smapper.popI());
596 emit(out, "@1 >>= @2;", smapper.getI(1), smapper.popI());
599 emit(out, "@1 >>= @2;", smapper.getL(1), smapper.popI());
602 emit(out, "@1 >>>= @2;", smapper.getI(1), smapper.popI());
605 emit(out, "@1 >>>= @2;", smapper.getL(1), smapper.popI());
608 final int varIndx = readByte(byteCodes, ++i);
609 final int incrBy = byteCodes[++i];
611 emit(out, "@1++;", lmapper.getI(varIndx));
613 emit(out, "@1 += @2;",
614 lmapper.getI(varIndx),
615 Integer.toString(incrBy));
620 emit(out, "return;");
623 emit(out, "return @1;", smapper.popI());
626 emit(out, "return @1;", smapper.popL());
629 emit(out, "return @1;", smapper.popF());
632 emit(out, "return @1;", smapper.popD());
635 emit(out, "return @1;", smapper.popA());
638 emit(out, "@2 = @1;", smapper.popI(), smapper.pushL());
641 emit(out, "@2 = @1;", smapper.popI(), smapper.pushF());
644 emit(out, "@2 = @1;", smapper.popI(), smapper.pushD());
647 emit(out, "@2 = @1;", smapper.popL(), smapper.pushI());
651 emit(out, "@2 = @1;", smapper.popL(), smapper.pushF());
654 emit(out, "@2 = @1;", smapper.popL(), smapper.pushD());
657 emit(out, "@2 = @1;", smapper.popF(), smapper.pushD());
660 emit(out, "@2 = @1;", smapper.popD(), smapper.pushF());
663 emit(out, "@2 = Math.floor(@1);",
664 smapper.popF(), smapper.pushI());
667 emit(out, "@2 = Math.floor(@1);",
668 smapper.popF(), smapper.pushL());
671 emit(out, "@2 = Math.floor(@1);",
672 smapper.popD(), smapper.pushI());
675 emit(out, "@2 = Math.floor(@1);",
676 smapper.popD(), smapper.pushL());
679 emit(out, "@1 = @1.toInt8();", smapper.getI(0));
682 out.append("{ /* number conversion */ }");
685 emit(out, "@1 = @1.toInt16();", smapper.getI(0));
687 case opc_aconst_null:
688 emit(out, "@1 = null;", smapper.pushA());
691 emit(out, "@1 = -1;", smapper.pushI());
694 emit(out, "@1 = 0;", smapper.pushI());
697 emit(out, "@1 = 0;", smapper.pushD());
700 emit(out, "@1 = 0;", smapper.pushL());
703 emit(out, "@1 = 0;", smapper.pushF());
706 emit(out, "@1 = 1;", smapper.pushI());
709 emit(out, "@1 = 1;", smapper.pushL());
712 emit(out, "@1 = 1;", smapper.pushF());
715 emit(out, "@1 = 1;", smapper.pushD());
718 emit(out, "@1 = 2;", smapper.pushI());
721 emit(out, "@1 = 2;", smapper.pushF());
724 emit(out, "@1 = 3;", smapper.pushI());
727 emit(out, "@1 = 4;", smapper.pushI());
730 emit(out, "@1 = 5;", smapper.pushI());
733 int indx = readByte(byteCodes, ++i);
734 String v = encodeConstant(indx);
735 int type = VarType.fromConstantType(jc.getTag(indx));
736 emit(out, "@1 = @2;", smapper.pushT(type), v);
741 int indx = readIntArg(byteCodes, i);
743 String v = encodeConstant(indx);
744 int type = VarType.fromConstantType(jc.getTag(indx));
745 emit(out, "@1 = @2;", smapper.pushT(type), v);
749 emit(out, "@3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
750 smapper.popL(), smapper.popL(), smapper.pushI());
754 emit(out, "@3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
755 smapper.popF(), smapper.popF(), smapper.pushI());
759 emit(out, "@3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
760 smapper.popD(), smapper.popD(), smapper.pushI());
763 i = generateIf(byteCodes, i, smapper.popA(), smapper.popA(),
767 i = generateIf(byteCodes, i, smapper.popA(), smapper.popA(),
771 i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
775 int indx = i + readIntArg(byteCodes, i);
776 emit(out, "if (@1 == 0) { gt = @2; continue; }",
777 smapper.popI(), Integer.toString(indx));
782 int indx = i + readIntArg(byteCodes, i);
783 emit(out, "if (@1 != 0) { gt = @2; continue; }",
784 smapper.popI(), Integer.toString(indx));
789 int indx = i + readIntArg(byteCodes, i);
790 emit(out, "if (@1 < 0) { gt = @2; continue; }",
791 smapper.popI(), Integer.toString(indx));
796 int indx = i + readIntArg(byteCodes, i);
797 emit(out, "if (@1 <= 0) { gt = @2; continue; }",
798 smapper.popI(), Integer.toString(indx));
803 int indx = i + readIntArg(byteCodes, i);
804 emit(out, "if (@1 > 0) { gt = @2; continue; }",
805 smapper.popI(), Integer.toString(indx));
810 int indx = i + readIntArg(byteCodes, i);
811 emit(out, "if (@1 >= 0) { gt = @2; continue; }",
812 smapper.popI(), Integer.toString(indx));
816 case opc_ifnonnull: {
817 int indx = i + readIntArg(byteCodes, i);
818 emit(out, "if (@1 !== null) { gt = @2; continue; }",
819 smapper.popA(), Integer.toString(indx));
824 int indx = i + readIntArg(byteCodes, i);
825 emit(out, "if (@1 === null) { gt = @2; continue; }",
826 smapper.popA(), Integer.toString(indx));
831 i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
835 i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
839 i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
843 i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
847 i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
851 int indx = i + readIntArg(byteCodes, i);
852 emit(out, "gt = @1; continue;", Integer.toString(indx));
856 case opc_lookupswitch: {
857 int table = i / 4 * 4 + 4;
858 int dflt = i + readInt4(byteCodes, table);
860 int n = readInt4(byteCodes, table);
862 out.append("switch (").append(smapper.popI()).append(") {\n");
864 int cnstnt = readInt4(byteCodes, table);
866 int offset = i + readInt4(byteCodes, table);
868 out.append(" case " + cnstnt).append(": gt = " + offset).append("; continue;\n");
870 out.append(" default: gt = " + dflt).append("; continue;\n}");
874 case opc_tableswitch: {
875 int table = i / 4 * 4 + 4;
876 int dflt = i + readInt4(byteCodes, table);
878 int low = readInt4(byteCodes, table);
880 int high = readInt4(byteCodes, table);
882 out.append("switch (").append(smapper.popI()).append(") {\n");
883 while (low <= high) {
884 int offset = i + readInt4(byteCodes, table);
886 out.append(" case " + low).append(": gt = " + offset).append("; continue;\n");
889 out.append(" default: gt = " + dflt).append("; continue;\n}");
893 case opc_invokeinterface: {
894 i = invokeVirtualMethod(byteCodes, i, smapper) + 2;
897 case opc_invokevirtual:
898 i = invokeVirtualMethod(byteCodes, i, smapper);
900 case opc_invokespecial:
901 i = invokeStaticMethod(byteCodes, i, smapper, false);
903 case opc_invokestatic:
904 i = invokeStaticMethod(byteCodes, i, smapper, true);
907 int indx = readIntArg(byteCodes, i);
908 String ci = jc.getClassName(indx);
909 emit(out, "@1 = new @2;",
910 smapper.pushA(), accessClass(ci.replace('/', '_')));
916 int atype = readByte(byteCodes, ++i);
919 case 4: jvmType = "[Z"; break;
920 case 5: jvmType = "[C"; break;
921 case 6: jvmType = "[F"; break;
922 case 7: jvmType = "[D"; break;
923 case 8: jvmType = "[B"; break;
924 case 9: jvmType = "[S"; break;
925 case 10: jvmType = "[I"; break;
926 case 11: jvmType = "[J"; break;
927 default: throw new IllegalStateException("Array type: " + atype);
929 emit(out, "@2 = Array.prototype.newArray__Ljava_lang_Object_2ZLjava_lang_String_2I(true, '@3', @1);",
930 smapper.popI(), smapper.pushA(), jvmType);
932 case opc_anewarray: {
933 int type = readIntArg(byteCodes, i);
935 String typeName = jc.getClassName(type);
936 if (typeName.startsWith("[")) {
937 typeName = "[" + typeName;
939 typeName = "[L" + typeName + ";";
941 emit(out, "@2 = Array.prototype.newArray__Ljava_lang_Object_2ZLjava_lang_String_2I(false, '@3', @1);",
942 smapper.popI(), smapper.pushA(), typeName);
945 case opc_multianewarray: {
946 int type = readIntArg(byteCodes, i);
948 String typeName = jc.getClassName(type);
949 int dim = readByte(byteCodes, ++i);
950 StringBuilder dims = new StringBuilder();
952 for (int d = 0; d < dim; d++) {
956 dims.append(smapper.popI());
959 emit(out, "@2 = Array.prototype.multiNewArray__Ljava_lang_Object_2Ljava_lang_String_2_3II('@3', @1, 0);",
960 dims.toString(), smapper.pushA(), typeName);
963 case opc_arraylength:
964 emit(out, "@2 = @1.length;", smapper.popA(), smapper.pushI());
967 emit(out, "@3.at(@2, @1);",
968 smapper.popL(), smapper.popI(), smapper.popA());
971 emit(out, "@3.at(@2, @1);",
972 smapper.popF(), smapper.popI(), smapper.popA());
975 emit(out, "@3.at(@2, @1);",
976 smapper.popD(), smapper.popI(), smapper.popA());
979 emit(out, "@3.at(@2, @1);",
980 smapper.popA(), smapper.popI(), smapper.popA());
986 emit(out, "@3.at(@2, @1);",
987 smapper.popI(), smapper.popI(), smapper.popA());
990 emit(out, "@3 = @2.at(@1);",
991 smapper.popI(), smapper.popA(), smapper.pushL());
994 emit(out, "@3 = @2.at(@1);",
995 smapper.popI(), smapper.popA(), smapper.pushF());
998 emit(out, "@3 = @2.at(@1);",
999 smapper.popI(), smapper.popA(), smapper.pushD());
1002 emit(out, "@3 = @2.at(@1);",
1003 smapper.popI(), smapper.popA(), smapper.pushA());
1009 emit(out, "@3 = @2.at(@1);",
1010 smapper.popI(), smapper.popA(), smapper.pushI());
1018 final Variable v = smapper.get(0);
1019 emit(out, "@1 = @2;", smapper.pushT(v.getType()), v);
1023 if (smapper.get(0).isCategory2()) {
1024 final Variable v = smapper.get(0);
1025 emit(out, "@1 = @2;", smapper.pushT(v.getType()), v);
1027 final Variable v1 = smapper.get(0);
1028 final Variable v2 = smapper.get(1);
1029 emit(out, "{ @1 = @2; @3 = @4; }",
1030 smapper.pushT(v2.getType()), v2,
1031 smapper.pushT(v1.getType()), v1);
1036 final Variable vi1 = smapper.pop();
1037 final Variable vi2 = smapper.pop();
1038 final Variable vo3 = smapper.pushT(vi1.getType());
1039 final Variable vo2 = smapper.pushT(vi2.getType());
1040 final Variable vo1 = smapper.pushT(vi1.getType());
1042 emit(out, "{ @1 = @2; @3 = @4; @5 = @6; }",
1043 vo1, vi1, vo2, vi2, vo3, vo1);
1047 if (smapper.get(1).isCategory2()) {
1048 final Variable vi1 = smapper.pop();
1049 final Variable vi2 = smapper.pop();
1050 final Variable vo3 = smapper.pushT(vi1.getType());
1051 final Variable vo2 = smapper.pushT(vi2.getType());
1052 final Variable vo1 = smapper.pushT(vi1.getType());
1054 emit(out, "{ @1 = @2; @3 = @4; @5 = @6; }",
1055 vo1, vi1, vo2, vi2, vo3, vo1);
1057 final Variable vi1 = smapper.pop();
1058 final Variable vi2 = smapper.pop();
1059 final Variable vi3 = smapper.pop();
1060 final Variable vo4 = smapper.pushT(vi1.getType());
1061 final Variable vo3 = smapper.pushT(vi3.getType());
1062 final Variable vo2 = smapper.pushT(vi2.getType());
1063 final Variable vo1 = smapper.pushT(vi1.getType());
1065 emit(out, "{ @1 = @2; @3 = @4; @5 = @6; @7 = @8; }",
1066 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1071 emit(out, "@1 = @2;",
1072 smapper.pushI(), Integer.toString(byteCodes[++i]));
1075 emit(out, "@1 = @2;",
1077 Integer.toString(readIntArg(byteCodes, i)));
1080 case opc_getfield: {
1081 int indx = readIntArg(byteCodes, i);
1082 String[] fi = jc.getFieldInfoName(indx);
1083 final int type = VarType.fromFieldType(fi[2].charAt(0));
1084 emit(out, "@2 = @1.fld_@3;",
1085 smapper.popA(), smapper.pushT(type), fi[1]);
1089 case opc_getstatic: {
1090 int indx = readIntArg(byteCodes, i);
1091 String[] fi = jc.getFieldInfoName(indx);
1092 final int type = VarType.fromFieldType(fi[2].charAt(0));
1093 emit(out, "@1 = @2(false).constructor.@3;",
1094 smapper.pushT(type),
1095 accessClass(fi[0].replace('/', '_')), fi[1]);
1097 addReference(fi[0]);
1100 case opc_putfield: {
1101 int indx = readIntArg(byteCodes, i);
1102 String[] fi = jc.getFieldInfoName(indx);
1103 final int type = VarType.fromFieldType(fi[2].charAt(0));
1104 emit(out, "@2.fld_@3 = @1;",
1105 smapper.popT(type), smapper.popA(), fi[1]);
1109 case opc_putstatic: {
1110 int indx = readIntArg(byteCodes, i);
1111 String[] fi = jc.getFieldInfoName(indx);
1112 final int type = VarType.fromFieldType(fi[2].charAt(0));
1113 emit(out, "@1(false).constructor.@2 = @3;",
1114 accessClass(fi[0].replace('/', '_')), fi[1],
1115 smapper.popT(type));
1117 addReference(fi[0]);
1120 case opc_checkcast: {
1121 int indx = readIntArg(byteCodes, i);
1122 final String type = jc.getClassName(indx);
1123 if (!type.startsWith("[")) {
1124 // no way to check arrays right now
1125 // XXX proper exception
1127 "if (@1 !== null && !@1.$instOf_@2) throw {};",
1128 smapper.getA(0), type.replace('/', '_'));
1133 case opc_instanceof: {
1134 int indx = readIntArg(byteCodes, i);
1135 final String type = jc.getClassName(indx);
1136 emit(out, "@2 = @1.$instOf_@3 ? 1 : 0;",
1137 smapper.popA(), smapper.pushI(),
1138 type.replace('/', '_'));
1143 final Variable v = smapper.popA();
1146 emit(out, "{ @1 = @2; throw @2; }",
1147 smapper.pushA(), v);
1151 case opc_monitorenter: {
1152 out.append("/* monitor enter */");
1157 case opc_monitorexit: {
1158 out.append("/* monitor exit */");
1164 emit(out, "throw 'unknown bytecode @1';",
1165 Integer.toString(c));
1169 for (int j = prev; j <= i; j++) {
1171 final int cc = readByte(byteCodes, j);
1172 out.append(Integer.toString(cc));
1177 if (previousTrap != null) {
1178 generateCatch(previousTrap);
1184 private int generateIf(byte[] byteCodes, int i,
1185 final Variable v2, final Variable v1,
1186 final String test) throws IOException {
1187 int indx = i + readIntArg(byteCodes, i);
1188 out.append("if (").append(v1)
1189 .append(' ').append(test).append(' ')
1190 .append(v2).append(") { gt = " + indx)
1191 .append("; continue; }");
1195 private int readIntArg(byte[] byteCodes, int offsetInstruction) {
1196 final int indxHi = byteCodes[offsetInstruction + 1] << 8;
1197 final int indxLo = byteCodes[offsetInstruction + 2];
1198 return (indxHi & 0xffffff00) | (indxLo & 0xff);
1200 private int readInt4(byte[] byteCodes, int offsetInstruction) {
1201 final int d = byteCodes[offsetInstruction + 0] << 24;
1202 final int c = byteCodes[offsetInstruction + 1] << 16;
1203 final int b = byteCodes[offsetInstruction + 2] << 8;
1204 final int a = byteCodes[offsetInstruction + 3];
1205 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
1207 private int readByte(byte[] byteCodes, int offsetInstruction) {
1208 return byteCodes[offsetInstruction] & 0xff;
1211 private static void countArgs(String descriptor, char[] returnType, StringBuilder sig, StringBuilder cnt) {
1213 Boolean count = null;
1214 boolean array = false;
1216 int firstPos = sig.length();
1217 while (i < descriptor.length()) {
1218 char ch = descriptor.charAt(i++);
1239 if (ch == 'J' || ch == 'D') {
1245 sig.insert(firstPos, ch);
1247 returnType[0] = '[';
1248 sig.insert(firstPos, "_3");
1257 returnType[0] = 'V';
1258 sig.insert(firstPos, 'V');
1261 int next = descriptor.indexOf(';', i);
1262 String realSig = mangleSig(descriptor, i - 1, next + 1);
1267 sig.append(realSig);
1270 sig.insert(firstPos, realSig);
1272 sig.insert(firstPos, "_3");
1274 returnType[0] = 'L';
1283 throw new IllegalStateException("Invalid char: " + ch);
1288 private static String mangleSig(String txt, int first, int last) {
1289 StringBuilder sb = new StringBuilder();
1290 for (int i = first; i < last; i++) {
1291 final char ch = txt.charAt(i);
1293 case '/': sb.append('_'); break;
1294 case '_': sb.append("_1"); break;
1295 case ';': sb.append("_2"); break;
1296 case '[': sb.append("_3"); break;
1297 default: sb.append(ch); break;
1300 return sb.toString();
1303 private static String findMethodName(MethodData m, StringBuilder cnt) {
1304 StringBuilder name = new StringBuilder();
1305 if ("<init>".equals(m.getName())) { // NOI18N
1306 name.append("cons"); // NOI18N
1307 } else if ("<clinit>".equals(m.getName())) { // NOI18N
1308 name.append("class"); // NOI18N
1310 name.append(m.getName());
1313 countArgs(m.getInternalSig(), new char[1], name, cnt);
1314 return name.toString();
1317 static String findMethodName(String[] mi, StringBuilder cnt, char[] returnType) {
1318 StringBuilder name = new StringBuilder();
1319 String descr = mi[2];//mi.getDescriptor();
1321 if ("<init>".equals(nm)) { // NOI18N
1322 name.append("cons"); // NOI18N
1326 countArgs(descr, returnType, name, cnt);
1327 return name.toString();
1330 private int invokeStaticMethod(byte[] byteCodes, int i, final StackMapper mapper, boolean isStatic)
1331 throws IOException {
1332 int methodIndex = readIntArg(byteCodes, i);
1333 String[] mi = jc.getFieldInfoName(methodIndex);
1334 char[] returnType = { 'V' };
1335 StringBuilder cnt = new StringBuilder();
1336 String mn = findMethodName(mi, cnt, returnType);
1338 final int numArguments = isStatic ? cnt.length() : cnt.length() + 1;
1339 final Variable[] vars = new Variable[numArguments];
1341 for (int j = numArguments - 1; j >= 0; --j) {
1342 vars[j] = mapper.pop();
1345 if (returnType[0] != 'V') {
1346 out.append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1350 final String in = mi[0];
1351 out.append(accessClass(in.replace('/', '_')));
1352 out.append("(false).");
1353 if (mn.startsWith("cons_")) {
1354 out.append("constructor.");
1360 out.append(".call(");
1362 if (numArguments > 0) {
1363 out.append(vars[0]);
1364 for (int j = 1; j < numArguments; ++j) {
1366 out.append(vars[j]);
1374 private int invokeVirtualMethod(byte[] byteCodes, int i, final StackMapper mapper)
1375 throws IOException {
1376 int methodIndex = readIntArg(byteCodes, i);
1377 String[] mi = jc.getFieldInfoName(methodIndex);
1378 char[] returnType = { 'V' };
1379 StringBuilder cnt = new StringBuilder();
1380 String mn = findMethodName(mi, cnt, returnType);
1382 final int numArguments = cnt.length() + 1;
1383 final Variable[] vars = new Variable[numArguments];
1385 for (int j = numArguments - 1; j >= 0; --j) {
1386 vars[j] = mapper.pop();
1389 if (returnType[0] != 'V') {
1390 out.append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1394 out.append(vars[0]).append('.');
1398 for (int j = 1; j < numArguments; ++j) {
1400 out.append(vars[j]);
1408 private void addReference(String cn) throws IOException {
1409 if (requireReference(cn)) {
1410 debug(" /* needs " + cn + " */");
1414 private void outType(String d, StringBuilder out) {
1416 while (d.charAt(0) == '[') {
1420 if (d.charAt(0) == 'L') {
1421 assert d.charAt(d.length() - 1) == ';';
1422 out.append(d.replace('/', '_').substring(0, d.length() - 1));
1428 private String encodeConstant(int entryIndex) throws IOException {
1429 String[] classRef = { null };
1430 String s = jc.stringValue(entryIndex, classRef);
1431 if (classRef[0] != null) {
1432 addReference(classRef[0]);
1433 s = accessClass(s.replace('/', '_')) + "(false).constructor.$class";
1438 private String javaScriptBody(String prefix, MethodData m, boolean isStatic) throws IOException {
1439 byte[] arr = m.findAnnotationData(true);
1443 final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
1444 class P extends AnnotationParser {
1450 String[] args = new String[30];
1454 protected void visitAttr(String type, String attr, String at, String value) {
1455 if (type.equals(jvmType)) {
1456 if ("body".equals(attr)) {
1458 } else if ("args".equals(attr)) {
1459 args[cnt++] = value;
1461 throw new IllegalArgumentException(attr);
1468 if (p.body == null) {
1471 StringBuilder cnt = new StringBuilder();
1472 final String mn = findMethodName(m, cnt);
1473 out.append(prefix).append(mn);
1474 out.append(" = function(");
1477 for (int i = 0; i < cnt.length(); i++) {
1479 space = outputArg(out, p.args, index);
1482 out.append(") {").append("\n");
1484 out.append("\n}\n");
1487 private static String className(ClassData jc) {
1488 //return jc.getName().getInternalName().replace('/', '_');
1489 return jc.getClassName().replace('/', '_');
1492 private static String[] findAnnotation(
1493 byte[] arr, ClassData cd, final String className,
1494 final String... attrNames
1495 ) throws IOException {
1499 final String[] values = new String[attrNames.length];
1500 final boolean[] found = { false };
1501 final String jvmType = "L" + className.replace('.', '/') + ";";
1502 AnnotationParser ap = new AnnotationParser(false) {
1504 protected void visitAttr(String type, String attr, String at, String value) {
1505 if (type.equals(jvmType)) {
1507 for (int i = 0; i < attrNames.length; i++) {
1508 if (attrNames[i].equals(attr)) {
1517 return found[0] ? values : null;
1520 private CharSequence initField(FieldData v) {
1521 final String is = v.getInternalSig();
1522 if (is.length() == 1) {
1523 switch (is.charAt(0)) {
1529 case 'I': return " = 0;";
1531 case 'D': return " = 0.0;";
1533 throw new IllegalStateException(is);
1539 private static void generateAnno(ClassData cd, final Appendable out, byte[] data) throws IOException {
1540 AnnotationParser ap = new AnnotationParser(true) {
1545 protected void visitAnnotationStart(String type) throws IOException {
1549 out.append('"').append(type).append("\" : {\n");
1554 protected void visitAnnotationEnd(String type) throws IOException {
1555 out.append("\n}\n");
1559 protected void visitAttr(String type, String attr, String attrType, String value)
1560 throws IOException {
1567 out.append(attr).append("__").append(attrType).append(" : ").append(value);
1573 private static String outputArg(Appendable out, String[] args, int indx) throws IOException {
1574 final String name = args[indx];
1578 if (name.contains(",")) {
1579 throw new IOException("Wrong parameter with ',': " + name);
1585 private static void emit(final Appendable out,
1586 final String format,
1587 final CharSequence... params) throws IOException {
1588 final int length = format.length();
1591 int paramOffset = format.indexOf('@');
1592 while ((paramOffset != -1) && (paramOffset < (length - 1))) {
1593 final char paramChar = format.charAt(paramOffset + 1);
1594 if ((paramChar >= '1') && (paramChar <= '9')) {
1595 final int paramIndex = paramChar - '0' - 1;
1597 out.append(format, processed, paramOffset);
1598 out.append(params[paramIndex]);
1601 processed = paramOffset + 1;
1604 paramOffset = format.indexOf('@', paramOffset + 1);
1607 out.append(format, processed, length);
1610 private void generateCatch(TrapData[] traps) throws IOException {
1611 out.append("} catch (e) {\n");
1613 for (TrapData e : traps) {
1617 if (e.catch_cpx != 0) { //not finally
1618 final String classInternalName = jc.getClassName(e.catch_cpx);
1619 addReference(classInternalName);
1620 if ("java/lang/Throwable".equals(classInternalName)) {
1621 out.append("if (e.$instOf_java_lang_Throwable) {");
1622 out.append(" stA0 = e;");
1623 out.append("} else {");
1624 out.append(" stA0 = vm.java_lang_Throwable(true);");
1625 out.append(" vm.java_lang_Throwable.cons__VLjava_lang_String_2.call(stA0, e.toString());");
1627 out.append("gt=" + e.handler_pc + "; continue;");
1629 out.append("if (e.$instOf_" + classInternalName.replace('/', '_') + ") {");
1630 out.append("gt=" + e.handler_pc + "; stA0 = e; continue;");
1634 finallyPC = e.handler_pc;
1637 if (finallyPC == -1) {
1638 out.append("throw e;");
1640 out.append("gt=" + finallyPC + "; stA0 = e; continue;");