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 = @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 = @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 = @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 = @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 += @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 = Math.floor(@1 / @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 <<= @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 = @1;", 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;", smapper.popL(), smapper.pushI());
634 emit(out, "var @2 = @1;", smapper.popL(), smapper.pushF());
637 emit(out, "var @2 = @1;", 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 = 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 = 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 = 0;", smapper.pushL());
686 emit(out, "var @1 = 0;", smapper.pushF());
689 emit(out, "var @1 = 1;", smapper.pushI());
692 emit(out, "var @1 = 1;", 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 emit(out, "var @1 = @2;", smapper.pushT(type), v);
732 emit(out, "var @3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
733 smapper.popL(), smapper.popL(), smapper.pushI());
737 emit(out, "var @3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
738 smapper.popF(), smapper.popF(), smapper.pushI());
742 emit(out, "var @3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
743 smapper.popD(), smapper.popD(), smapper.pushI());
746 i = generateIf(byteCodes, i, smapper.popA(), smapper.popA(),
750 i = generateIf(byteCodes, i, smapper.popA(), smapper.popA(),
754 i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
758 int indx = i + readIntArg(byteCodes, i);
759 emit(out, "if (@1 == 0) { gt = @2; continue; }",
760 smapper.popI(), Integer.toString(indx));
765 int indx = i + readIntArg(byteCodes, i);
766 emit(out, "if (@1 != 0) { gt = @2; continue; }",
767 smapper.popI(), Integer.toString(indx));
772 int indx = i + readIntArg(byteCodes, i);
773 emit(out, "if (@1 < 0) { gt = @2; continue; }",
774 smapper.popI(), Integer.toString(indx));
779 int indx = i + readIntArg(byteCodes, i);
780 emit(out, "if (@1 <= 0) { gt = @2; continue; }",
781 smapper.popI(), Integer.toString(indx));
786 int indx = i + readIntArg(byteCodes, i);
787 emit(out, "if (@1 > 0) { gt = @2; continue; }",
788 smapper.popI(), Integer.toString(indx));
793 int indx = i + readIntArg(byteCodes, i);
794 emit(out, "if (@1 >= 0) { gt = @2; continue; }",
795 smapper.popI(), Integer.toString(indx));
799 case opc_ifnonnull: {
800 int indx = i + readIntArg(byteCodes, i);
801 emit(out, "if (@1 !== null) { gt = @2; continue; }",
802 smapper.popA(), Integer.toString(indx));
807 int indx = i + readIntArg(byteCodes, i);
808 emit(out, "if (@1 === null) { gt = @2; continue; }",
809 smapper.popA(), Integer.toString(indx));
814 i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
818 i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
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 int indx = i + readIntArg(byteCodes, i);
835 emit(out, "gt = @1; continue;", Integer.toString(indx));
839 case opc_lookupswitch: {
840 int table = i / 4 * 4 + 4;
841 int dflt = i + readInt4(byteCodes, table);
843 int n = readInt4(byteCodes, table);
845 out.append("switch (").append(smapper.popI()).append(") {\n");
847 int cnstnt = readInt4(byteCodes, table);
849 int offset = i + readInt4(byteCodes, table);
851 out.append(" case " + cnstnt).append(": gt = " + offset).append("; continue;\n");
853 out.append(" default: gt = " + dflt).append("; continue;\n}");
857 case opc_tableswitch: {
858 int table = i / 4 * 4 + 4;
859 int dflt = i + readInt4(byteCodes, table);
861 int low = readInt4(byteCodes, table);
863 int high = readInt4(byteCodes, table);
865 out.append("switch (").append(smapper.popI()).append(") {\n");
866 while (low <= high) {
867 int offset = i + readInt4(byteCodes, table);
869 out.append(" case " + low).append(": gt = " + offset).append("; continue;\n");
872 out.append(" default: gt = " + dflt).append("; continue;\n}");
876 case opc_invokeinterface: {
877 i = invokeVirtualMethod(byteCodes, i, smapper) + 2;
880 case opc_invokevirtual:
881 i = invokeVirtualMethod(byteCodes, i, smapper);
883 case opc_invokespecial:
884 i = invokeStaticMethod(byteCodes, i, smapper, false);
886 case opc_invokestatic:
887 i = invokeStaticMethod(byteCodes, i, smapper, true);
890 int indx = readIntArg(byteCodes, i);
891 String ci = jc.getClassName(indx);
892 emit(out, "var @1 = new @2;",
893 smapper.pushA(), accessClass(ci.replace('/', '_')));
899 int atype = readByte(byteCodes, ++i);
902 case 4: jvmType = "[Z"; break;
903 case 5: jvmType = "[C"; break;
904 case 6: jvmType = "[F"; break;
905 case 7: jvmType = "[D"; break;
906 case 8: jvmType = "[B"; break;
907 case 9: jvmType = "[S"; break;
908 case 10: jvmType = "[I"; break;
909 case 11: jvmType = "[J"; break;
910 default: throw new IllegalStateException("Array type: " + atype);
912 emit(out, "var @2 = Array.prototype.newArray__Ljava_lang_Object_2ZLjava_lang_String_2I(true, '@3', @1);",
913 smapper.popI(), smapper.pushA(), jvmType);
915 case opc_anewarray: {
916 int type = readIntArg(byteCodes, i);
918 String typeName = jc.getClassName(type);
919 if (typeName.startsWith("[")) {
920 typeName = "[" + typeName;
922 typeName = "[L" + typeName + ";";
924 emit(out, "var @2 = Array.prototype.newArray__Ljava_lang_Object_2ZLjava_lang_String_2I(false, '@3', @1);",
925 smapper.popI(), smapper.pushA(), typeName);
928 case opc_multianewarray: {
929 int type = readIntArg(byteCodes, i);
931 String typeName = jc.getClassName(type);
932 int dim = readByte(byteCodes, ++i);
933 StringBuilder dims = new StringBuilder();
935 for (int d = 0; d < dim; d++) {
939 dims.append(smapper.popI());
942 emit(out, "var @2 = Array.prototype.multiNewArray__Ljava_lang_Object_2Ljava_lang_String_2_3II('@3', @1, 0);",
943 dims.toString(), smapper.pushA(), typeName);
946 case opc_arraylength:
947 emit(out, "var @2 = @1.length;",
948 smapper.popA(), smapper.pushI());
951 emit(out, "@3.at(@2, @1);",
952 smapper.popL(), smapper.popI(), smapper.popA());
955 emit(out, "@3.at(@2, @1);",
956 smapper.popF(), smapper.popI(), smapper.popA());
959 emit(out, "@3.at(@2, @1);",
960 smapper.popD(), smapper.popI(), smapper.popA());
963 emit(out, "@3.at(@2, @1);",
964 smapper.popA(), smapper.popI(), smapper.popA());
970 emit(out, "@3.at(@2, @1);",
971 smapper.popI(), smapper.popI(), smapper.popA());
974 emit(out, "var @3 = @2.at(@1);",
975 smapper.popI(), smapper.popA(), smapper.pushL());
978 emit(out, "var @3 = @2.at(@1);",
979 smapper.popI(), smapper.popA(), smapper.pushF());
982 emit(out, "var @3 = @2.at(@1);",
983 smapper.popI(), smapper.popA(), smapper.pushD());
986 emit(out, "var @3 = @2.at(@1);",
987 smapper.popI(), smapper.popA(), smapper.pushA());
993 emit(out, "var @3 = @2.at(@1);",
994 smapper.popI(), smapper.popA(), smapper.pushI());
1002 final Variable v = smapper.get(0);
1003 emit(out, "var @1 = @2;", smapper.pushT(v.getType()), v);
1007 if (smapper.get(0).isCategory2()) {
1008 final Variable v = smapper.get(0);
1009 emit(out, "var @1 = @2;",
1010 smapper.pushT(v.getType()), v);
1012 final Variable v1 = smapper.get(0);
1013 final Variable v2 = smapper.get(1);
1014 emit(out, "var @1 = @2, @3 = @4;",
1015 smapper.pushT(v2.getType()), v2,
1016 smapper.pushT(v1.getType()), v1);
1021 final Variable vi1 = smapper.pop();
1022 final Variable vi2 = smapper.pop();
1023 final Variable vo3 = smapper.pushT(vi1.getType());
1024 final Variable vo2 = smapper.pushT(vi2.getType());
1025 final Variable vo1 = smapper.pushT(vi1.getType());
1027 emit(out, "var @1 = @2, @3 = @4, @5 = @6;",
1028 vo1, vi1, vo2, vi2, vo3, vo1);
1032 if (smapper.get(1).isCategory2()) {
1033 final Variable vi1 = smapper.pop();
1034 final Variable vi2 = smapper.pop();
1035 final Variable vo3 = smapper.pushT(vi1.getType());
1036 final Variable vo2 = smapper.pushT(vi2.getType());
1037 final Variable vo1 = smapper.pushT(vi1.getType());
1039 emit(out, "var @1 = @2, @3 = @4, @5 = @6;",
1040 vo1, vi1, vo2, vi2, vo3, vo1);
1042 final Variable vi1 = smapper.pop();
1043 final Variable vi2 = smapper.pop();
1044 final Variable vi3 = smapper.pop();
1045 final Variable vo4 = smapper.pushT(vi1.getType());
1046 final Variable vo3 = smapper.pushT(vi3.getType());
1047 final Variable vo2 = smapper.pushT(vi2.getType());
1048 final Variable vo1 = smapper.pushT(vi1.getType());
1050 emit(out, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1051 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1056 emit(out, "var @1 = @2;",
1057 smapper.pushI(), Integer.toString(byteCodes[++i]));
1060 emit(out, "var @1 = @2;",
1062 Integer.toString(readIntArg(byteCodes, i)));
1065 case opc_getfield: {
1066 int indx = readIntArg(byteCodes, i);
1067 String[] fi = jc.getFieldInfoName(indx);
1068 final int type = VarType.fromFieldType(fi[2].charAt(0));
1069 emit(out, "var @2 = @1.fld_@3;",
1070 smapper.popA(), smapper.pushT(type), fi[1]);
1074 case opc_getstatic: {
1075 int indx = readIntArg(byteCodes, i);
1076 String[] fi = jc.getFieldInfoName(indx);
1077 final int type = VarType.fromFieldType(fi[2].charAt(0));
1078 emit(out, "var @1 = @2(false).constructor.@3;",
1079 smapper.pushT(type),
1080 accessClass(fi[0].replace('/', '_')), fi[1]);
1082 addReference(fi[0]);
1085 case opc_putfield: {
1086 int indx = readIntArg(byteCodes, i);
1087 String[] fi = jc.getFieldInfoName(indx);
1088 final int type = VarType.fromFieldType(fi[2].charAt(0));
1089 emit(out, "@2.fld_@3 = @1;",
1090 smapper.popT(type), smapper.popA(), fi[1]);
1094 case opc_putstatic: {
1095 int indx = readIntArg(byteCodes, i);
1096 String[] fi = jc.getFieldInfoName(indx);
1097 final int type = VarType.fromFieldType(fi[2].charAt(0));
1098 emit(out, "@1(false).constructor.@2 = @3;",
1099 accessClass(fi[0].replace('/', '_')), fi[1],
1100 smapper.popT(type));
1102 addReference(fi[0]);
1105 case opc_checkcast: {
1106 int indx = readIntArg(byteCodes, i);
1107 final String type = jc.getClassName(indx);
1108 if (!type.startsWith("[")) {
1109 // no way to check arrays right now
1110 // XXX proper exception
1112 "if (@1 !== null && !@1.$instOf_@2) throw {};",
1113 smapper.getA(0), type.replace('/', '_'));
1118 case opc_instanceof: {
1119 int indx = readIntArg(byteCodes, i);
1120 final String type = jc.getClassName(indx);
1121 emit(out, "var @2 = @1.$instOf_@3 ? 1 : 0;",
1122 smapper.popA(), smapper.pushI(),
1123 type.replace('/', '_'));
1128 final Variable v = smapper.popA();
1131 emit(out, "{ var @1 = @2; throw @2; }",
1132 smapper.pushA(), v);
1136 case opc_monitorenter: {
1137 out.append("/* monitor enter */");
1142 case opc_monitorexit: {
1143 out.append("/* monitor exit */");
1149 emit(out, "throw 'unknown bytecode @1';",
1150 Integer.toString(c));
1154 for (int j = prev; j <= i; j++) {
1156 final int cc = readByte(byteCodes, j);
1157 out.append(Integer.toString(cc));
1162 if (previousTrap != null) {
1163 generateCatch(previousTrap);
1169 private int generateIf(byte[] byteCodes, int i,
1170 final Variable v2, final Variable v1,
1171 final String test) throws IOException {
1172 int indx = i + readIntArg(byteCodes, i);
1173 out.append("if (").append(v1)
1174 .append(' ').append(test).append(' ')
1175 .append(v2).append(") { gt = " + indx)
1176 .append("; continue; }");
1180 private int readIntArg(byte[] byteCodes, int offsetInstruction) {
1181 final int indxHi = byteCodes[offsetInstruction + 1] << 8;
1182 final int indxLo = byteCodes[offsetInstruction + 2];
1183 return (indxHi & 0xffffff00) | (indxLo & 0xff);
1185 private int readInt4(byte[] byteCodes, int offsetInstruction) {
1186 final int d = byteCodes[offsetInstruction + 0] << 24;
1187 final int c = byteCodes[offsetInstruction + 1] << 16;
1188 final int b = byteCodes[offsetInstruction + 2] << 8;
1189 final int a = byteCodes[offsetInstruction + 3];
1190 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
1192 private int readByte(byte[] byteCodes, int offsetInstruction) {
1193 return byteCodes[offsetInstruction] & 0xff;
1196 private static void countArgs(String descriptor, char[] returnType, StringBuilder sig, StringBuilder cnt) {
1198 Boolean count = null;
1199 boolean array = false;
1201 int firstPos = sig.length();
1202 while (i < descriptor.length()) {
1203 char ch = descriptor.charAt(i++);
1224 if (ch == 'J' || ch == 'D') {
1230 sig.insert(firstPos, ch);
1232 returnType[0] = '[';
1233 sig.insert(firstPos, "_3");
1242 returnType[0] = 'V';
1243 sig.insert(firstPos, 'V');
1246 int next = descriptor.indexOf(';', i);
1247 String realSig = mangleSig(descriptor, i - 1, next + 1);
1252 sig.append(realSig);
1255 sig.insert(firstPos, realSig);
1257 sig.insert(firstPos, "_3");
1259 returnType[0] = 'L';
1268 throw new IllegalStateException("Invalid char: " + ch);
1273 private static String mangleSig(String txt, int first, int last) {
1274 StringBuilder sb = new StringBuilder();
1275 for (int i = first; i < last; i++) {
1276 final char ch = txt.charAt(i);
1278 case '/': sb.append('_'); break;
1279 case '_': sb.append("_1"); break;
1280 case ';': sb.append("_2"); break;
1281 case '[': sb.append("_3"); break;
1282 default: sb.append(ch); break;
1285 return sb.toString();
1288 private static String findMethodName(MethodData m, StringBuilder cnt) {
1289 StringBuilder name = new StringBuilder();
1290 if ("<init>".equals(m.getName())) { // NOI18N
1291 name.append("cons"); // NOI18N
1292 } else if ("<clinit>".equals(m.getName())) { // NOI18N
1293 name.append("class"); // NOI18N
1295 name.append(m.getName());
1298 countArgs(m.getInternalSig(), new char[1], name, cnt);
1299 return name.toString();
1302 static String findMethodName(String[] mi, StringBuilder cnt, char[] returnType) {
1303 StringBuilder name = new StringBuilder();
1304 String descr = mi[2];//mi.getDescriptor();
1306 if ("<init>".equals(nm)) { // NOI18N
1307 name.append("cons"); // NOI18N
1311 countArgs(descr, returnType, name, cnt);
1312 return name.toString();
1315 private int invokeStaticMethod(byte[] byteCodes, int i, final StackMapper mapper, boolean isStatic)
1316 throws IOException {
1317 int methodIndex = readIntArg(byteCodes, i);
1318 String[] mi = jc.getFieldInfoName(methodIndex);
1319 char[] returnType = { 'V' };
1320 StringBuilder cnt = new StringBuilder();
1321 String mn = findMethodName(mi, cnt, returnType);
1323 final int numArguments = isStatic ? cnt.length() : cnt.length() + 1;
1324 final Variable[] vars = new Variable[numArguments];
1326 for (int j = numArguments - 1; j >= 0; --j) {
1327 vars[j] = mapper.pop();
1330 if (returnType[0] != 'V') {
1332 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1336 final String in = mi[0];
1337 out.append(accessClass(in.replace('/', '_')));
1338 out.append("(false).");
1339 if (mn.startsWith("cons_")) {
1340 out.append("constructor.");
1346 out.append(".call(");
1348 if (numArguments > 0) {
1349 out.append(vars[0]);
1350 for (int j = 1; j < numArguments; ++j) {
1352 out.append(vars[j]);
1360 private int invokeVirtualMethod(byte[] byteCodes, int i, final StackMapper mapper)
1361 throws IOException {
1362 int methodIndex = readIntArg(byteCodes, i);
1363 String[] mi = jc.getFieldInfoName(methodIndex);
1364 char[] returnType = { 'V' };
1365 StringBuilder cnt = new StringBuilder();
1366 String mn = findMethodName(mi, cnt, returnType);
1368 final int numArguments = cnt.length() + 1;
1369 final Variable[] vars = new Variable[numArguments];
1371 for (int j = numArguments - 1; j >= 0; --j) {
1372 vars[j] = mapper.pop();
1375 if (returnType[0] != 'V') {
1377 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1381 out.append(vars[0]).append('.');
1385 for (int j = 1; j < numArguments; ++j) {
1387 out.append(vars[j]);
1395 private void addReference(String cn) throws IOException {
1396 if (requireReference(cn)) {
1397 debug(" /* needs " + cn + " */");
1401 private void outType(String d, StringBuilder out) {
1403 while (d.charAt(0) == '[') {
1407 if (d.charAt(0) == 'L') {
1408 assert d.charAt(d.length() - 1) == ';';
1409 out.append(d.replace('/', '_').substring(0, d.length() - 1));
1415 private String encodeConstant(int entryIndex) throws IOException {
1416 String[] classRef = { null };
1417 String s = jc.stringValue(entryIndex, classRef);
1418 if (classRef[0] != null) {
1419 addReference(classRef[0]);
1420 s = accessClass(s.replace('/', '_')) + "(false).constructor.$class";
1425 private String javaScriptBody(String prefix, MethodData m, boolean isStatic) throws IOException {
1426 byte[] arr = m.findAnnotationData(true);
1430 final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
1431 class P extends AnnotationParser {
1437 String[] args = new String[30];
1441 protected void visitAttr(String type, String attr, String at, String value) {
1442 if (type.equals(jvmType)) {
1443 if ("body".equals(attr)) {
1445 } else if ("args".equals(attr)) {
1446 args[cnt++] = value;
1448 throw new IllegalArgumentException(attr);
1455 if (p.body == null) {
1458 StringBuilder cnt = new StringBuilder();
1459 final String mn = findMethodName(m, cnt);
1460 out.append(prefix).append(mn);
1461 out.append(" = function(");
1464 for (int i = 0; i < cnt.length(); i++) {
1466 space = outputArg(out, p.args, index);
1469 out.append(") {").append("\n");
1471 out.append("\n}\n");
1474 private static String className(ClassData jc) {
1475 //return jc.getName().getInternalName().replace('/', '_');
1476 return jc.getClassName().replace('/', '_');
1479 private static String[] findAnnotation(
1480 byte[] arr, ClassData cd, final String className,
1481 final String... attrNames
1482 ) throws IOException {
1486 final String[] values = new String[attrNames.length];
1487 final boolean[] found = { false };
1488 final String jvmType = "L" + className.replace('.', '/') + ";";
1489 AnnotationParser ap = new AnnotationParser(false) {
1491 protected void visitAttr(String type, String attr, String at, String value) {
1492 if (type.equals(jvmType)) {
1494 for (int i = 0; i < attrNames.length; i++) {
1495 if (attrNames[i].equals(attr)) {
1504 return found[0] ? values : null;
1507 private CharSequence initField(FieldData v) {
1508 final String is = v.getInternalSig();
1509 if (is.length() == 1) {
1510 switch (is.charAt(0)) {
1516 case 'I': return " = 0;";
1518 case 'D': return " = 0.0;";
1520 throw new IllegalStateException(is);
1526 private static void generateAnno(ClassData cd, final Appendable out, byte[] data) throws IOException {
1527 AnnotationParser ap = new AnnotationParser(true) {
1532 protected void visitAnnotationStart(String type) throws IOException {
1536 out.append('"').append(type).append("\" : {\n");
1541 protected void visitAnnotationEnd(String type) throws IOException {
1542 out.append("\n}\n");
1546 protected void visitAttr(String type, String attr, String attrType, String value)
1547 throws IOException {
1554 out.append(attr).append("__").append(attrType).append(" : ").append(value);
1560 private static String outputArg(Appendable out, String[] args, int indx) throws IOException {
1561 final String name = args[indx];
1565 if (name.contains(",")) {
1566 throw new IOException("Wrong parameter with ',': " + name);
1572 private static void emit(final Appendable out,
1573 final String format,
1574 final CharSequence... params) throws IOException {
1575 final int length = format.length();
1578 int paramOffset = format.indexOf('@');
1579 while ((paramOffset != -1) && (paramOffset < (length - 1))) {
1580 final char paramChar = format.charAt(paramOffset + 1);
1581 if ((paramChar >= '1') && (paramChar <= '9')) {
1582 final int paramIndex = paramChar - '0' - 1;
1584 out.append(format, processed, paramOffset);
1585 out.append(params[paramIndex]);
1588 processed = paramOffset + 1;
1591 paramOffset = format.indexOf('@', paramOffset + 1);
1594 out.append(format, processed, length);
1597 private void generateCatch(TrapData[] traps) throws IOException {
1598 out.append("} catch (e) {\n");
1600 for (TrapData e : traps) {
1604 if (e.catch_cpx != 0) { //not finally
1605 final String classInternalName = jc.getClassName(e.catch_cpx);
1606 addReference(classInternalName);
1607 if ("java/lang/Throwable".equals(classInternalName)) {
1608 out.append("if (e.$instOf_java_lang_Throwable) {");
1609 out.append(" var stA0 = e;");
1610 out.append("} else {");
1611 out.append(" var stA0 = vm.java_lang_Throwable(true);");
1612 out.append(" vm.java_lang_Throwable.cons__VLjava_lang_String_2.call(stA0, e.toString());");
1614 out.append("gt=" + e.handler_pc + "; continue;");
1616 out.append("if (e.$instOf_" + classInternalName.replace('/', '_') + ") {");
1617 out.append("gt=" + e.handler_pc + "; var stA0 = e; continue;");
1621 finallyPC = e.handler_pc;
1624 if (finallyPC == -1) {
1625 out.append("throw e;");
1627 out.append("gt=" + finallyPC + "; var stA0 = e; continue;");