Short arithmetic - added tests and conversion int->short.
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);
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 // maxStack includes two stack positions for every pushed long / double
280 // so this might generate more stack variables than we need
281 final int maxStack = m.getMaxStack();
283 // TODO: generate only used stack variables
284 for (int j = 0; j <= VarType.LAST; ++j) {
285 out.append("\n var ").append(Variable.getStackVariable(j, 0));
286 for (int i = 1; i < maxStack; ++i) {
288 out.append(Variable.getStackVariable(j, i));
294 int lastStackFrame = -1;
295 TrapData[] previousTrap = null;
297 out.append("\n var gt = 0;\n for(;;) switch(gt) {\n");
298 for (int i = 0; i < byteCodes.length; i++) {
300 stackMapIterator.advanceTo(i);
301 boolean changeInCatch = trap.advanceTo(i);
302 if (changeInCatch || lastStackFrame != stackMapIterator.getFrameIndex()) {
303 if (previousTrap != null) {
304 generateCatch(previousTrap);
308 if (lastStackFrame != stackMapIterator.getFrameIndex()) {
309 lastStackFrame = stackMapIterator.getFrameIndex();
310 lmapper.syncWithFrameLocals(stackMapIterator.getFrameLocals());
311 smapper.syncWithFrameStack(stackMapIterator.getFrameStack());
312 out.append(" case " + i).append(": ");
313 changeInCatch = true;
315 debug(" /* " + i + " */ ");
317 if (changeInCatch && trap.useTry()) {
319 previousTrap = trap.current();
321 final int c = readByte(byteCodes, i);
324 emit(out, "@1 = @2;", smapper.pushA(), lmapper.getA(0));
327 emit(out, "@1 = @2;", smapper.pushI(), lmapper.getI(0));
330 emit(out, "@1 = @2;", smapper.pushL(), lmapper.getL(0));
333 emit(out, "@1 = @2;", smapper.pushF(), lmapper.getF(0));
336 emit(out, "@1 = @2;", smapper.pushD(), lmapper.getD(0));
339 emit(out, "@1 = @2;", smapper.pushA(), lmapper.getA(1));
342 emit(out, "@1 = @2;", smapper.pushI(), lmapper.getI(1));
345 emit(out, "@1 = @2;", smapper.pushL(), lmapper.getL(1));
348 emit(out, "@1 = @2;", smapper.pushF(), lmapper.getF(1));
351 emit(out, "@1 = @2;", smapper.pushD(), lmapper.getD(1));
354 emit(out, "@1 = @2;", smapper.pushA(), lmapper.getA(2));
357 emit(out, "@1 = @2;", smapper.pushI(), lmapper.getI(2));
360 emit(out, "@1 = @2;", smapper.pushL(), lmapper.getL(2));
363 emit(out, "@1 = @2;", smapper.pushF(), lmapper.getF(2));
366 emit(out, "@1 = @2;", smapper.pushD(), lmapper.getD(2));
369 emit(out, "@1 = @2;", smapper.pushA(), lmapper.getA(3));
372 emit(out, "@1 = @2;", smapper.pushI(), lmapper.getI(3));
375 emit(out, "@1 = @2;", smapper.pushL(), lmapper.getL(3));
378 emit(out, "@1 = @2;", smapper.pushF(), lmapper.getF(3));
381 emit(out, "@1 = @2;", smapper.pushD(), lmapper.getD(3));
384 final int indx = readByte(byteCodes, ++i);
385 emit(out, "@1 = @2;", smapper.pushI(), lmapper.getI(indx));
389 final int indx = readByte(byteCodes, ++i);
390 emit(out, "@1 = @2;", smapper.pushL(), lmapper.getL(indx));
394 final int indx = readByte(byteCodes, ++i);
395 emit(out, "@1 = @2;", smapper.pushF(), lmapper.getF(indx));
399 final int indx = readByte(byteCodes, ++i);
400 emit(out, "@1 = @2;", smapper.pushD(), lmapper.getD(indx));
404 final int indx = readByte(byteCodes, ++i);
405 emit(out, "@1 = @2;", smapper.pushA(), lmapper.getA(indx));
409 final int indx = readByte(byteCodes, ++i);
410 emit(out, "@1 = @2;", lmapper.setI(indx), smapper.popI());
414 final int indx = readByte(byteCodes, ++i);
415 emit(out, "@1 = @2;", lmapper.setL(indx), smapper.popL());
419 final int indx = readByte(byteCodes, ++i);
420 emit(out, "@1 = @2;", lmapper.setF(indx), smapper.popF());
424 final int indx = readByte(byteCodes, ++i);
425 emit(out, "@1 = @2;", lmapper.setD(indx), smapper.popD());
429 final int indx = readByte(byteCodes, ++i);
430 emit(out, "@1 = @2;", lmapper.setA(indx), smapper.popA());
434 emit(out, "@1 = @2;", lmapper.setA(0), smapper.popA());
437 emit(out, "@1 = @2;", lmapper.setI(0), smapper.popI());
440 emit(out, "@1 = @2;", lmapper.setL(0), smapper.popL());
443 emit(out, "@1 = @2;", lmapper.setF(0), smapper.popF());
446 emit(out, "@1 = @2;", lmapper.setD(0), smapper.popD());
449 emit(out, "@1 = @2;", lmapper.setA(1), smapper.popA());
452 emit(out, "@1 = @2;", lmapper.setI(1), smapper.popI());
455 emit(out, "@1 = @2;", lmapper.setL(1), smapper.popL());
458 emit(out, "@1 = @2;", lmapper.setF(1), smapper.popF());
461 emit(out, "@1 = @2;", lmapper.setD(1), smapper.popD());
464 emit(out, "@1 = @2;", lmapper.setA(2), smapper.popA());
467 emit(out, "@1 = @2;", lmapper.setI(2), smapper.popI());
470 emit(out, "@1 = @2;", lmapper.setL(2), smapper.popL());
473 emit(out, "@1 = @2;", lmapper.setF(2), smapper.popF());
476 emit(out, "@1 = @2;", lmapper.setD(2), smapper.popD());
479 emit(out, "@1 = @2;", lmapper.setA(3), smapper.popA());
482 emit(out, "@1 = @2;", lmapper.setI(3), smapper.popI());
485 emit(out, "@1 = @2;", lmapper.setL(3), smapper.popL());
488 emit(out, "@1 = @2;", lmapper.setF(3), smapper.popF());
491 emit(out, "@1 = @2;", lmapper.setD(3), smapper.popD());
494 emit(out, "@1 = __add32(@1,@2);", smapper.getI(1), smapper.popI());
497 emit(out, "@1 += @2;", smapper.getL(1), smapper.popL());
500 emit(out, "@1 += @2;", smapper.getF(1), smapper.popF());
503 emit(out, "@1 += @2;", smapper.getD(1), smapper.popD());
506 emit(out, "@1 = __sub32(@1,@2);", smapper.getI(1), smapper.popI());
509 emit(out, "@1 -= @2;", smapper.getL(1), smapper.popL());
512 emit(out, "@1 -= @2;", smapper.getF(1), smapper.popF());
515 emit(out, "@1 -= @2;", smapper.getD(1), smapper.popD());
518 emit(out, "@1 = __mul32(@1,@2);", smapper.getI(1), smapper.popI());
521 emit(out, "@1 *= @2;", smapper.getL(1), smapper.popL());
524 emit(out, "@1 *= @2;", smapper.getF(1), smapper.popF());
527 emit(out, "@1 *= @2;", smapper.getD(1), smapper.popD());
530 emit(out, "@1 = Math.floor(@1 / @2);",
531 smapper.getI(1), smapper.popI());
534 emit(out, "@1 = Math.floor(@1 / @2);",
535 smapper.getL(1), smapper.popL());
538 emit(out, "@1 /= @2;", smapper.getF(1), smapper.popF());
541 emit(out, "@1 /= @2;", smapper.getD(1), smapper.popD());
544 emit(out, "@1 %= @2;", smapper.getI(1), smapper.popI());
547 emit(out, "@1 %= @2;", smapper.getL(1), smapper.popL());
550 emit(out, "@1 %= @2;", smapper.getF(1), smapper.popF());
553 emit(out, "@1 %= @2;", smapper.getD(1), smapper.popD());
556 emit(out, "@1 &= @2;", smapper.getI(1), smapper.popI());
559 emit(out, "@1 &= @2;", smapper.getL(1), smapper.popL());
562 emit(out, "@1 |= @2;", smapper.getI(1), smapper.popI());
565 emit(out, "@1 |= @2;", smapper.getL(1), smapper.popL());
568 emit(out, "@1 ^= @2;", smapper.getI(1), smapper.popI());
571 emit(out, "@1 ^= @2;", smapper.getL(1), smapper.popL());
574 emit(out, "@1 = -@1;", smapper.getI(0));
577 emit(out, "@1 = -@1;", smapper.getL(0));
580 emit(out, "@1 = -@1;", smapper.getF(0));
583 emit(out, "@1 = -@1;", smapper.getD(0));
586 emit(out, "@1 <<= @2;", smapper.getI(1), smapper.popI());
589 emit(out, "@1 <<= @2;", smapper.getL(1), smapper.popI());
592 emit(out, "@1 >>= @2;", smapper.getI(1), smapper.popI());
595 emit(out, "@1 >>= @2;", smapper.getL(1), smapper.popI());
598 emit(out, "@1 >>>= @2;", smapper.getI(1), smapper.popI());
601 emit(out, "@1 >>>= @2;", smapper.getL(1), smapper.popI());
604 final int varIndx = readByte(byteCodes, ++i);
605 final int incrBy = byteCodes[++i];
607 emit(out, "@1++;", lmapper.getI(varIndx));
609 emit(out, "@1 += @2;",
610 lmapper.getI(varIndx),
611 Integer.toString(incrBy));
616 emit(out, "return;");
619 emit(out, "return @1;", smapper.popI());
622 emit(out, "return @1;", smapper.popL());
625 emit(out, "return @1;", smapper.popF());
628 emit(out, "return @1;", smapper.popD());
631 emit(out, "return @1;", smapper.popA());
634 emit(out, "@2 = @1;", smapper.popI(), smapper.pushL());
637 emit(out, "@2 = @1;", smapper.popI(), smapper.pushF());
640 emit(out, "@2 = @1;", smapper.popI(), smapper.pushD());
643 emit(out, "@2 = @1;", smapper.popL(), smapper.pushI());
647 emit(out, "@2 = @1;", smapper.popL(), smapper.pushF());
650 emit(out, "@2 = @1;", smapper.popL(), smapper.pushD());
653 emit(out, "@2 = @1;", smapper.popF(), smapper.pushD());
656 emit(out, "@2 = @1;", smapper.popD(), smapper.pushF());
659 emit(out, "@2 = Math.floor(@1);",
660 smapper.popF(), smapper.pushI());
663 emit(out, "@2 = Math.floor(@1);",
664 smapper.popF(), smapper.pushL());
667 emit(out, "@2 = Math.floor(@1);",
668 smapper.popD(), smapper.pushI());
671 emit(out, "@2 = Math.floor(@1);",
672 smapper.popD(), smapper.pushL());
676 out.append("{ /* number conversion */ }");
679 emit(out, "@1 = __toInt16(@1);", smapper.getI(0));
681 case opc_aconst_null:
682 emit(out, "@1 = null;", smapper.pushA());
685 emit(out, "@1 = -1;", smapper.pushI());
688 emit(out, "@1 = 0;", smapper.pushI());
691 emit(out, "@1 = 0;", smapper.pushD());
694 emit(out, "@1 = 0;", smapper.pushL());
697 emit(out, "@1 = 0;", smapper.pushF());
700 emit(out, "@1 = 1;", smapper.pushI());
703 emit(out, "@1 = 1;", smapper.pushL());
706 emit(out, "@1 = 1;", smapper.pushF());
709 emit(out, "@1 = 1;", smapper.pushD());
712 emit(out, "@1 = 2;", smapper.pushI());
715 emit(out, "@1 = 2;", smapper.pushF());
718 emit(out, "@1 = 3;", smapper.pushI());
721 emit(out, "@1 = 4;", smapper.pushI());
724 emit(out, "@1 = 5;", smapper.pushI());
727 int indx = readByte(byteCodes, ++i);
728 String v = encodeConstant(indx);
729 int type = VarType.fromConstantType(jc.getTag(indx));
730 emit(out, "@1 = @2;", smapper.pushT(type), v);
735 int indx = readIntArg(byteCodes, i);
737 String v = encodeConstant(indx);
738 int type = VarType.fromConstantType(jc.getTag(indx));
739 emit(out, "@1 = @2;", smapper.pushT(type), v);
743 emit(out, "@3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
744 smapper.popL(), smapper.popL(), smapper.pushI());
748 emit(out, "@3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
749 smapper.popF(), smapper.popF(), smapper.pushI());
753 emit(out, "@3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
754 smapper.popD(), smapper.popD(), smapper.pushI());
757 i = generateIf(byteCodes, i, smapper.popA(), smapper.popA(),
761 i = generateIf(byteCodes, i, smapper.popA(), smapper.popA(),
765 i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
769 int indx = i + readIntArg(byteCodes, i);
770 emit(out, "if (@1 == 0) { gt = @2; continue; }",
771 smapper.popI(), Integer.toString(indx));
776 int indx = i + readIntArg(byteCodes, i);
777 emit(out, "if (@1 != 0) { gt = @2; continue; }",
778 smapper.popI(), Integer.toString(indx));
783 int indx = i + readIntArg(byteCodes, i);
784 emit(out, "if (@1 < 0) { gt = @2; continue; }",
785 smapper.popI(), Integer.toString(indx));
790 int indx = i + readIntArg(byteCodes, i);
791 emit(out, "if (@1 <= 0) { gt = @2; continue; }",
792 smapper.popI(), Integer.toString(indx));
797 int indx = i + readIntArg(byteCodes, i);
798 emit(out, "if (@1 > 0) { gt = @2; continue; }",
799 smapper.popI(), Integer.toString(indx));
804 int indx = i + readIntArg(byteCodes, i);
805 emit(out, "if (@1 >= 0) { gt = @2; continue; }",
806 smapper.popI(), Integer.toString(indx));
810 case opc_ifnonnull: {
811 int indx = i + readIntArg(byteCodes, i);
812 emit(out, "if (@1 !== null) { gt = @2; continue; }",
813 smapper.popA(), Integer.toString(indx));
818 int indx = i + readIntArg(byteCodes, i);
819 emit(out, "if (@1 === null) { gt = @2; continue; }",
820 smapper.popA(), Integer.toString(indx));
825 i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
829 i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
833 i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
837 i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
841 i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
845 int indx = i + readIntArg(byteCodes, i);
846 emit(out, "gt = @1; continue;", Integer.toString(indx));
850 case opc_lookupswitch: {
851 int table = i / 4 * 4 + 4;
852 int dflt = i + readInt4(byteCodes, table);
854 int n = readInt4(byteCodes, table);
856 out.append("switch (").append(smapper.popI()).append(") {\n");
858 int cnstnt = readInt4(byteCodes, table);
860 int offset = i + readInt4(byteCodes, table);
862 out.append(" case " + cnstnt).append(": gt = " + offset).append("; continue;\n");
864 out.append(" default: gt = " + dflt).append("; continue;\n}");
868 case opc_tableswitch: {
869 int table = i / 4 * 4 + 4;
870 int dflt = i + readInt4(byteCodes, table);
872 int low = readInt4(byteCodes, table);
874 int high = readInt4(byteCodes, table);
876 out.append("switch (").append(smapper.popI()).append(") {\n");
877 while (low <= high) {
878 int offset = i + readInt4(byteCodes, table);
880 out.append(" case " + low).append(": gt = " + offset).append("; continue;\n");
883 out.append(" default: gt = " + dflt).append("; continue;\n}");
887 case opc_invokeinterface: {
888 i = invokeVirtualMethod(byteCodes, i, smapper) + 2;
891 case opc_invokevirtual:
892 i = invokeVirtualMethod(byteCodes, i, smapper);
894 case opc_invokespecial:
895 i = invokeStaticMethod(byteCodes, i, smapper, false);
897 case opc_invokestatic:
898 i = invokeStaticMethod(byteCodes, i, smapper, true);
901 int indx = readIntArg(byteCodes, i);
902 String ci = jc.getClassName(indx);
903 emit(out, "@1 = new @2;",
904 smapper.pushA(), accessClass(ci.replace('/', '_')));
910 ++i; // skip type of array
911 emit(out, "@2 = new Array(@1).fillNulls();",
912 smapper.popI(), smapper.pushA());
915 i += 2; // skip type of array
916 emit(out, "@2 = new Array(@1).fillNulls();",
917 smapper.popI(), smapper.pushA());
919 case opc_multianewarray: {
921 int dim = readByte(byteCodes, ++i);
922 out.append("{ var a0 = new Array(").append(smapper.popI())
923 .append(").fillNulls();");
924 for (int d = 1; d < dim; d++) {
925 out.append("\n var l" + d).append(" = ")
926 .append(smapper.popI()).append(';');
927 out.append("\n for (var i" + d).append (" = 0; i" + d).
928 append(" < a" + (d - 1)).
929 append(".length; i" + d).append("++) {");
930 out.append("\n var a" + d).
931 append (" = new Array(l" + d).append(").fillNulls();");
932 out.append("\n a" + (d - 1)).append("[i" + d).append("] = a" + d).
935 for (int d = 1; d < dim; d++) {
938 out.append("\n").append(smapper.pushA()).append(" = a0; }");
941 case opc_arraylength:
942 emit(out, "@2 = @1.length;", smapper.popA(), smapper.pushI());
945 emit(out, "@3[@2] = @1;",
946 smapper.popL(), smapper.popI(), smapper.popA());
949 emit(out, "@3[@2] = @1;",
950 smapper.popF(), smapper.popI(), smapper.popA());
953 emit(out, "@3[@2] = @1;",
954 smapper.popD(), smapper.popI(), smapper.popA());
957 emit(out, "@3[@2] = @1;",
958 smapper.popA(), smapper.popI(), smapper.popA());
964 emit(out, "@3[@2] = @1;",
965 smapper.popI(), smapper.popI(), smapper.popA());
968 emit(out, "@3 = @2[@1];",
969 smapper.popI(), smapper.popA(), smapper.pushL());
972 emit(out, "@3 = @2[@1];",
973 smapper.popI(), smapper.popA(), smapper.pushF());
976 emit(out, "@3 = @2[@1];",
977 smapper.popI(), smapper.popA(), smapper.pushD());
980 emit(out, "@3 = @2[@1];",
981 smapper.popI(), smapper.popA(), smapper.pushA());
987 emit(out, "@3 = @2[@1];",
988 smapper.popI(), smapper.popA(), smapper.pushI());
996 final Variable v = smapper.get(0);
997 emit(out, "@1 = @2;", smapper.pushT(v.getType()), v);
1001 if (smapper.get(0).isCategory2()) {
1002 final Variable v = smapper.get(0);
1003 emit(out, "@1 = @2;", smapper.pushT(v.getType()), v);
1005 final Variable v1 = smapper.get(0);
1006 final Variable v2 = smapper.get(1);
1007 emit(out, "{ @1 = @2; @3 = @4; }",
1008 smapper.pushT(v2.getType()), v2,
1009 smapper.pushT(v1.getType()), v1);
1014 final Variable vi1 = smapper.pop();
1015 final Variable vi2 = smapper.pop();
1016 final Variable vo3 = smapper.pushT(vi1.getType());
1017 final Variable vo2 = smapper.pushT(vi2.getType());
1018 final Variable vo1 = smapper.pushT(vi1.getType());
1020 emit(out, "{ @1 = @2; @3 = @4; @5 = @6; }",
1021 vo1, vi1, vo2, vi2, vo3, vo1);
1025 if (smapper.get(1).isCategory2()) {
1026 final Variable vi1 = smapper.pop();
1027 final Variable vi2 = smapper.pop();
1028 final Variable vo3 = smapper.pushT(vi1.getType());
1029 final Variable vo2 = smapper.pushT(vi2.getType());
1030 final Variable vo1 = smapper.pushT(vi1.getType());
1032 emit(out, "{ @1 = @2; @3 = @4; @5 = @6; }",
1033 vo1, vi1, vo2, vi2, vo3, vo1);
1035 final Variable vi1 = smapper.pop();
1036 final Variable vi2 = smapper.pop();
1037 final Variable vi3 = smapper.pop();
1038 final Variable vo4 = smapper.pushT(vi1.getType());
1039 final Variable vo3 = smapper.pushT(vi3.getType());
1040 final Variable vo2 = smapper.pushT(vi2.getType());
1041 final Variable vo1 = smapper.pushT(vi1.getType());
1043 emit(out, "{ @1 = @2; @3 = @4; @5 = @6; @7 = @8; }",
1044 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1049 emit(out, "@1 = @2;",
1050 smapper.pushI(), Integer.toString(byteCodes[++i]));
1053 emit(out, "@1 = @2;",
1055 Integer.toString(readIntArg(byteCodes, i)));
1058 case opc_getfield: {
1059 int indx = readIntArg(byteCodes, i);
1060 String[] fi = jc.getFieldInfoName(indx);
1061 final int type = VarType.fromFieldType(fi[2].charAt(0));
1062 emit(out, "@2 = @1.fld_@3;",
1063 smapper.popA(), smapper.pushT(type), fi[1]);
1067 case opc_getstatic: {
1068 int indx = readIntArg(byteCodes, i);
1069 String[] fi = jc.getFieldInfoName(indx);
1070 final int type = VarType.fromFieldType(fi[2].charAt(0));
1071 emit(out, "@1 = @2(false).constructor.@3;",
1072 smapper.pushT(type),
1073 accessClass(fi[0].replace('/', '_')), fi[1]);
1075 addReference(fi[0]);
1078 case opc_putfield: {
1079 int indx = readIntArg(byteCodes, i);
1080 String[] fi = jc.getFieldInfoName(indx);
1081 final int type = VarType.fromFieldType(fi[2].charAt(0));
1082 emit(out, "@2.fld_@3 = @1;",
1083 smapper.popT(type), smapper.popA(), fi[1]);
1087 case opc_putstatic: {
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, "@1(false).constructor.@2 = @3;",
1092 accessClass(fi[0].replace('/', '_')), fi[1],
1093 smapper.popT(type));
1095 addReference(fi[0]);
1098 case opc_checkcast: {
1099 int indx = readIntArg(byteCodes, i);
1100 final String type = jc.getClassName(indx);
1101 if (!type.startsWith("[")) {
1102 // no way to check arrays right now
1103 // XXX proper exception
1105 "if (@1 !== null && !@1.$instOf_@2) throw {};",
1106 smapper.getA(0), type.replace('/', '_'));
1111 case opc_instanceof: {
1112 int indx = readIntArg(byteCodes, i);
1113 final String type = jc.getClassName(indx);
1114 emit(out, "@2 = @1.$instOf_@3 ? 1 : 0;",
1115 smapper.popA(), smapper.pushI(),
1116 type.replace('/', '_'));
1121 final Variable v = smapper.popA();
1124 emit(out, "{ @1 = @2; throw @2; }",
1125 smapper.pushA(), v);
1129 case opc_monitorenter: {
1130 out.append("/* monitor enter */");
1135 case opc_monitorexit: {
1136 out.append("/* monitor exit */");
1142 emit(out, "throw 'unknown bytecode @1';",
1143 Integer.toString(c));
1147 for (int j = prev; j <= i; j++) {
1149 final int cc = readByte(byteCodes, j);
1150 out.append(Integer.toString(cc));
1155 if (previousTrap != null) {
1156 generateCatch(previousTrap);
1162 private int generateIf(byte[] byteCodes, int i,
1163 final Variable v2, final Variable v1,
1164 final String test) throws IOException {
1165 int indx = i + readIntArg(byteCodes, i);
1166 out.append("if (").append(v1)
1167 .append(' ').append(test).append(' ')
1168 .append(v2).append(") { gt = " + indx)
1169 .append("; continue; }");
1173 private int readIntArg(byte[] byteCodes, int offsetInstruction) {
1174 final int indxHi = byteCodes[offsetInstruction + 1] << 8;
1175 final int indxLo = byteCodes[offsetInstruction + 2];
1176 return (indxHi & 0xffffff00) | (indxLo & 0xff);
1178 private int readInt4(byte[] byteCodes, int offsetInstruction) {
1179 final int d = byteCodes[offsetInstruction + 0] << 24;
1180 final int c = byteCodes[offsetInstruction + 1] << 16;
1181 final int b = byteCodes[offsetInstruction + 2] << 8;
1182 final int a = byteCodes[offsetInstruction + 3];
1183 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
1185 private int readByte(byte[] byteCodes, int offsetInstruction) {
1186 return byteCodes[offsetInstruction] & 0xff;
1189 private static void countArgs(String descriptor, char[] returnType, StringBuilder sig, StringBuilder cnt) {
1191 Boolean count = null;
1192 boolean array = false;
1194 int firstPos = sig.length();
1195 while (i < descriptor.length()) {
1196 char ch = descriptor.charAt(i++);
1217 if (ch == 'J' || ch == 'D') {
1223 sig.insert(firstPos, ch);
1225 returnType[0] = '[';
1226 sig.insert(firstPos, "_3");
1235 returnType[0] = 'V';
1236 sig.insert(firstPos, 'V');
1239 int next = descriptor.indexOf(';', i);
1240 String realSig = mangleSig(descriptor, i - 1, next + 1);
1245 sig.append(realSig);
1248 sig.insert(firstPos, realSig);
1250 sig.insert(firstPos, "_3");
1252 returnType[0] = 'L';
1261 throw new IllegalStateException("Invalid char: " + ch);
1266 private static String mangleSig(String txt, int first, int last) {
1267 StringBuilder sb = new StringBuilder();
1268 for (int i = first; i < last; i++) {
1269 final char ch = txt.charAt(i);
1271 case '/': sb.append('_'); break;
1272 case '_': sb.append("_1"); break;
1273 case ';': sb.append("_2"); break;
1274 case '[': sb.append("_3"); break;
1275 default: sb.append(ch); break;
1278 return sb.toString();
1281 private static String findMethodName(MethodData m, StringBuilder cnt) {
1282 StringBuilder name = new StringBuilder();
1283 if ("<init>".equals(m.getName())) { // NOI18N
1284 name.append("cons"); // NOI18N
1285 } else if ("<clinit>".equals(m.getName())) { // NOI18N
1286 name.append("class"); // NOI18N
1288 name.append(m.getName());
1291 countArgs(m.getInternalSig(), new char[1], name, cnt);
1292 return name.toString();
1295 static String findMethodName(String[] mi, StringBuilder cnt, char[] returnType) {
1296 StringBuilder name = new StringBuilder();
1297 String descr = mi[2];//mi.getDescriptor();
1299 if ("<init>".equals(nm)) { // NOI18N
1300 name.append("cons"); // NOI18N
1304 countArgs(descr, returnType, name, cnt);
1305 return name.toString();
1308 private int invokeStaticMethod(byte[] byteCodes, int i, final StackMapper mapper, boolean isStatic)
1309 throws IOException {
1310 int methodIndex = readIntArg(byteCodes, i);
1311 String[] mi = jc.getFieldInfoName(methodIndex);
1312 char[] returnType = { 'V' };
1313 StringBuilder cnt = new StringBuilder();
1314 String mn = findMethodName(mi, cnt, returnType);
1316 final int numArguments = isStatic ? cnt.length() : cnt.length() + 1;
1317 final Variable[] vars = new Variable[numArguments];
1319 for (int j = numArguments - 1; j >= 0; --j) {
1320 vars[j] = mapper.pop();
1323 if (returnType[0] != 'V') {
1324 out.append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1328 final String in = mi[0];
1329 out.append(accessClass(in.replace('/', '_')));
1330 out.append("(false).");
1331 if (mn.startsWith("cons_")) {
1332 out.append("constructor.");
1336 if (numArguments > 0) {
1337 out.append(vars[0]);
1338 for (int j = 1; j < numArguments; ++j) {
1340 out.append(vars[j]);
1348 private int invokeVirtualMethod(byte[] byteCodes, int i, final StackMapper mapper)
1349 throws IOException {
1350 int methodIndex = readIntArg(byteCodes, i);
1351 String[] mi = jc.getFieldInfoName(methodIndex);
1352 char[] returnType = { 'V' };
1353 StringBuilder cnt = new StringBuilder();
1354 String mn = findMethodName(mi, cnt, returnType);
1356 final int numArguments = cnt.length() + 1;
1357 final Variable[] vars = new Variable[numArguments];
1359 for (int j = numArguments - 1; j >= 0; --j) {
1360 vars[j] = mapper.pop();
1363 if (returnType[0] != 'V') {
1364 out.append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1368 out.append(vars[0]).append('.');
1371 out.append(vars[0]);
1372 for (int j = 1; j < numArguments; ++j) {
1374 out.append(vars[j]);
1381 private void addReference(String cn) throws IOException {
1382 if (requireReference(cn)) {
1383 debug(" /* needs " + cn + " */");
1387 private void outType(String d, StringBuilder out) {
1389 while (d.charAt(0) == '[') {
1393 if (d.charAt(0) == 'L') {
1394 assert d.charAt(d.length() - 1) == ';';
1395 out.append(d.replace('/', '_').substring(0, d.length() - 1));
1401 private String encodeConstant(int entryIndex) throws IOException {
1402 String[] classRef = { null };
1403 String s = jc.stringValue(entryIndex, classRef);
1404 if (classRef[0] != null) {
1405 addReference(classRef[0]);
1406 s = accessClass(s.replace('/', '_')) + "(false).constructor.$class";
1411 private String javaScriptBody(String prefix, MethodData m, boolean isStatic) throws IOException {
1412 byte[] arr = m.findAnnotationData(true);
1416 final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
1417 class P extends AnnotationParser {
1423 String[] args = new String[30];
1427 protected void visitAttr(String type, String attr, String at, String value) {
1428 if (type.equals(jvmType)) {
1429 if ("body".equals(attr)) {
1431 } else if ("args".equals(attr)) {
1432 args[cnt++] = value;
1434 throw new IllegalArgumentException(attr);
1441 if (p.body == null) {
1444 StringBuilder cnt = new StringBuilder();
1445 final String mn = findMethodName(m, cnt);
1446 out.append(prefix).append(mn);
1447 out.append(" = function(");
1451 space = outputArg(out, p.args, 0);
1457 for (int i = 0; i < cnt.length(); i++) {
1459 space = outputArg(out, p.args, index);
1462 out.append(") {").append("\n");
1464 out.append("\n}\n");
1467 private static String className(ClassData jc) {
1468 //return jc.getName().getInternalName().replace('/', '_');
1469 return jc.getClassName().replace('/', '_');
1472 private static String[] findAnnotation(
1473 byte[] arr, ClassData cd, final String className,
1474 final String... attrNames
1475 ) throws IOException {
1479 final String[] values = new String[attrNames.length];
1480 final boolean[] found = { false };
1481 final String jvmType = "L" + className.replace('.', '/') + ";";
1482 AnnotationParser ap = new AnnotationParser(false) {
1484 protected void visitAttr(String type, String attr, String at, String value) {
1485 if (type.equals(jvmType)) {
1487 for (int i = 0; i < attrNames.length; i++) {
1488 if (attrNames[i].equals(attr)) {
1497 return found[0] ? values : null;
1500 private CharSequence initField(FieldData v) {
1501 final String is = v.getInternalSig();
1502 if (is.length() == 1) {
1503 switch (is.charAt(0)) {
1509 case 'I': return " = 0;";
1511 case 'D': return " = 0.0;";
1513 throw new IllegalStateException(is);
1519 private static void generateAnno(ClassData cd, final Appendable out, byte[] data) throws IOException {
1520 AnnotationParser ap = new AnnotationParser(true) {
1525 protected void visitAnnotationStart(String type) throws IOException {
1529 out.append('"').append(type).append("\" : {\n");
1534 protected void visitAnnotationEnd(String type) throws IOException {
1535 out.append("\n}\n");
1539 protected void visitAttr(String type, String attr, String attrType, String value)
1540 throws IOException {
1547 out.append(attr).append("__").append(attrType).append(" : ").append(value);
1553 private static String outputArg(Appendable out, String[] args, int indx) throws IOException {
1554 final String name = args[indx];
1558 if (name.contains(",")) {
1559 throw new IOException("Wrong parameter with ',': " + name);
1565 private static void emit(final Appendable out,
1566 final String format,
1567 final CharSequence... params) throws IOException {
1568 final int length = format.length();
1571 int paramOffset = format.indexOf('@');
1572 while ((paramOffset != -1) && (paramOffset < (length - 1))) {
1573 final char paramChar = format.charAt(paramOffset + 1);
1574 if ((paramChar >= '1') && (paramChar <= '9')) {
1575 final int paramIndex = paramChar - '0' - 1;
1577 out.append(format, processed, paramOffset);
1578 out.append(params[paramIndex]);
1581 processed = paramOffset + 1;
1584 paramOffset = format.indexOf('@', paramOffset + 1);
1587 out.append(format, processed, length);
1590 private void generateCatch(TrapData[] traps) throws IOException {
1591 out.append("} catch (e) {\n");
1593 for (TrapData e : traps) {
1597 if (e.catch_cpx != 0) { //not finally
1598 final String classInternalName = jc.getClassName(e.catch_cpx);
1599 addReference(classInternalName);
1600 if ("java/lang/Throwable".equals(classInternalName)) {
1601 out.append("if (e.$instOf_java_lang_Throwable) {");
1602 out.append(" stA0 = e;");
1603 out.append("} else {");
1604 out.append(" stA0 = vm.java_lang_Throwable(true);");
1605 out.append(" vm.java_lang_Throwable.cons__VLjava_lang_String_2(stA0, e.toString());");
1607 out.append("gt=" + e.handler_pc + "; continue;");
1609 out.append("if (e.$instOf_" + classInternalName.replace('/', '_') + ") {");
1610 out.append("gt=" + e.handler_pc + "; stA0 = e; continue;");
1614 finallyPC = e.handler_pc;
1617 if (finallyPC == -1) {
1618 out.append("throw e;");
1620 out.append("gt=" + finallyPC + "; stA0 = e; continue;");