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 static org.apidesign.javap.RuntimeConstants.*;
28 /** Translator of the code inside class files to JavaScript.
30 * @author Jaroslav Tulach <jtulach@netbeans.org>
32 public abstract class ByteCodeToJavaScript {
34 private final Appendable out;
36 protected ByteCodeToJavaScript(Appendable out) {
40 /* Collects additional required resources.
42 * @param internalClassName classes that were referenced and should be loaded in order the
43 * generated JavaScript code works properly. The names are in internal
44 * JVM form so String is <code>java/lang/String</code>.
46 protected abstract boolean requireReference(String internalClassName);
49 * @param resourcePath name of resources to read
51 protected abstract void requireScript(String resourcePath);
54 * Converts a given class file to a JavaScript version.
56 * @param classFile input stream with code of the .class file
57 * @return the initialization code for this class, if any. Otherwise <code>null</code>
59 * @throws IOException if something goes wrong during read or write or translating
62 public String compile(InputStream classFile) throws IOException {
63 this.jc = new ClassData(classFile);
64 byte[] arrData = jc.findAnnotationData(true);
65 String[] arr = findAnnotation(arrData, jc,
66 "org.apidesign.bck2brwsr.core.ExtraJavaScript",
67 "resource", "processByteCode"
70 requireScript(arr[0]);
71 if ("0".equals(arr[1])) {
75 StringArray toInitilize = new StringArray();
76 final String className = className(jc);
77 out.append("\n\nfunction ").append(className).append("() {");
78 out.append("\n if (!").append(className).
79 append(".prototype.$instOf_").append(className).append(") {");
80 for (FieldData v : jc.getFields()) {
82 generateStaticField(v);
85 // ClassName sc = jc.getSuperClass();
86 String sc = jc.getSuperClassName(); // with _
88 out.append("\n var p = ").append(className)
89 .append(".prototype = ").
90 append(sc.replace('/', '_')).append("(true);");
92 out.append("\n var p = ").append(className).append(".prototype;");
94 for (MethodData m : jc.getMethods()) {
96 generateStaticMethod("\n p.", m, toInitilize);
98 generateInstanceMethod("\n p.", m);
101 out.append("\n p.$instOf_").append(className).append(" = true;");
102 for (String superInterface : jc.getSuperInterfaces()) {
103 out.append("\n p.$instOf_").append(superInterface.replace('/', '_')).append(" = true;");
105 out.append("\n if (arguments.length === 0) {");
106 out.append("\n return new ").append(className).append("();");
109 out.append("\n if (arguments.length === 0) {");
110 for (FieldData v : jc.getFields()) {
112 out.append("\n this.fld_").
113 append(v.getName()).append(initField(v));
116 out.append("\n return this;");
118 out.append("\n return new ").append(className).append(";");
120 StringBuilder sb = new StringBuilder();
121 for (String init : toInitilize.toArray()) {
122 sb.append("\n").append(init).append("();");
124 return sb.toString();
126 private void generateStaticMethod(String prefix, MethodData m, StringArray toInitilize) throws IOException {
127 if (javaScriptBody(prefix, m, true)) {
130 StringBuilder argsCnt = new StringBuilder();
131 final String mn = findMethodName(m, argsCnt);
132 out.append(prefix).append(mn).append(" = function");
133 if (mn.equals("classV")) {
134 toInitilize.add(className(jc) + "(true)." + mn);
138 for (int index = 0, i = 0; i < argsCnt.length(); i++) {
140 out.append("arg").append(String.valueOf(index));
142 final String desc = null;// XXX findDescriptor(args.get(i).getDescriptor());
143 if (argsCnt.charAt(i) == '1') {
149 out.append(") {").append("\n");
150 final byte[] code = m.getCode();
152 int len = m.getMaxLocals();
153 for (int index = argsCnt.length(), i = argsCnt.length(); i < len; i++) {
155 out.append("arg").append(String.valueOf(i)).append(";\n");
157 out.append(" var stack = new Array();\n");
160 out.append(" /* no code found for ").append(m.getInternalSig()).append(" */\n");
165 private void generateInstanceMethod(String prefix, MethodData m) throws IOException {
166 if (javaScriptBody(prefix, m, false)) {
169 StringBuilder argsCnt = new StringBuilder();
170 final String mn = findMethodName(m, argsCnt);
171 out.append(prefix).append(mn).append(" = function");
174 for (int index = 1, i = 0; i < argsCnt.length(); i++) {
176 out.append("arg").append(String.valueOf(index));
177 if (argsCnt.charAt(i) == '1') {
183 out.append(") {").append("\n");
184 final byte[] code = m.getCode();
186 int len = m.getMaxLocals();
187 for (int index = argsCnt.length(), i = argsCnt.length(); i < len; i++) {
189 out.append("arg").append(String.valueOf(i + 1)).append(";\n");
191 out.append(";\n var stack = new Array();\n");
194 out.append(" /* no code found for ").append(m.getInternalSig()).append(" */\n");
199 private void produceCode(byte[] byteCodes) throws IOException {
200 out.append("\n var gt = 0;\n for(;;) switch(gt) {\n");
201 for (int i = 0; i < byteCodes.length; i++) {
203 out.append(" case " + i).append(": ");
204 final int c = readByte(byteCodes, i);
211 out.append("stack.push(arg0);");
218 out.append("stack.push(arg1);");
225 out.append("stack.push(arg2);");
232 out.append("stack.push(arg3);");
239 final int indx = readByte(byteCodes, ++i);
240 out.append("stack.push(arg").append(indx + ");");
248 final int indx = readByte(byteCodes, ++i);
249 out.append("arg" + indx).append(" = stack.pop();");
257 out.append("arg0 = stack.pop();");
264 out.append("arg1 = stack.pop();");
271 out.append("arg2 = stack.pop();");
278 out.append("arg3 = stack.pop();");
284 out.append("stack.push(stack.pop() + stack.pop());");
290 out.append("{ var tmp = stack.pop(); stack.push(stack.pop() - tmp); }");
296 out.append("stack.push(stack.pop() * stack.pop());");
300 out.append("{ var tmp = stack.pop(); stack.push(Math.floor(stack.pop() / tmp)); }");
304 out.append("{ var tmp = stack.pop(); stack.push(stack.pop() / tmp); }");
310 out.append("{ var d = stack.pop(); stack.push(stack.pop() % d); }");
314 out.append("stack.push(stack.pop() & stack.pop());");
318 out.append("stack.push(stack.pop() | stack.pop());");
322 out.append("stack.push(stack.pop() ^ stack.pop());");
328 out.append("stack.push(- stack.pop());");
332 out.append("{ var v = stack.pop(); stack.push(stack.pop() << v); }");
336 out.append("{ var v = stack.pop(); stack.push(stack.pop() >> v); }");
340 out.append("{ var v = stack.pop(); stack.push(stack.pop() >>> v); }");
343 final int varIndx = readByte(byteCodes, ++i);
344 final int incrBy = byteCodes[++i];
346 out.append("arg" + varIndx).append("++;");
348 out.append("arg" + varIndx).append(" += " + incrBy).append(";");
353 out.append("return;");
360 out.append("return stack.pop();");
371 out.append("/* number conversion */");
377 out.append("stack.push(Math.floor(stack.pop()));");
382 out.append("/* number conversion */");
384 case opc_aconst_null:
385 out.append("stack.push(null);");
388 out.append("stack.push(-1);");
394 out.append("stack.push(0);");
400 out.append("stack.push(1);");
404 out.append("stack.push(2);");
407 out.append("stack.push(3);");
410 out.append("stack.push(4);");
413 out.append("stack.push(5);");
416 int indx = readByte(byteCodes, ++i);
417 String v = encodeConstant(indx);
418 out.append("stack.push(").append(v).append(");");
423 int indx = readIntArg(byteCodes, i);
425 String v = encodeConstant(indx);
426 out.append("stack.push(").append(v).append(");");
434 out.append("{ var delta = stack.pop() - stack.pop(); stack.push(delta < 0 ?-1 : (delta == 0 ? 0 : 1)); }");
438 i = generateIf(byteCodes, i, "===");
441 i = generateIf(byteCodes, i, "!=");
443 case opc_if_icmpeq: {
444 i = generateIf(byteCodes, i, "==");
448 int indx = i + readIntArg(byteCodes, i);
449 out.append("if (stack.pop() == 0) { gt = " + indx);
450 out.append("; continue; }");
455 int indx = i + readIntArg(byteCodes, i);
456 out.append("if (stack.pop() != 0) { gt = " + indx);
457 out.append("; continue; }");
462 int indx = i + readIntArg(byteCodes, i);
463 out.append("if (stack.pop() < 0) { gt = " + indx);
464 out.append("; continue; }");
469 int indx = i + readIntArg(byteCodes, i);
470 out.append("if (stack.pop() <= 0) { gt = " + indx);
471 out.append("; continue; }");
476 int indx = i + readIntArg(byteCodes, i);
477 out.append("if (stack.pop() > 0) { gt = " + indx);
478 out.append("; continue; }");
483 int indx = i + readIntArg(byteCodes, i);
484 out.append("if (stack.pop() >= 0) { gt = " + indx);
485 out.append("; continue; }");
489 case opc_ifnonnull: {
490 int indx = i + readIntArg(byteCodes, i);
491 out.append("if (stack.pop() !== null) { gt = " + indx);
492 out.append("; continue; }");
497 int indx = i + readIntArg(byteCodes, i);
498 out.append("if (stack.pop() === null) { gt = " + indx);
499 out.append("; continue; }");
504 i = generateIf(byteCodes, i, "!=");
507 i = generateIf(byteCodes, i, ">");
510 i = generateIf(byteCodes, i, ">=");
513 i = generateIf(byteCodes, i, "<");
516 i = generateIf(byteCodes, i, "<=");
519 int indx = i + readIntArg(byteCodes, i);
520 out.append("gt = " + indx).append("; continue;");
524 case opc_lookupswitch: {
525 int table = i / 4 * 4 + 4;
526 int dflt = i + readInt4(byteCodes, table);
528 int n = readInt4(byteCodes, table);
530 out.append("switch (stack.pop()) {\n");
532 int cnstnt = readInt4(byteCodes, table);
534 int offset = i + readInt4(byteCodes, table);
536 out.append(" case " + cnstnt).append(": gt = " + offset).append("; continue;\n");
538 out.append(" default: gt = " + dflt).append("; continue;\n}");
542 case opc_tableswitch: {
543 int table = i / 4 * 4 + 4;
544 int dflt = i + readInt4(byteCodes, table);
546 int low = readInt4(byteCodes, table);
548 int high = readInt4(byteCodes, table);
550 out.append("switch (stack.pop()) {\n");
551 while (low <= high) {
552 int offset = i + readInt4(byteCodes, table);
554 out.append(" case " + low).append(": gt = " + offset).append("; continue;\n");
557 out.append(" default: gt = " + dflt).append("; continue;\n}");
561 case opc_invokeinterface: {
562 i = invokeVirtualMethod(byteCodes, i) + 2;
565 case opc_invokevirtual:
566 i = invokeVirtualMethod(byteCodes, i);
568 case opc_invokespecial:
569 i = invokeStaticMethod(byteCodes, i, false);
571 case opc_invokestatic:
572 i = invokeStaticMethod(byteCodes, i, true);
575 int indx = readIntArg(byteCodes, i);
576 String ci = jc.getClassName(indx);
577 out.append("stack.push(");
578 out.append("new ").append(ci.replace('/','_'));
585 int type = byteCodes[i++];
586 out.append("stack.push(new Array(stack.pop()).fillNulls());");
589 case opc_anewarray: {
590 i += 2; // skip type of array
591 out.append("stack.push(new Array(stack.pop()).fillNulls());");
594 case opc_multianewarray: {
596 int dim = readByte(byteCodes, ++i);
597 out.append("{ var a0 = new Array(stack.pop()).fillNulls();");
598 for (int d = 1; d < dim; d++) {
599 out.append("\n var l" + d).append(" = stack.pop();");
600 out.append("\n for (var i" + d).append (" = 0; i" + d).
601 append(" < a" + (d - 1)).
602 append(".length; i" + d).append("++) {");
603 out.append("\n var a" + d).
604 append (" = new Array(l" + d).append(").fillNulls();");
605 out.append("\n a" + (d - 1)).append("[i" + d).append("] = a" + d).
608 for (int d = 1; d < dim; d++) {
611 out.append("\nstack.push(a0); }");
614 case opc_arraylength:
615 out.append("stack.push(stack.pop().length);");
625 out.append("{ var value = stack.pop(); var indx = stack.pop(); stack.pop()[indx] = value; }");
636 out.append("{ var indx = stack.pop(); stack.push(stack.pop()[indx]); }");
640 out.append("stack.pop();");
642 out.append("stack.pop();");
645 out.append("stack.push(stack[stack.length - 1]);");
648 out.append("{ var v1 = stack.pop(); var v2 = stack.pop(); stack.push(v1); stack.push(v2); stack.push(v1); }");
651 out.append("{ var v1 = stack.pop(); var v2 = stack.pop(); var v3 = stack.pop(); stack.push(v1); stack.push(v3); stack.push(v2); stack.push(v1); }");
654 out.append("stack.push(" + byteCodes[++i] + ");");
657 out.append("stack.push(" + readIntArg(byteCodes, i) + ");");
661 int indx = readIntArg(byteCodes, i);
662 String[] fi = jc.getFieldInfoName(indx);
663 out.append("stack.push(stack.pop().fld_").
664 append(fi[1]).append(");");
668 case opc_getstatic: {
669 int indx = readIntArg(byteCodes, i);
670 String[] fi = jc.getFieldInfoName(indx);
671 out.append("stack.push(").append(fi[0].replace('/', '_'));
672 out.append('.').append(fi[1]).append(");");
677 case opc_putstatic: {
678 int indx = readIntArg(byteCodes, i);
679 String[] fi = jc.getFieldInfoName(indx);
680 out.append(fi[0].replace('/', '_'));
681 out.append('.').append(fi[1]).append(" = stack.pop();");
687 int indx = readIntArg(byteCodes, i);
688 String[] fi = jc.getFieldInfoName(indx);
689 out.append("{ var v = stack.pop(); stack.pop().fld_")
690 .append(fi[1]).append(" = v; }");
694 case opc_checkcast: {
695 int indx = readIntArg(byteCodes, i);
696 final String type = jc.getClassName(indx);
697 if (!type.startsWith("[")) {
698 // no way to check arrays right now
699 out.append("if(stack[stack.length - 1].$instOf_")
700 .append(type.replace('/', '_'))
701 .append(" != 1) throw {};"); // XXX proper exception
706 case opc_instanceof: {
707 int indx = readIntArg(byteCodes, i);
708 final String type = jc.getClassName(indx);
709 out.append("stack.push(stack.pop().$instOf_")
710 .append(type.replace('/', '_'))
711 .append(" ? 1 : 0);");
716 out.append("{ var t = stack.pop(); stack = new Array(1); stack[0] = t; throw t; }");
720 out.append("throw 'unknown bytecode " + c + "';");
725 for (int j = prev; j <= i; j++) {
727 final int cc = readByte(byteCodes, j);
728 out.append(Integer.toString(cc));
735 private int generateIf(byte[] byteCodes, int i, final String test) throws IOException {
736 int indx = i + readIntArg(byteCodes, i);
737 out.append("if (stack.pop() ").append(test).append(" stack.pop()) { gt = " + indx);
738 out.append("; continue; }");
742 private int readIntArg(byte[] byteCodes, int offsetInstruction) {
743 final int indxHi = byteCodes[offsetInstruction + 1] << 8;
744 final int indxLo = byteCodes[offsetInstruction + 2];
745 return (indxHi & 0xffffff00) | (indxLo & 0xff);
747 private int readInt4(byte[] byteCodes, int offsetInstruction) {
748 final int d = byteCodes[offsetInstruction + 0] << 24;
749 final int c = byteCodes[offsetInstruction + 1] << 16;
750 final int b = byteCodes[offsetInstruction + 2] << 8;
751 final int a = byteCodes[offsetInstruction + 3];
752 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
754 private int readByte(byte[] byteCodes, int offsetInstruction) {
755 return (byteCodes[offsetInstruction] + 256) % 256;
758 private static void countArgs(String descriptor, boolean[] hasReturnType, StringBuilder sig, StringBuilder cnt) {
760 Boolean count = null;
761 boolean array = false;
762 int firstPos = sig.length();
763 while (i < descriptor.length()) {
764 char ch = descriptor.charAt(i++);
788 if (ch == 'J' || ch == 'D') {
794 hasReturnType[0] = true;
795 sig.insert(firstPos, ch);
797 sig.insert(firstPos, 'A');
804 hasReturnType[0] = false;
805 sig.insert(firstPos, 'V');
808 int next = descriptor.indexOf(';', i);
814 sig.append(descriptor.substring(i, next).replace('/', '_'));
817 sig.insert(firstPos, descriptor.substring(i, next).replace('/', '_'));
818 sig.insert(firstPos, ch);
820 sig.insert(firstPos, 'A');
822 hasReturnType[0] = true;
830 break; // invalid character
835 private void generateStaticField(FieldData v) throws IOException {
837 .append(className(jc))
838 .append('.').append(v.getName()).append(initField(v));
841 private String findMethodName(MethodData m, StringBuilder cnt) {
842 StringBuilder name = new StringBuilder();
843 if ("<init>".equals(m.getName())) { // NOI18N
844 name.append("cons"); // NOI18N
845 } else if ("<clinit>".equals(m.getName())) { // NOI18N
846 name.append("class"); // NOI18N
848 name.append(m.getName());
851 boolean hasReturn[] = { false };
852 countArgs(findDescriptor(m.getInternalSig()), hasReturn, name, cnt);
853 return name.toString();
856 private String findMethodName(String[] mi, StringBuilder cnt, boolean[] hasReturn) {
857 StringBuilder name = new StringBuilder();
858 String descr = mi[2];//mi.getDescriptor();
860 if ("<init>".equals(nm)) { // NOI18N
861 name.append("cons"); // NOI18N
865 countArgs(findDescriptor(descr), hasReturn, name, cnt);
866 return name.toString();
869 private int invokeStaticMethod(byte[] byteCodes, int i, boolean isStatic)
871 int methodIndex = readIntArg(byteCodes, i);
872 String[] mi = jc.getFieldInfoName(methodIndex);
873 boolean[] hasReturn = { false };
874 StringBuilder cnt = new StringBuilder();
875 String mn = findMethodName(mi, cnt, hasReturn);
877 for (int j = cnt.length() - 1; j >= 0; j--) {
878 out.append("var v" + j).append(" = stack.pop(); ");
882 out.append("stack.push(");
884 final String in = mi[0];
885 out.append(in.replace('/', '_'));
886 out.append("(true).");
891 out.append("stack.pop()");
894 for (int j = 0; j < cnt.length(); j++) {
908 private int invokeVirtualMethod(byte[] byteCodes, int i)
910 int methodIndex = readIntArg(byteCodes, i);
911 String[] mi = jc.getFieldInfoName(methodIndex);
912 boolean[] hasReturn = { false };
913 StringBuilder cnt = new StringBuilder();
914 String mn = findMethodName(mi, cnt, hasReturn);
916 for (int j = cnt.length() - 1; j >= 0; j--) {
917 out.append("var v" + j).append(" = stack.pop(); ");
919 out.append("var self = stack.pop(); ");
921 out.append("stack.push(");
927 for (int j = 0; j < cnt.length(); j++) {
940 private void addReference(String cn) throws IOException {
941 if (requireReference(cn)) {
942 out.append(" /* needs ").append(cn).append(" */");
946 private void outType(String d, StringBuilder out) {
948 while (d.charAt(0) == '[') {
952 if (d.charAt(0) == 'L') {
953 assert d.charAt(d.length() - 1) == ';';
954 out.append(d.replace('/', '_').substring(0, d.length() - 1));
960 private String encodeConstant(int entryIndex) {
961 String s = jc.stringValue(entryIndex, true);
965 private String findDescriptor(String d) {
966 return d.replace('[', 'A');
969 private boolean javaScriptBody(String prefix, MethodData m, boolean isStatic) throws IOException {
970 byte[] arr = m.findAnnotationData(true);
974 final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
975 class P extends AnnotationParser {
977 String[] args = new String[30];
981 protected void visitAttr(String type, String attr, String value) {
982 if (type.equals(jvmType)) {
983 if ("body".equals(attr)) {
985 } else if ("args".equals(attr)) {
988 throw new IllegalArgumentException(attr);
995 if (p.body == null) {
998 StringBuilder cnt = new StringBuilder();
999 out.append(prefix).append(findMethodName(m, cnt));
1000 out.append(" = function(");
1004 out.append(p.args[0]);
1011 for (int i = 0; i < cnt.length(); i++) {
1013 out.append(p.args[index]);
1017 out.append(") {").append("\n");
1019 out.append("\n}\n");
1022 private static String className(ClassData jc) {
1023 //return jc.getName().getInternalName().replace('/', '_');
1024 return jc.getClassName().replace('/', '_');
1027 private static String[] findAnnotation(
1028 byte[] arr, ClassData cd, final String className,
1029 final String... attrNames
1030 ) throws IOException {
1034 final String[] values = new String[attrNames.length];
1035 final boolean[] found = { false };
1036 final String jvmType = "L" + className.replace('.', '/') + ";";
1037 AnnotationParser ap = new AnnotationParser() {
1039 protected void visitAttr(String type, String attr, String value) {
1040 if (type.equals(jvmType)) {
1042 for (int i = 0; i < attrNames.length; i++) {
1043 if (attrNames[i].equals(attr)) {
1052 return found[0] ? values : null;
1055 private CharSequence initField(FieldData v) {
1056 final String is = v.getInternalSig();
1057 if (is.length() == 1) {
1058 switch (is.charAt(0)) {
1064 case 'I': return " = 0;";
1066 case 'D': return " = 0.0;";
1068 throw new IllegalStateException(is);