Long arithmetic prototype, Long currently represented by separate JavaScript object with two JS-Numbers.
Just few operation implemented to pass tests. Tests under vmtest directory are still failing.
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) throws IOException;
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();
268 out.append(" var ").append(" lcA0 = this;\n");
271 int lastStackFrame = -1;
272 TrapData[] previousTrap = null;
274 out.append("\n var gt = 0;\n for(;;) switch(gt) {\n");
275 for (int i = 0; i < byteCodes.length; i++) {
277 stackMapIterator.advanceTo(i);
278 boolean changeInCatch = trap.advanceTo(i);
279 if (changeInCatch || lastStackFrame != stackMapIterator.getFrameIndex()) {
280 if (previousTrap != null) {
281 generateCatch(previousTrap);
285 if (lastStackFrame != stackMapIterator.getFrameIndex()) {
286 lastStackFrame = stackMapIterator.getFrameIndex();
287 lmapper.syncWithFrameLocals(stackMapIterator.getFrameLocals());
288 smapper.syncWithFrameStack(stackMapIterator.getFrameStack());
289 out.append(" case " + i).append(": ");
290 changeInCatch = true;
292 debug(" /* " + i + " */ ");
294 if (changeInCatch && trap.useTry()) {
296 previousTrap = trap.current();
298 final int c = readByte(byteCodes, i);
301 emit(out, "var @1 = @2;", smapper.pushA(), lmapper.getA(0));
304 emit(out, "var @1 = @2;", smapper.pushI(), lmapper.getI(0));
307 emit(out, "var @1 = MakeLong(@2);", smapper.pushL(), lmapper.getL(0));
310 emit(out, "var @1 = @2;", smapper.pushF(), lmapper.getF(0));
313 emit(out, "var @1 = @2;", smapper.pushD(), lmapper.getD(0));
316 emit(out, "var @1 = @2;", smapper.pushA(), lmapper.getA(1));
319 emit(out, "var @1 = @2;", smapper.pushI(), lmapper.getI(1));
322 emit(out, "var @1 = MakeLong(@2);", smapper.pushL(), lmapper.getL(1));
325 emit(out, "var @1 = @2;", smapper.pushF(), lmapper.getF(1));
328 emit(out, "var @1 = @2;", smapper.pushD(), lmapper.getD(1));
331 emit(out, "var @1 = @2;", smapper.pushA(), lmapper.getA(2));
334 emit(out, "var @1 = @2;", smapper.pushI(), lmapper.getI(2));
337 emit(out, "var @1 = MakeLong(@2);", smapper.pushL(), lmapper.getL(2));
340 emit(out, "var @1 = @2;", smapper.pushF(), lmapper.getF(2));
343 emit(out, "var @1 = @2;", smapper.pushD(), lmapper.getD(2));
346 emit(out, "var @1 = @2;", smapper.pushA(), lmapper.getA(3));
349 emit(out, "var @1 = @2;", smapper.pushI(), lmapper.getI(3));
352 emit(out, "var @1 = MakeLong(@2);", smapper.pushL(), lmapper.getL(3));
355 emit(out, "var @1 = @2;", smapper.pushF(), lmapper.getF(3));
358 emit(out, "var @1 = @2;", smapper.pushD(), lmapper.getD(3));
361 final int indx = readByte(byteCodes, ++i);
362 emit(out, "var @1 = @2;",
363 smapper.pushI(), lmapper.getI(indx));
367 final int indx = readByte(byteCodes, ++i);
368 emit(out, "var @1 = @2;",
369 smapper.pushL(), lmapper.getL(indx));
373 final int indx = readByte(byteCodes, ++i);
374 emit(out, "var @1 = @2;",
375 smapper.pushF(), lmapper.getF(indx));
379 final int indx = readByte(byteCodes, ++i);
380 emit(out, "var @1 = @2;",
381 smapper.pushD(), lmapper.getD(indx));
385 final int indx = readByte(byteCodes, ++i);
386 emit(out, "var @1 = @2;",
387 smapper.pushA(), lmapper.getA(indx));
391 final int indx = readByte(byteCodes, ++i);
392 emit(out, "var @1 = @2;",
393 lmapper.setI(indx), smapper.popI());
397 final int indx = readByte(byteCodes, ++i);
398 emit(out, "var @1 = @2;",
399 lmapper.setL(indx), smapper.popL());
403 final int indx = readByte(byteCodes, ++i);
404 emit(out, "var @1 = @2;",
405 lmapper.setF(indx), smapper.popF());
409 final int indx = readByte(byteCodes, ++i);
410 emit(out, "var @1 = @2;",
411 lmapper.setD(indx), smapper.popD());
415 final int indx = readByte(byteCodes, ++i);
416 emit(out, "var @1 = @2;",
417 lmapper.setA(indx), smapper.popA());
421 emit(out, "var @1 = @2;", lmapper.setA(0), smapper.popA());
424 emit(out, "var @1 = @2;", lmapper.setI(0), smapper.popI());
427 emit(out, "var @1 = @2;", lmapper.setL(0), smapper.popL());
430 emit(out, "var @1 = @2;", lmapper.setF(0), smapper.popF());
433 emit(out, "var @1 = @2;", lmapper.setD(0), smapper.popD());
436 emit(out, "var @1 = @2;", lmapper.setA(1), smapper.popA());
439 emit(out, "var @1 = @2;", lmapper.setI(1), smapper.popI());
442 emit(out, "var @1 = @2;", lmapper.setL(1), smapper.popL());
445 emit(out, "var @1 = @2;", lmapper.setF(1), smapper.popF());
448 emit(out, "var @1 = @2;", lmapper.setD(1), smapper.popD());
451 emit(out, "var @1 = @2;", lmapper.setA(2), smapper.popA());
454 emit(out, "var @1 = @2;", lmapper.setI(2), smapper.popI());
457 emit(out, "var @1 = @2;", lmapper.setL(2), smapper.popL());
460 emit(out, "var @1 = @2;", lmapper.setF(2), smapper.popF());
463 emit(out, "var @1 = @2;", lmapper.setD(2), smapper.popD());
466 emit(out, "var @1 = @2;", lmapper.setA(3), smapper.popA());
469 emit(out, "var @1 = @2;", lmapper.setI(3), smapper.popI());
472 emit(out, "var @1 = @2;", lmapper.setL(3), smapper.popL());
475 emit(out, "var @1 = @2;", lmapper.setF(3), smapper.popF());
478 emit(out, "var @1 = @2;", lmapper.setD(3), smapper.popD());
481 emit(out, "@1 = @1.add32(@2);", smapper.getI(1), smapper.popI());
484 emit(out, "@1 = @1.add64(@2);", smapper.getL(1), smapper.popL());
487 emit(out, "@1 += @2;", smapper.getF(1), smapper.popF());
490 emit(out, "@1 += @2;", smapper.getD(1), smapper.popD());
493 emit(out, "@1 = @1.sub32(@2);", smapper.getI(1), smapper.popI());
496 emit(out, "@1 -= @2;", smapper.getL(1), smapper.popL());
499 emit(out, "@1 -= @2;", smapper.getF(1), smapper.popF());
502 emit(out, "@1 -= @2;", smapper.getD(1), smapper.popD());
505 emit(out, "@1 = @1.mul32(@2);", smapper.getI(1), smapper.popI());
508 emit(out, "@1 *= @2;", smapper.getL(1), smapper.popL());
511 emit(out, "@1 *= @2;", smapper.getF(1), smapper.popF());
514 emit(out, "@1 *= @2;", smapper.getD(1), smapper.popD());
517 emit(out, "@1 = Math.floor(@1 / @2);",
518 smapper.getI(1), smapper.popI());
521 emit(out, "@1 = @1.div64(@2);",
522 smapper.getL(1), smapper.popL());
525 emit(out, "@1 /= @2;", smapper.getF(1), smapper.popF());
528 emit(out, "@1 /= @2;", smapper.getD(1), smapper.popD());
531 emit(out, "@1 %= @2;", smapper.getI(1), smapper.popI());
534 emit(out, "@1 %= @2;", smapper.getL(1), smapper.popL());
537 emit(out, "@1 %= @2;", smapper.getF(1), smapper.popF());
540 emit(out, "@1 %= @2;", smapper.getD(1), smapper.popD());
543 emit(out, "@1 &= @2;", smapper.getI(1), smapper.popI());
546 emit(out, "@1 &= @2;", smapper.getL(1), smapper.popL());
549 emit(out, "@1 |= @2;", smapper.getI(1), smapper.popI());
552 emit(out, "@1 |= @2;", smapper.getL(1), smapper.popL());
555 emit(out, "@1 ^= @2;", smapper.getI(1), smapper.popI());
558 emit(out, "@1 ^= @2;", smapper.getL(1), smapper.popL());
561 emit(out, "@1 = -@1;", smapper.getI(0));
564 emit(out, "@1 = -@1;", smapper.getL(0));
567 emit(out, "@1 = -@1;", smapper.getF(0));
570 emit(out, "@1 = -@1;", smapper.getD(0));
573 emit(out, "@1 <<= @2;", smapper.getI(1), smapper.popI());
576 emit(out, "@1 = @1.shl64(@2);", smapper.getL(1), smapper.popI());
579 emit(out, "@1 >>= @2;", smapper.getI(1), smapper.popI());
582 emit(out, "@1 >>= @2;", smapper.getL(1), smapper.popI());
585 emit(out, "@1 >>>= @2;", smapper.getI(1), smapper.popI());
588 emit(out, "@1 >>>= @2;", smapper.getL(1), smapper.popI());
591 final int varIndx = readByte(byteCodes, ++i);
592 final int incrBy = byteCodes[++i];
594 emit(out, "@1++;", lmapper.getI(varIndx));
596 emit(out, "@1 += @2;",
597 lmapper.getI(varIndx),
598 Integer.toString(incrBy));
603 emit(out, "return;");
606 emit(out, "return @1;", smapper.popI());
609 emit(out, "return @1;", smapper.popL());
612 emit(out, "return @1;", smapper.popF());
615 emit(out, "return @1;", smapper.popD());
618 emit(out, "return @1;", smapper.popA());
621 emit(out, "var @2 = new Long(@1, 0);", smapper.popI(), smapper.pushL());
624 emit(out, "var @2 = @1;", smapper.popI(), smapper.pushF());
627 emit(out, "var @2 = @1;", smapper.popI(), smapper.pushD());
630 emit(out, "var @2 = @1.toInt32();", smapper.popL(), smapper.pushI());
634 emit(out, "var @2 = @1.toFP();", smapper.popL(), smapper.pushF());
637 emit(out, "var @2 = @1.toFP();", smapper.popL(), smapper.pushD());
640 emit(out, "var @2 = @1;", smapper.popF(), smapper.pushD());
643 emit(out, "var @2 = @1;", smapper.popD(), smapper.pushF());
646 emit(out, "var @2 = Math.floor(@1);",
647 smapper.popF(), smapper.pushI());
650 emit(out, "var @2 = LongFromNumber(Math.floor(@1));",
651 smapper.popF(), smapper.pushL());
654 emit(out, "var @2 = Math.floor(@1);",
655 smapper.popD(), smapper.pushI());
658 emit(out, "var @2 = LongFromNumber(Math.floor(@1));",
659 smapper.popD(), smapper.pushL());
662 emit(out, "var @1 = @1.toInt8();", smapper.getI(0));
665 out.append("{ /* number conversion */ }");
668 emit(out, "var @1 = @1.toInt16();", smapper.getI(0));
670 case opc_aconst_null:
671 emit(out, "var @1 = null;", smapper.pushA());
674 emit(out, "var @1 = -1;", smapper.pushI());
677 emit(out, "var @1 = 0;", smapper.pushI());
680 emit(out, "var @1 = 0;", smapper.pushD());
683 emit(out, "var @1 = new Long(0,0);", smapper.pushL());
686 emit(out, "var @1 = 0;", smapper.pushF());
689 emit(out, "var @1 = 1;", smapper.pushI());
692 emit(out, "var @1 = new Long(1,0);", smapper.pushL());
695 emit(out, "var @1 = 1;", smapper.pushF());
698 emit(out, "var @1 = 1;", smapper.pushD());
701 emit(out, "var @1 = 2;", smapper.pushI());
704 emit(out, "var @1 = 2;", smapper.pushF());
707 emit(out, "var @1 = 3;", smapper.pushI());
710 emit(out, "var @1 = 4;", smapper.pushI());
713 emit(out, "var @1 = 5;", smapper.pushI());
716 int indx = readByte(byteCodes, ++i);
717 String v = encodeConstant(indx);
718 int type = VarType.fromConstantType(jc.getTag(indx));
719 emit(out, "var @1 = @2;", smapper.pushT(type), v);
724 int indx = readIntArg(byteCodes, i);
726 String v = encodeConstant(indx);
727 int type = VarType.fromConstantType(jc.getTag(indx));
728 if (type == VarType.LONG) {
729 final Long lv = new Long(v);
730 final int low = (int)(lv.longValue() & 0xFFFFFFFF);
731 final int hi = (int)(lv.longValue() >> 32);
732 emit(out, "var @1 = new Long(0x@2, 0x@3);", smapper.pushL(),
733 Integer.toHexString(low), Integer.toHexString(hi));
735 emit(out, "var @1 = @2;", smapper.pushT(type), v);
740 emit(out, "var @3 = @2.compare64(@1);",
741 smapper.popL(), smapper.popL(), smapper.pushI());
745 emit(out, "var @3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
746 smapper.popF(), smapper.popF(), smapper.pushI());
750 emit(out, "var @3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
751 smapper.popD(), smapper.popD(), smapper.pushI());
754 i = generateIf(byteCodes, i, smapper.popA(), smapper.popA(),
758 i = generateIf(byteCodes, i, smapper.popA(), smapper.popA(),
762 i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
766 int indx = i + readIntArg(byteCodes, i);
767 emit(out, "if (@1 == 0) { gt = @2; continue; }",
768 smapper.popI(), Integer.toString(indx));
773 int indx = i + readIntArg(byteCodes, i);
774 emit(out, "if (@1 != 0) { gt = @2; continue; }",
775 smapper.popI(), Integer.toString(indx));
780 int indx = i + readIntArg(byteCodes, i);
781 emit(out, "if (@1 < 0) { gt = @2; continue; }",
782 smapper.popI(), Integer.toString(indx));
787 int indx = i + readIntArg(byteCodes, i);
788 emit(out, "if (@1 <= 0) { gt = @2; continue; }",
789 smapper.popI(), Integer.toString(indx));
794 int indx = i + readIntArg(byteCodes, i);
795 emit(out, "if (@1 > 0) { gt = @2; continue; }",
796 smapper.popI(), Integer.toString(indx));
801 int indx = i + readIntArg(byteCodes, i);
802 emit(out, "if (@1 >= 0) { gt = @2; continue; }",
803 smapper.popI(), Integer.toString(indx));
807 case opc_ifnonnull: {
808 int indx = i + readIntArg(byteCodes, i);
809 emit(out, "if (@1 !== null) { gt = @2; continue; }",
810 smapper.popA(), Integer.toString(indx));
815 int indx = i + readIntArg(byteCodes, i);
816 emit(out, "if (@1 === null) { gt = @2; continue; }",
817 smapper.popA(), Integer.toString(indx));
822 i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
826 i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
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 int indx = i + readIntArg(byteCodes, i);
843 emit(out, "gt = @1; continue;", Integer.toString(indx));
847 case opc_lookupswitch: {
848 int table = i / 4 * 4 + 4;
849 int dflt = i + readInt4(byteCodes, table);
851 int n = readInt4(byteCodes, table);
853 out.append("switch (").append(smapper.popI()).append(") {\n");
855 int cnstnt = readInt4(byteCodes, table);
857 int offset = i + readInt4(byteCodes, table);
859 out.append(" case " + cnstnt).append(": gt = " + offset).append("; continue;\n");
861 out.append(" default: gt = " + dflt).append("; continue;\n}");
865 case opc_tableswitch: {
866 int table = i / 4 * 4 + 4;
867 int dflt = i + readInt4(byteCodes, table);
869 int low = readInt4(byteCodes, table);
871 int high = readInt4(byteCodes, table);
873 out.append("switch (").append(smapper.popI()).append(") {\n");
874 while (low <= high) {
875 int offset = i + readInt4(byteCodes, table);
877 out.append(" case " + low).append(": gt = " + offset).append("; continue;\n");
880 out.append(" default: gt = " + dflt).append("; continue;\n}");
884 case opc_invokeinterface: {
885 i = invokeVirtualMethod(byteCodes, i, smapper) + 2;
888 case opc_invokevirtual:
889 i = invokeVirtualMethod(byteCodes, i, smapper);
891 case opc_invokespecial:
892 i = invokeStaticMethod(byteCodes, i, smapper, false);
894 case opc_invokestatic:
895 i = invokeStaticMethod(byteCodes, i, smapper, true);
898 int indx = readIntArg(byteCodes, i);
899 String ci = jc.getClassName(indx);
900 emit(out, "var @1 = new @2;",
901 smapper.pushA(), accessClass(ci.replace('/', '_')));
907 int atype = readByte(byteCodes, ++i);
910 case 4: jvmType = "[Z"; break;
911 case 5: jvmType = "[C"; break;
912 case 6: jvmType = "[F"; break;
913 case 7: jvmType = "[D"; break;
914 case 8: jvmType = "[B"; break;
915 case 9: jvmType = "[S"; break;
916 case 10: jvmType = "[I"; break;
917 case 11: jvmType = "[J"; break;
918 default: throw new IllegalStateException("Array type: " + atype);
920 emit(out, "var @2 = Array.prototype.newArray__Ljava_lang_Object_2ZLjava_lang_String_2I(true, '@3', @1);",
921 smapper.popI(), smapper.pushA(), jvmType);
923 case opc_anewarray: {
924 int type = readIntArg(byteCodes, i);
926 String typeName = jc.getClassName(type);
927 if (typeName.startsWith("[")) {
928 typeName = "[" + typeName;
930 typeName = "[L" + typeName + ";";
932 emit(out, "var @2 = Array.prototype.newArray__Ljava_lang_Object_2ZLjava_lang_String_2I(false, '@3', @1);",
933 smapper.popI(), smapper.pushA(), typeName);
936 case opc_multianewarray: {
937 int type = readIntArg(byteCodes, i);
939 String typeName = jc.getClassName(type);
940 int dim = readByte(byteCodes, ++i);
941 StringBuilder dims = new StringBuilder();
943 for (int d = 0; d < dim; d++) {
947 dims.append(smapper.popI());
950 emit(out, "var @2 = Array.prototype.multiNewArray__Ljava_lang_Object_2Ljava_lang_String_2_3II('@3', @1, 0);",
951 dims.toString(), smapper.pushA(), typeName);
954 case opc_arraylength:
955 emit(out, "var @2 = @1.length;",
956 smapper.popA(), smapper.pushI());
959 emit(out, "@3.at(@2, @1);",
960 smapper.popL(), smapper.popI(), smapper.popA());
963 emit(out, "@3.at(@2, @1);",
964 smapper.popF(), smapper.popI(), smapper.popA());
967 emit(out, "@3.at(@2, @1);",
968 smapper.popD(), smapper.popI(), smapper.popA());
971 emit(out, "@3.at(@2, @1);",
972 smapper.popA(), smapper.popI(), smapper.popA());
978 emit(out, "@3.at(@2, @1);",
979 smapper.popI(), smapper.popI(), smapper.popA());
982 emit(out, "var @3 = @2.at(@1);",
983 smapper.popI(), smapper.popA(), smapper.pushL());
986 emit(out, "var @3 = @2.at(@1);",
987 smapper.popI(), smapper.popA(), smapper.pushF());
990 emit(out, "var @3 = @2.at(@1);",
991 smapper.popI(), smapper.popA(), smapper.pushD());
994 emit(out, "var @3 = @2.at(@1);",
995 smapper.popI(), smapper.popA(), smapper.pushA());
1001 emit(out, "var @3 = @2.at(@1);",
1002 smapper.popI(), smapper.popA(), smapper.pushI());
1010 final Variable v = smapper.get(0);
1011 emit(out, "var @1 = @2;", smapper.pushT(v.getType()), v);
1015 if (smapper.get(0).isCategory2()) {
1016 final Variable v = smapper.get(0);
1017 emit(out, "var @1 = @2;",
1018 smapper.pushT(v.getType()), v);
1020 final Variable v1 = smapper.get(0);
1021 final Variable v2 = smapper.get(1);
1022 emit(out, "var @1 = @2, @3 = @4;",
1023 smapper.pushT(v2.getType()), v2,
1024 smapper.pushT(v1.getType()), v1);
1029 final Variable vi1 = smapper.pop();
1030 final Variable vi2 = smapper.pop();
1031 final Variable vo3 = smapper.pushT(vi1.getType());
1032 final Variable vo2 = smapper.pushT(vi2.getType());
1033 final Variable vo1 = smapper.pushT(vi1.getType());
1035 emit(out, "var @1 = @2, @3 = @4, @5 = @6;",
1036 vo1, vi1, vo2, vi2, vo3, vo1);
1040 if (smapper.get(1).isCategory2()) {
1041 final Variable vi1 = smapper.pop();
1042 final Variable vi2 = smapper.pop();
1043 final Variable vo3 = smapper.pushT(vi1.getType());
1044 final Variable vo2 = smapper.pushT(vi2.getType());
1045 final Variable vo1 = smapper.pushT(vi1.getType());
1047 emit(out, "var @1 = @2, @3 = @4, @5 = @6;",
1048 vo1, vi1, vo2, vi2, vo3, vo1);
1050 final Variable vi1 = smapper.pop();
1051 final Variable vi2 = smapper.pop();
1052 final Variable vi3 = smapper.pop();
1053 final Variable vo4 = smapper.pushT(vi1.getType());
1054 final Variable vo3 = smapper.pushT(vi3.getType());
1055 final Variable vo2 = smapper.pushT(vi2.getType());
1056 final Variable vo1 = smapper.pushT(vi1.getType());
1058 emit(out, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1059 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1064 emit(out, "var @1 = @2;",
1065 smapper.pushI(), Integer.toString(byteCodes[++i]));
1068 emit(out, "var @1 = @2;",
1070 Integer.toString(readIntArg(byteCodes, i)));
1073 case opc_getfield: {
1074 int indx = readIntArg(byteCodes, i);
1075 String[] fi = jc.getFieldInfoName(indx);
1076 final int type = VarType.fromFieldType(fi[2].charAt(0));
1077 emit(out, "var @2 = @1.fld_@3;",
1078 smapper.popA(), smapper.pushT(type), fi[1]);
1082 case opc_getstatic: {
1083 int indx = readIntArg(byteCodes, i);
1084 String[] fi = jc.getFieldInfoName(indx);
1085 final int type = VarType.fromFieldType(fi[2].charAt(0));
1086 emit(out, "var @1 = @2(false).constructor.@3;",
1087 smapper.pushT(type),
1088 accessClass(fi[0].replace('/', '_')), fi[1]);
1090 addReference(fi[0]);
1093 case opc_putfield: {
1094 int indx = readIntArg(byteCodes, i);
1095 String[] fi = jc.getFieldInfoName(indx);
1096 final int type = VarType.fromFieldType(fi[2].charAt(0));
1097 emit(out, "@2.fld_@3 = @1;",
1098 smapper.popT(type), smapper.popA(), fi[1]);
1102 case opc_putstatic: {
1103 int indx = readIntArg(byteCodes, i);
1104 String[] fi = jc.getFieldInfoName(indx);
1105 final int type = VarType.fromFieldType(fi[2].charAt(0));
1106 emit(out, "@1(false).constructor.@2 = @3;",
1107 accessClass(fi[0].replace('/', '_')), fi[1],
1108 smapper.popT(type));
1110 addReference(fi[0]);
1113 case opc_checkcast: {
1114 int indx = readIntArg(byteCodes, i);
1115 final String type = jc.getClassName(indx);
1116 if (!type.startsWith("[")) {
1117 // no way to check arrays right now
1118 // XXX proper exception
1120 "if (@1 !== null && !@1.$instOf_@2) throw {};",
1121 smapper.getA(0), type.replace('/', '_'));
1126 case opc_instanceof: {
1127 int indx = readIntArg(byteCodes, i);
1128 final String type = jc.getClassName(indx);
1129 emit(out, "var @2 = @1.$instOf_@3 ? 1 : 0;",
1130 smapper.popA(), smapper.pushI(),
1131 type.replace('/', '_'));
1136 final Variable v = smapper.popA();
1139 emit(out, "{ var @1 = @2; throw @2; }",
1140 smapper.pushA(), v);
1144 case opc_monitorenter: {
1145 out.append("/* monitor enter */");
1150 case opc_monitorexit: {
1151 out.append("/* monitor exit */");
1157 emit(out, "throw 'unknown bytecode @1';",
1158 Integer.toString(c));
1162 for (int j = prev; j <= i; j++) {
1164 final int cc = readByte(byteCodes, j);
1165 out.append(Integer.toString(cc));
1170 if (previousTrap != null) {
1171 generateCatch(previousTrap);
1177 private int generateIf(byte[] byteCodes, int i,
1178 final Variable v2, final Variable v1,
1179 final String test) throws IOException {
1180 int indx = i + readIntArg(byteCodes, i);
1181 out.append("if (").append(v1)
1182 .append(' ').append(test).append(' ')
1183 .append(v2).append(") { gt = " + indx)
1184 .append("; continue; }");
1188 private int readIntArg(byte[] byteCodes, int offsetInstruction) {
1189 final int indxHi = byteCodes[offsetInstruction + 1] << 8;
1190 final int indxLo = byteCodes[offsetInstruction + 2];
1191 return (indxHi & 0xffffff00) | (indxLo & 0xff);
1193 private int readInt4(byte[] byteCodes, int offsetInstruction) {
1194 final int d = byteCodes[offsetInstruction + 0] << 24;
1195 final int c = byteCodes[offsetInstruction + 1] << 16;
1196 final int b = byteCodes[offsetInstruction + 2] << 8;
1197 final int a = byteCodes[offsetInstruction + 3];
1198 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
1200 private int readByte(byte[] byteCodes, int offsetInstruction) {
1201 return byteCodes[offsetInstruction] & 0xff;
1204 private static void countArgs(String descriptor, char[] returnType, StringBuilder sig, StringBuilder cnt) {
1206 Boolean count = null;
1207 boolean array = false;
1209 int firstPos = sig.length();
1210 while (i < descriptor.length()) {
1211 char ch = descriptor.charAt(i++);
1232 if (ch == 'J' || ch == 'D') {
1238 sig.insert(firstPos, ch);
1240 returnType[0] = '[';
1241 sig.insert(firstPos, "_3");
1250 returnType[0] = 'V';
1251 sig.insert(firstPos, 'V');
1254 int next = descriptor.indexOf(';', i);
1255 String realSig = mangleSig(descriptor, i - 1, next + 1);
1260 sig.append(realSig);
1263 sig.insert(firstPos, realSig);
1265 sig.insert(firstPos, "_3");
1267 returnType[0] = 'L';
1276 throw new IllegalStateException("Invalid char: " + ch);
1281 private static String mangleSig(String txt, int first, int last) {
1282 StringBuilder sb = new StringBuilder();
1283 for (int i = first; i < last; i++) {
1284 final char ch = txt.charAt(i);
1286 case '/': sb.append('_'); break;
1287 case '_': sb.append("_1"); break;
1288 case ';': sb.append("_2"); break;
1289 case '[': sb.append("_3"); break;
1290 default: sb.append(ch); break;
1293 return sb.toString();
1296 private static String findMethodName(MethodData m, StringBuilder cnt) {
1297 StringBuilder name = new StringBuilder();
1298 if ("<init>".equals(m.getName())) { // NOI18N
1299 name.append("cons"); // NOI18N
1300 } else if ("<clinit>".equals(m.getName())) { // NOI18N
1301 name.append("class"); // NOI18N
1303 name.append(m.getName());
1306 countArgs(m.getInternalSig(), new char[1], name, cnt);
1307 return name.toString();
1310 static String findMethodName(String[] mi, StringBuilder cnt, char[] returnType) {
1311 StringBuilder name = new StringBuilder();
1312 String descr = mi[2];//mi.getDescriptor();
1314 if ("<init>".equals(nm)) { // NOI18N
1315 name.append("cons"); // NOI18N
1319 countArgs(descr, returnType, name, cnt);
1320 return name.toString();
1323 private int invokeStaticMethod(byte[] byteCodes, int i, final StackMapper mapper, boolean isStatic)
1324 throws IOException {
1325 int methodIndex = readIntArg(byteCodes, i);
1326 String[] mi = jc.getFieldInfoName(methodIndex);
1327 char[] returnType = { 'V' };
1328 StringBuilder cnt = new StringBuilder();
1329 String mn = findMethodName(mi, cnt, returnType);
1331 final int numArguments = isStatic ? cnt.length() : cnt.length() + 1;
1332 final Variable[] vars = new Variable[numArguments];
1334 for (int j = numArguments - 1; j >= 0; --j) {
1335 vars[j] = mapper.pop();
1338 if (returnType[0] != 'V') {
1340 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1344 final String in = mi[0];
1345 out.append(accessClass(in.replace('/', '_')));
1346 out.append("(false).");
1347 if (mn.startsWith("cons_")) {
1348 out.append("constructor.");
1354 out.append(".call(");
1356 if (numArguments > 0) {
1357 out.append(vars[0]);
1358 for (int j = 1; j < numArguments; ++j) {
1360 out.append(vars[j]);
1368 private int invokeVirtualMethod(byte[] byteCodes, int i, final StackMapper mapper)
1369 throws IOException {
1370 int methodIndex = readIntArg(byteCodes, i);
1371 String[] mi = jc.getFieldInfoName(methodIndex);
1372 char[] returnType = { 'V' };
1373 StringBuilder cnt = new StringBuilder();
1374 String mn = findMethodName(mi, cnt, returnType);
1376 final int numArguments = cnt.length() + 1;
1377 final Variable[] vars = new Variable[numArguments];
1379 for (int j = numArguments - 1; j >= 0; --j) {
1380 vars[j] = mapper.pop();
1383 if (returnType[0] != 'V') {
1385 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1389 out.append(vars[0]).append('.');
1393 for (int j = 1; j < numArguments; ++j) {
1395 out.append(vars[j]);
1403 private void addReference(String cn) throws IOException {
1404 if (requireReference(cn)) {
1405 debug(" /* needs " + cn + " */");
1409 private void outType(String d, StringBuilder out) {
1411 while (d.charAt(0) == '[') {
1415 if (d.charAt(0) == 'L') {
1416 assert d.charAt(d.length() - 1) == ';';
1417 out.append(d.replace('/', '_').substring(0, d.length() - 1));
1423 private String encodeConstant(int entryIndex) throws IOException {
1424 String[] classRef = { null };
1425 String s = jc.stringValue(entryIndex, classRef);
1426 if (classRef[0] != null) {
1427 addReference(classRef[0]);
1428 s = accessClass(s.replace('/', '_')) + "(false).constructor.$class";
1433 private String javaScriptBody(String prefix, MethodData m, boolean isStatic) throws IOException {
1434 byte[] arr = m.findAnnotationData(true);
1438 final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
1439 class P extends AnnotationParser {
1445 String[] args = new String[30];
1449 protected void visitAttr(String type, String attr, String at, String value) {
1450 if (type.equals(jvmType)) {
1451 if ("body".equals(attr)) {
1453 } else if ("args".equals(attr)) {
1454 args[cnt++] = value;
1456 throw new IllegalArgumentException(attr);
1463 if (p.body == null) {
1466 StringBuilder cnt = new StringBuilder();
1467 final String mn = findMethodName(m, cnt);
1468 out.append(prefix).append(mn);
1469 out.append(" = function(");
1472 for (int i = 0; i < cnt.length(); i++) {
1474 space = outputArg(out, p.args, index);
1477 out.append(") {").append("\n");
1479 out.append("\n}\n");
1482 private static String className(ClassData jc) {
1483 //return jc.getName().getInternalName().replace('/', '_');
1484 return jc.getClassName().replace('/', '_');
1487 private static String[] findAnnotation(
1488 byte[] arr, ClassData cd, final String className,
1489 final String... attrNames
1490 ) throws IOException {
1494 final String[] values = new String[attrNames.length];
1495 final boolean[] found = { false };
1496 final String jvmType = "L" + className.replace('.', '/') + ";";
1497 AnnotationParser ap = new AnnotationParser(false) {
1499 protected void visitAttr(String type, String attr, String at, String value) {
1500 if (type.equals(jvmType)) {
1502 for (int i = 0; i < attrNames.length; i++) {
1503 if (attrNames[i].equals(attr)) {
1512 return found[0] ? values : null;
1515 private CharSequence initField(FieldData v) {
1516 final String is = v.getInternalSig();
1517 if (is.length() == 1) {
1518 switch (is.charAt(0)) {
1524 case 'I': return " = 0;";
1526 case 'D': return " = 0.0;";
1528 throw new IllegalStateException(is);
1534 private static void generateAnno(ClassData cd, final Appendable out, byte[] data) throws IOException {
1535 AnnotationParser ap = new AnnotationParser(true) {
1540 protected void visitAnnotationStart(String type) throws IOException {
1544 out.append('"').append(type).append("\" : {\n");
1549 protected void visitAnnotationEnd(String type) throws IOException {
1550 out.append("\n}\n");
1554 protected void visitAttr(String type, String attr, String attrType, String value)
1555 throws IOException {
1562 out.append(attr).append("__").append(attrType).append(" : ").append(value);
1568 private static String outputArg(Appendable out, String[] args, int indx) throws IOException {
1569 final String name = args[indx];
1573 if (name.contains(",")) {
1574 throw new IOException("Wrong parameter with ',': " + name);
1580 private static void emit(final Appendable out,
1581 final String format,
1582 final CharSequence... params) throws IOException {
1583 final int length = format.length();
1586 int paramOffset = format.indexOf('@');
1587 while ((paramOffset != -1) && (paramOffset < (length - 1))) {
1588 final char paramChar = format.charAt(paramOffset + 1);
1589 if ((paramChar >= '1') && (paramChar <= '9')) {
1590 final int paramIndex = paramChar - '0' - 1;
1592 out.append(format, processed, paramOffset);
1593 out.append(params[paramIndex]);
1596 processed = paramOffset + 1;
1599 paramOffset = format.indexOf('@', paramOffset + 1);
1602 out.append(format, processed, length);
1605 private void generateCatch(TrapData[] traps) throws IOException {
1606 out.append("} catch (e) {\n");
1608 for (TrapData e : traps) {
1612 if (e.catch_cpx != 0) { //not finally
1613 final String classInternalName = jc.getClassName(e.catch_cpx);
1614 addReference(classInternalName);
1615 if ("java/lang/Throwable".equals(classInternalName)) {
1616 out.append("if (e.$instOf_java_lang_Throwable) {");
1617 out.append(" var stA0 = e;");
1618 out.append("} else {");
1619 out.append(" var stA0 = vm.java_lang_Throwable(true);");
1620 out.append(" vm.java_lang_Throwable.cons__VLjava_lang_String_2.call(stA0, e.toString());");
1622 out.append("gt=" + e.handler_pc + "; continue;");
1624 out.append("if (e.$instOf_" + classInternalName.replace('/', '_') + ") {");
1625 out.append("gt=" + e.handler_pc + "; var stA0 = e; continue;");
1629 finallyPC = e.handler_pc;
1632 if (finallyPC == -1) {
1633 out.append("throw e;");
1635 out.append("gt=" + finallyPC + "; var stA0 = e; continue;");