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);
53 /** Allows subclasses to redefine what field a function representing a
54 * class gets assigned. By default it returns the suggested name followed
55 * by <code>" = "</code>;
57 * @param className suggested name of the class
59 protected String assignClass(String className) {
60 return className + " = ";
64 * Converts a given class file to a JavaScript version.
66 * @param classFile input stream with code of the .class file
67 * @return the initialization code for this class, if any. Otherwise <code>null</code>
69 * @throws IOException if something goes wrong during read or write or translating
72 public String compile(InputStream classFile) throws IOException {
73 this.jc = new ClassData(classFile);
74 byte[] arrData = jc.findAnnotationData(true);
75 String[] arr = findAnnotation(arrData, jc,
76 "org.apidesign.bck2brwsr.core.ExtraJavaScript",
77 "resource", "processByteCode"
80 requireScript(arr[0]);
81 if ("0".equals(arr[1])) {
85 StringArray toInitilize = new StringArray();
86 final String className = className(jc);
87 out.append("\n\n").append(assignClass(className));
88 out.append("function CLS() {");
89 out.append("\n if (!CLS.prototype.$instOf_").append(className).append(") {");
90 for (FieldData v : jc.getFields()) {
92 out.append("\n CLS.").append(v.getName()).append(initField(v));
95 // ClassName sc = jc.getSuperClass();
96 String sc = jc.getSuperClassName(); // with _
98 out.append("\n var pp = ").
99 append(sc.replace('/', '_')).append("(true);");
100 out.append("\n var p = CLS.prototype = pp;");
101 out.append("\n var sprcls = pp.constructor.$class;");
103 out.append("\n var p = CLS.prototype;");
104 out.append("\n var sprcls = null;");
106 for (MethodData m : jc.getMethods()) {
108 generateStaticMethod("\n p.", m, toInitilize);
110 generateInstanceMethod("\n p.", m);
113 out.append("\n p.constructor = CLS;");
114 out.append("\n p.$instOf_").append(className).append(" = true;");
115 for (String superInterface : jc.getSuperInterfaces()) {
116 out.append("\n p.$instOf_").append(superInterface.replace('/', '_')).append(" = true;");
118 out.append("\n CLS.$class = java_lang_Class(true);");
119 out.append("\n CLS.$class.jvmName = '").append(jc.getClassName()).append("';");
120 out.append("\n CLS.$class.superclass = sprcls;");
122 out.append("\n if (arguments.length === 0) {");
123 out.append("\n if (!(this instanceof CLS)) {");
124 out.append("\n return new CLS();");
126 for (FieldData v : jc.getFields()) {
128 out.append("\n this.fld_").
129 append(v.getName()).append(initField(v));
132 out.append("\n return this;");
134 out.append("\n return arguments[0] ? new CLS() : CLS.prototype;");
136 StringBuilder sb = new StringBuilder();
137 for (String init : toInitilize.toArray()) {
138 sb.append("\n").append(init).append("();");
140 return sb.toString();
142 private void generateStaticMethod(String prefix, MethodData m, StringArray toInitilize) throws IOException {
143 if (javaScriptBody(prefix, m, true)) {
146 StringBuilder argsCnt = new StringBuilder();
147 final String mn = findMethodName(m, argsCnt);
148 out.append(prefix).append(mn).append(" = function");
149 if (mn.equals("classV")) {
150 toInitilize.add(className(jc) + "(false)." + mn);
154 for (int index = 0, i = 0; i < argsCnt.length(); i++) {
156 out.append("arg").append(String.valueOf(index));
158 final String desc = null;// XXX findDescriptor(args.get(i).getDescriptor());
159 if (argsCnt.charAt(i) == '1') {
165 out.append(") {").append("\n");
166 final byte[] code = m.getCode();
168 int len = m.getMaxLocals();
169 for (int index = argsCnt.length(), i = argsCnt.length(); i < len; i++) {
171 out.append("arg").append(String.valueOf(i)).append(";\n");
173 out.append(" var s = new Array();\n");
176 out.append(" /* no code found for ").append(m.getInternalSig()).append(" */\n");
181 private void generateInstanceMethod(String prefix, MethodData m) throws IOException {
182 if (javaScriptBody(prefix, m, false)) {
185 StringBuilder argsCnt = new StringBuilder();
186 final String mn = findMethodName(m, argsCnt);
187 out.append(prefix).append(mn).append(" = function");
190 for (int index = 1, i = 0; i < argsCnt.length(); i++) {
192 out.append("arg").append(String.valueOf(index));
193 if (argsCnt.charAt(i) == '1') {
199 out.append(") {").append("\n");
200 final byte[] code = m.getCode();
202 int len = m.getMaxLocals();
203 for (int index = argsCnt.length(), i = argsCnt.length(); i < len; i++) {
205 out.append("arg").append(String.valueOf(i + 1)).append(";\n");
207 out.append(";\n var s = new Array();\n");
210 out.append(" /* no code found for ").append(m.getInternalSig()).append(" */\n");
215 private void produceCode(byte[] byteCodes) throws IOException {
216 out.append("\n var gt = 0;\n for(;;) switch(gt) {\n");
217 for (int i = 0; i < byteCodes.length; i++) {
219 out.append(" case " + i).append(": ");
220 final int c = readByte(byteCodes, i);
227 out.append("s.push(arg0);");
234 out.append("s.push(arg1);");
241 out.append("s.push(arg2);");
248 out.append("s.push(arg3);");
255 final int indx = readByte(byteCodes, ++i);
256 out.append("s.push(arg").append(indx + ");");
264 final int indx = readByte(byteCodes, ++i);
265 out.append("arg" + indx).append(" = s.pop();");
273 out.append("arg0 = s.pop();");
280 out.append("arg1 = s.pop();");
287 out.append("arg2 = s.pop();");
294 out.append("arg3 = s.pop();");
300 out.append("s.push(s.pop() + s.pop());");
306 out.append("{ var tmp = s.pop(); s.push(s.pop() - tmp); }");
312 out.append("s.push(s.pop() * s.pop());");
316 out.append("{ var tmp = s.pop(); s.push(Math.floor(s.pop() / tmp)); }");
320 out.append("{ var tmp = s.pop(); s.push(s.pop() / tmp); }");
326 out.append("{ var d = s.pop(); s.push(s.pop() % d); }");
330 out.append("s.push(s.pop() & s.pop());");
334 out.append("s.push(s.pop() | s.pop());");
338 out.append("s.push(s.pop() ^ s.pop());");
344 out.append("s.push(- s.pop());");
348 out.append("{ var v = s.pop(); s.push(s.pop() << v); }");
352 out.append("{ var v = s.pop(); s.push(s.pop() >> v); }");
356 out.append("{ var v = s.pop(); s.push(s.pop() >>> v); }");
359 final int varIndx = readByte(byteCodes, ++i);
360 final int incrBy = byteCodes[++i];
362 out.append("arg" + varIndx).append("++;");
364 out.append("arg" + varIndx).append(" += " + incrBy).append(";");
369 out.append("return;");
376 out.append("return s.pop();");
387 out.append("/* number conversion */");
393 out.append("s.push(Math.floor(s.pop()));");
398 out.append("/* number conversion */");
400 case opc_aconst_null:
401 out.append("s.push(null);");
404 out.append("s.push(-1);");
410 out.append("s.push(0);");
416 out.append("s.push(1);");
420 out.append("s.push(2);");
423 out.append("s.push(3);");
426 out.append("s.push(4);");
429 out.append("s.push(5);");
432 int indx = readByte(byteCodes, ++i);
433 String v = encodeConstant(indx);
434 out.append("s.push(").append(v).append(");");
439 int indx = readIntArg(byteCodes, i);
441 String v = encodeConstant(indx);
442 out.append("s.push(").append(v).append(");");
450 out.append("{ var delta = s.pop() - s.pop(); s.push(delta < 0 ?-1 : (delta == 0 ? 0 : 1)); }");
454 i = generateIf(byteCodes, i, "===");
457 i = generateIf(byteCodes, i, "!=");
459 case opc_if_icmpeq: {
460 i = generateIf(byteCodes, i, "==");
464 int indx = i + readIntArg(byteCodes, i);
465 out.append("if (s.pop() == 0) { gt = " + indx);
466 out.append("; continue; }");
471 int indx = i + readIntArg(byteCodes, i);
472 out.append("if (s.pop() != 0) { gt = " + indx);
473 out.append("; continue; }");
478 int indx = i + readIntArg(byteCodes, i);
479 out.append("if (s.pop() < 0) { gt = " + indx);
480 out.append("; continue; }");
485 int indx = i + readIntArg(byteCodes, i);
486 out.append("if (s.pop() <= 0) { gt = " + indx);
487 out.append("; continue; }");
492 int indx = i + readIntArg(byteCodes, i);
493 out.append("if (s.pop() > 0) { gt = " + indx);
494 out.append("; continue; }");
499 int indx = i + readIntArg(byteCodes, i);
500 out.append("if (s.pop() >= 0) { gt = " + indx);
501 out.append("; continue; }");
505 case opc_ifnonnull: {
506 int indx = i + readIntArg(byteCodes, i);
507 out.append("if (s.pop() !== null) { gt = " + indx);
508 out.append("; continue; }");
513 int indx = i + readIntArg(byteCodes, i);
514 out.append("if (s.pop() === null) { gt = " + indx);
515 out.append("; continue; }");
520 i = generateIf(byteCodes, i, "!=");
523 i = generateIf(byteCodes, i, ">");
526 i = generateIf(byteCodes, i, ">=");
529 i = generateIf(byteCodes, i, "<");
532 i = generateIf(byteCodes, i, "<=");
535 int indx = i + readIntArg(byteCodes, i);
536 out.append("gt = " + indx).append("; continue;");
540 case opc_lookupswitch: {
541 int table = i / 4 * 4 + 4;
542 int dflt = i + readInt4(byteCodes, table);
544 int n = readInt4(byteCodes, table);
546 out.append("switch (s.pop()) {\n");
548 int cnstnt = readInt4(byteCodes, table);
550 int offset = i + readInt4(byteCodes, table);
552 out.append(" case " + cnstnt).append(": gt = " + offset).append("; continue;\n");
554 out.append(" default: gt = " + dflt).append("; continue;\n}");
558 case opc_tableswitch: {
559 int table = i / 4 * 4 + 4;
560 int dflt = i + readInt4(byteCodes, table);
562 int low = readInt4(byteCodes, table);
564 int high = readInt4(byteCodes, table);
566 out.append("switch (s.pop()) {\n");
567 while (low <= high) {
568 int offset = i + readInt4(byteCodes, table);
570 out.append(" case " + low).append(": gt = " + offset).append("; continue;\n");
573 out.append(" default: gt = " + dflt).append("; continue;\n}");
577 case opc_invokeinterface: {
578 i = invokeVirtualMethod(byteCodes, i) + 2;
581 case opc_invokevirtual:
582 i = invokeVirtualMethod(byteCodes, i);
584 case opc_invokespecial:
585 i = invokeStaticMethod(byteCodes, i, false);
587 case opc_invokestatic:
588 i = invokeStaticMethod(byteCodes, i, true);
591 int indx = readIntArg(byteCodes, i);
592 String ci = jc.getClassName(indx);
593 out.append("s.push(new ");
594 out.append(ci.replace('/','_'));
601 int type = byteCodes[i++];
602 out.append("s.push(new Array(s.pop()).fillNulls());");
605 case opc_anewarray: {
606 i += 2; // skip type of array
607 out.append("s.push(new Array(s.pop()).fillNulls());");
610 case opc_multianewarray: {
612 int dim = readByte(byteCodes, ++i);
613 out.append("{ var a0 = new Array(s.pop()).fillNulls();");
614 for (int d = 1; d < dim; d++) {
615 out.append("\n var l" + d).append(" = s.pop();");
616 out.append("\n for (var i" + d).append (" = 0; i" + d).
617 append(" < a" + (d - 1)).
618 append(".length; i" + d).append("++) {");
619 out.append("\n var a" + d).
620 append (" = new Array(l" + d).append(").fillNulls();");
621 out.append("\n a" + (d - 1)).append("[i" + d).append("] = a" + d).
624 for (int d = 1; d < dim; d++) {
627 out.append("\ns.push(a0); }");
630 case opc_arraylength:
631 out.append("s.push(s.pop().length);");
641 out.append("{ var value = s.pop(); var indx = s.pop(); s.pop()[indx] = value; }");
652 out.append("{ var indx = s.pop(); s.push(s.pop()[indx]); }");
656 out.append("s.pop();");
658 out.append("s.pop();");
661 out.append("s.push(s[s.length - 1]);");
664 out.append("{ var v1 = s.pop(); var v2 = s.pop(); s.push(v1); s.push(v2); s.push(v1); }");
667 out.append("{ var v1 = s.pop(); var v2 = s.pop(); var v3 = s.pop(); s.push(v1); s.push(v3); s.push(v2); s.push(v1); }");
670 out.append("s.push(" + byteCodes[++i] + ");");
673 out.append("s.push(" + readIntArg(byteCodes, i) + ");");
677 int indx = readIntArg(byteCodes, i);
678 String[] fi = jc.getFieldInfoName(indx);
679 out.append("s.push(s.pop().fld_").
680 append(fi[1]).append(");");
684 case opc_getstatic: {
685 int indx = readIntArg(byteCodes, i);
686 String[] fi = jc.getFieldInfoName(indx);
687 out.append("s.push(").append(fi[0].replace('/', '_'));
688 out.append('.').append(fi[1]).append(");");
693 case opc_putstatic: {
694 int indx = readIntArg(byteCodes, i);
695 String[] fi = jc.getFieldInfoName(indx);
696 out.append(fi[0].replace('/', '_'));
697 out.append('.').append(fi[1]).append(" = s.pop();");
703 int indx = readIntArg(byteCodes, i);
704 String[] fi = jc.getFieldInfoName(indx);
705 out.append("{ var v = s.pop(); s.pop().fld_")
706 .append(fi[1]).append(" = v; }");
710 case opc_checkcast: {
711 int indx = readIntArg(byteCodes, i);
712 final String type = jc.getClassName(indx);
713 if (!type.startsWith("[")) {
714 // no way to check arrays right now
715 out.append("if(s[s.length - 1].$instOf_")
716 .append(type.replace('/', '_'))
717 .append(" != 1) throw {};"); // XXX proper exception
722 case opc_instanceof: {
723 int indx = readIntArg(byteCodes, i);
724 final String type = jc.getClassName(indx);
725 out.append("s.push(s.pop().$instOf_")
726 .append(type.replace('/', '_'))
727 .append(" ? 1 : 0);");
732 out.append("{ var t = s.pop(); s = new Array(1); s[0] = t; throw t; }");
736 out.append("throw 'unknown bytecode " + c + "';");
741 for (int j = prev; j <= i; j++) {
743 final int cc = readByte(byteCodes, j);
744 out.append(Integer.toString(cc));
751 private int generateIf(byte[] byteCodes, int i, final String test) throws IOException {
752 int indx = i + readIntArg(byteCodes, i);
753 out.append("if (s.pop() ").append(test).append(" s.pop()) { gt = " + indx);
754 out.append("; continue; }");
758 private int readIntArg(byte[] byteCodes, int offsetInstruction) {
759 final int indxHi = byteCodes[offsetInstruction + 1] << 8;
760 final int indxLo = byteCodes[offsetInstruction + 2];
761 return (indxHi & 0xffffff00) | (indxLo & 0xff);
763 private int readInt4(byte[] byteCodes, int offsetInstruction) {
764 final int d = byteCodes[offsetInstruction + 0] << 24;
765 final int c = byteCodes[offsetInstruction + 1] << 16;
766 final int b = byteCodes[offsetInstruction + 2] << 8;
767 final int a = byteCodes[offsetInstruction + 3];
768 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
770 private int readByte(byte[] byteCodes, int offsetInstruction) {
771 return (byteCodes[offsetInstruction] + 256) % 256;
774 private static void countArgs(String descriptor, boolean[] hasReturnType, StringBuilder sig, StringBuilder cnt) {
776 Boolean count = null;
777 boolean array = false;
778 int firstPos = sig.length();
779 while (i < descriptor.length()) {
780 char ch = descriptor.charAt(i++);
804 if (ch == 'J' || ch == 'D') {
810 hasReturnType[0] = true;
811 sig.insert(firstPos, ch);
813 sig.insert(firstPos, 'A');
820 hasReturnType[0] = false;
821 sig.insert(firstPos, 'V');
824 int next = descriptor.indexOf(';', i);
830 sig.append(descriptor.substring(i, next).replace('/', '_'));
833 sig.insert(firstPos, descriptor.substring(i, next).replace('/', '_'));
834 sig.insert(firstPos, ch);
836 sig.insert(firstPos, 'A');
838 hasReturnType[0] = true;
846 break; // invalid character
851 private String findMethodName(MethodData m, StringBuilder cnt) {
852 StringBuilder name = new StringBuilder();
853 if ("<init>".equals(m.getName())) { // NOI18N
854 name.append("cons"); // NOI18N
855 } else if ("<clinit>".equals(m.getName())) { // NOI18N
856 name.append("class"); // NOI18N
858 name.append(m.getName());
861 boolean hasReturn[] = { false };
862 countArgs(findDescriptor(m.getInternalSig()), hasReturn, name, cnt);
863 return name.toString();
866 private String findMethodName(String[] mi, StringBuilder cnt, boolean[] hasReturn) {
867 StringBuilder name = new StringBuilder();
868 String descr = mi[2];//mi.getDescriptor();
870 if ("<init>".equals(nm)) { // NOI18N
871 name.append("cons"); // NOI18N
875 countArgs(findDescriptor(descr), hasReturn, name, cnt);
876 return name.toString();
879 private int invokeStaticMethod(byte[] byteCodes, int i, boolean isStatic)
881 int methodIndex = readIntArg(byteCodes, i);
882 String[] mi = jc.getFieldInfoName(methodIndex);
883 boolean[] hasReturn = { false };
884 StringBuilder cnt = new StringBuilder();
885 String mn = findMethodName(mi, cnt, hasReturn);
887 for (int j = cnt.length() - 1; j >= 0; j--) {
888 out.append("var v" + j).append(" = s.pop(); ");
892 out.append("s.push(");
894 final String in = mi[0];
895 out.append(in.replace('/', '_'));
896 out.append("(false).");
901 out.append("s.pop()");
904 for (int j = 0; j < cnt.length(); j++) {
918 private int invokeVirtualMethod(byte[] byteCodes, int i)
920 int methodIndex = readIntArg(byteCodes, i);
921 String[] mi = jc.getFieldInfoName(methodIndex);
922 boolean[] hasReturn = { false };
923 StringBuilder cnt = new StringBuilder();
924 String mn = findMethodName(mi, cnt, hasReturn);
926 for (int j = cnt.length() - 1; j >= 0; j--) {
927 out.append("var v" + j).append(" = s.pop(); ");
929 out.append("var self = s.pop(); ");
931 out.append("s.push(");
937 for (int j = 0; j < cnt.length(); j++) {
950 private void addReference(String cn) throws IOException {
951 if (requireReference(cn)) {
952 out.append(" /* needs ").append(cn).append(" */");
956 private void outType(String d, StringBuilder out) {
958 while (d.charAt(0) == '[') {
962 if (d.charAt(0) == 'L') {
963 assert d.charAt(d.length() - 1) == ';';
964 out.append(d.replace('/', '_').substring(0, d.length() - 1));
970 private String encodeConstant(int entryIndex) throws IOException {
971 String[] classRef = { null };
972 String s = jc.stringValue(entryIndex, classRef);
973 if (classRef[0] != null) {
974 addReference(classRef[0]);
979 private String findDescriptor(String d) {
980 return d.replace('[', 'A');
983 private boolean javaScriptBody(String prefix, MethodData m, boolean isStatic) throws IOException {
984 byte[] arr = m.findAnnotationData(true);
988 final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
989 class P extends AnnotationParser {
991 String[] args = new String[30];
995 protected void visitAttr(String type, String attr, String value) {
996 if (type.equals(jvmType)) {
997 if ("body".equals(attr)) {
999 } else if ("args".equals(attr)) {
1000 args[cnt++] = value;
1002 throw new IllegalArgumentException(attr);
1009 if (p.body == null) {
1012 StringBuilder cnt = new StringBuilder();
1013 out.append(prefix).append(findMethodName(m, cnt));
1014 out.append(" = function(");
1018 out.append(p.args[0]);
1025 for (int i = 0; i < cnt.length(); i++) {
1027 out.append(p.args[index]);
1031 out.append(") {").append("\n");
1033 out.append("\n}\n");
1036 private static String className(ClassData jc) {
1037 //return jc.getName().getInternalName().replace('/', '_');
1038 return jc.getClassName().replace('/', '_');
1041 private static String[] findAnnotation(
1042 byte[] arr, ClassData cd, final String className,
1043 final String... attrNames
1044 ) throws IOException {
1048 final String[] values = new String[attrNames.length];
1049 final boolean[] found = { false };
1050 final String jvmType = "L" + className.replace('.', '/') + ";";
1051 AnnotationParser ap = new AnnotationParser() {
1053 protected void visitAttr(String type, String attr, String value) {
1054 if (type.equals(jvmType)) {
1056 for (int i = 0; i < attrNames.length; i++) {
1057 if (attrNames[i].equals(attr)) {
1066 return found[0] ? values : null;
1069 private CharSequence initField(FieldData v) {
1070 final String is = v.getInternalSig();
1071 if (is.length() == 1) {
1072 switch (is.charAt(0)) {
1078 case 'I': return " = 0;";
1080 case 'D': return " = 0.0;";
1082 throw new IllegalStateException(is);