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;");
121 out.append("\n CLS.$class.cnstr = CLS;");
122 byte[] classAnno = jc.findAnnotationData(false);
123 if (classAnno != null) {
124 out.append("\n CLS.$class.anno = {");
125 generateAnno(jc, out, classAnno);
129 out.append("\n if (arguments.length === 0) {");
130 out.append("\n if (!(this instanceof CLS)) {");
131 out.append("\n return new CLS();");
133 for (FieldData v : jc.getFields()) {
135 out.append("\n this.fld_").
136 append(v.getName()).append(initField(v));
139 out.append("\n return this;");
141 out.append("\n return arguments[0] ? new CLS() : CLS.prototype;");
143 StringBuilder sb = new StringBuilder();
144 for (String init : toInitilize.toArray()) {
145 sb.append("\n").append(init).append("();");
147 return sb.toString();
149 private void generateStaticMethod(String prefix, MethodData m, StringArray toInitilize) throws IOException {
150 if (javaScriptBody(prefix, m, true)) {
153 StringBuilder argsCnt = new StringBuilder();
154 final String mn = findMethodName(m, argsCnt);
155 out.append(prefix).append(mn).append(" = function");
156 if (mn.equals("classV")) {
157 toInitilize.add(className(jc) + "(false)." + mn);
161 for (int index = 0, i = 0; i < argsCnt.length(); i++) {
163 out.append("arg").append(String.valueOf(index));
165 final String desc = null;// XXX findDescriptor(args.get(i).getDescriptor());
166 if (argsCnt.charAt(i) == '1') {
172 out.append(") {").append("\n");
173 final byte[] code = m.getCode();
175 int len = m.getMaxLocals();
176 for (int index = argsCnt.length(), i = argsCnt.length(); i < len; i++) {
178 out.append("arg").append(String.valueOf(i)).append(";\n");
180 out.append(" var s = new Array();\n");
183 out.append(" throw 'no code found for ").append(m.getInternalSig()).append("';\n");
188 private void generateInstanceMethod(String prefix, MethodData m) throws IOException {
189 if (javaScriptBody(prefix, m, false)) {
192 StringBuilder argsCnt = new StringBuilder();
193 final String mn = findMethodName(m, argsCnt);
194 out.append(prefix).append(mn).append(" = function");
197 for (int index = 1, i = 0; i < argsCnt.length(); i++) {
199 out.append("arg").append(String.valueOf(index));
200 if (argsCnt.charAt(i) == '1') {
206 out.append(") {").append("\n");
207 final byte[] code = m.getCode();
209 int len = m.getMaxLocals();
210 for (int index = argsCnt.length(), i = argsCnt.length(); i < len; i++) {
212 out.append("arg").append(String.valueOf(i + 1)).append(";\n");
214 out.append(";\n var s = new Array();\n");
217 out.append(" throw 'no code found for ").append(m.getInternalSig()).append("';\n");
222 private void produceCode(byte[] byteCodes) throws IOException {
223 out.append("\n var gt = 0;\n for(;;) switch(gt) {\n");
224 for (int i = 0; i < byteCodes.length; i++) {
226 out.append(" case " + i).append(": ");
227 final int c = readByte(byteCodes, i);
234 out.append("s.push(arg0);");
241 out.append("s.push(arg1);");
248 out.append("s.push(arg2);");
255 out.append("s.push(arg3);");
262 final int indx = readByte(byteCodes, ++i);
263 out.append("s.push(arg").append(indx + ");");
271 final int indx = readByte(byteCodes, ++i);
272 out.append("arg" + indx).append(" = s.pop();");
280 out.append("arg0 = s.pop();");
287 out.append("arg1 = s.pop();");
294 out.append("arg2 = s.pop();");
301 out.append("arg3 = s.pop();");
307 out.append("s.push(s.pop() + s.pop());");
313 out.append("{ var tmp = s.pop(); s.push(s.pop() - tmp); }");
319 out.append("s.push(s.pop() * s.pop());");
323 out.append("{ var tmp = s.pop(); s.push(Math.floor(s.pop() / tmp)); }");
327 out.append("{ var tmp = s.pop(); s.push(s.pop() / tmp); }");
333 out.append("{ var d = s.pop(); s.push(s.pop() % d); }");
337 out.append("s.push(s.pop() & s.pop());");
341 out.append("s.push(s.pop() | s.pop());");
345 out.append("s.push(s.pop() ^ s.pop());");
351 out.append("s.push(- s.pop());");
355 out.append("{ var v = s.pop(); s.push(s.pop() << v); }");
359 out.append("{ var v = s.pop(); s.push(s.pop() >> v); }");
363 out.append("{ var v = s.pop(); s.push(s.pop() >>> v); }");
366 final int varIndx = readByte(byteCodes, ++i);
367 final int incrBy = byteCodes[++i];
369 out.append("arg" + varIndx).append("++;");
371 out.append("arg" + varIndx).append(" += " + incrBy).append(";");
376 out.append("return;");
383 out.append("return s.pop();");
394 out.append("/* number conversion */");
400 out.append("s.push(Math.floor(s.pop()));");
405 out.append("/* number conversion */");
407 case opc_aconst_null:
408 out.append("s.push(null);");
411 out.append("s.push(-1);");
417 out.append("s.push(0);");
423 out.append("s.push(1);");
427 out.append("s.push(2);");
430 out.append("s.push(3);");
433 out.append("s.push(4);");
436 out.append("s.push(5);");
439 int indx = readByte(byteCodes, ++i);
440 String v = encodeConstant(indx);
441 out.append("s.push(").append(v).append(");");
446 int indx = readIntArg(byteCodes, i);
448 String v = encodeConstant(indx);
449 out.append("s.push(").append(v).append(");");
457 out.append("{ var delta = s.pop() - s.pop(); s.push(delta < 0 ?-1 : (delta == 0 ? 0 : 1)); }");
461 i = generateIf(byteCodes, i, "===");
464 i = generateIf(byteCodes, i, "!=");
466 case opc_if_icmpeq: {
467 i = generateIf(byteCodes, i, "==");
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; }");
506 int indx = i + readIntArg(byteCodes, i);
507 out.append("if (s.pop() >= 0) { gt = " + indx);
508 out.append("; continue; }");
512 case opc_ifnonnull: {
513 int indx = i + readIntArg(byteCodes, i);
514 out.append("if (s.pop() !== null) { gt = " + indx);
515 out.append("; continue; }");
520 int indx = i + readIntArg(byteCodes, i);
521 out.append("if (s.pop() === null) { gt = " + indx);
522 out.append("; continue; }");
527 i = generateIf(byteCodes, i, "!=");
530 i = generateIf(byteCodes, i, ">");
533 i = generateIf(byteCodes, i, ">=");
536 i = generateIf(byteCodes, i, "<");
539 i = generateIf(byteCodes, i, "<=");
542 int indx = i + readIntArg(byteCodes, i);
543 out.append("gt = " + indx).append("; continue;");
547 case opc_lookupswitch: {
548 int table = i / 4 * 4 + 4;
549 int dflt = i + readInt4(byteCodes, table);
551 int n = readInt4(byteCodes, table);
553 out.append("switch (s.pop()) {\n");
555 int cnstnt = readInt4(byteCodes, table);
557 int offset = i + readInt4(byteCodes, table);
559 out.append(" case " + cnstnt).append(": gt = " + offset).append("; continue;\n");
561 out.append(" default: gt = " + dflt).append("; continue;\n}");
565 case opc_tableswitch: {
566 int table = i / 4 * 4 + 4;
567 int dflt = i + readInt4(byteCodes, table);
569 int low = readInt4(byteCodes, table);
571 int high = readInt4(byteCodes, table);
573 out.append("switch (s.pop()) {\n");
574 while (low <= high) {
575 int offset = i + readInt4(byteCodes, table);
577 out.append(" case " + low).append(": gt = " + offset).append("; continue;\n");
580 out.append(" default: gt = " + dflt).append("; continue;\n}");
584 case opc_invokeinterface: {
585 i = invokeVirtualMethod(byteCodes, i) + 2;
588 case opc_invokevirtual:
589 i = invokeVirtualMethod(byteCodes, i);
591 case opc_invokespecial:
592 i = invokeStaticMethod(byteCodes, i, false);
594 case opc_invokestatic:
595 i = invokeStaticMethod(byteCodes, i, true);
598 int indx = readIntArg(byteCodes, i);
599 String ci = jc.getClassName(indx);
600 out.append("s.push(new ");
601 out.append(ci.replace('/','_'));
608 int type = byteCodes[i++];
609 out.append("s.push(new Array(s.pop()).fillNulls());");
612 case opc_anewarray: {
613 i += 2; // skip type of array
614 out.append("s.push(new Array(s.pop()).fillNulls());");
617 case opc_multianewarray: {
619 int dim = readByte(byteCodes, ++i);
620 out.append("{ var a0 = new Array(s.pop()).fillNulls();");
621 for (int d = 1; d < dim; d++) {
622 out.append("\n var l" + d).append(" = s.pop();");
623 out.append("\n for (var i" + d).append (" = 0; i" + d).
624 append(" < a" + (d - 1)).
625 append(".length; i" + d).append("++) {");
626 out.append("\n var a" + d).
627 append (" = new Array(l" + d).append(").fillNulls();");
628 out.append("\n a" + (d - 1)).append("[i" + d).append("] = a" + d).
631 for (int d = 1; d < dim; d++) {
634 out.append("\ns.push(a0); }");
637 case opc_arraylength:
638 out.append("s.push(s.pop().length);");
648 out.append("{ var value = s.pop(); var indx = s.pop(); s.pop()[indx] = value; }");
659 out.append("{ var indx = s.pop(); s.push(s.pop()[indx]); }");
663 out.append("s.pop();");
665 out.append("s.pop();");
668 out.append("s.push(s[s.length - 1]);");
671 out.append("{ var v1 = s.pop(); var v2 = s.pop(); s.push(v1); s.push(v2); s.push(v1); }");
674 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); }");
677 out.append("s.push(" + byteCodes[++i] + ");");
680 out.append("s.push(" + readIntArg(byteCodes, i) + ");");
684 int indx = readIntArg(byteCodes, i);
685 String[] fi = jc.getFieldInfoName(indx);
686 out.append("s.push(s.pop().fld_").
687 append(fi[1]).append(");");
691 case opc_getstatic: {
692 int indx = readIntArg(byteCodes, i);
693 String[] fi = jc.getFieldInfoName(indx);
694 out.append("s.push(").append(fi[0].replace('/', '_'));
695 out.append('.').append(fi[1]).append(");");
700 case opc_putstatic: {
701 int indx = readIntArg(byteCodes, i);
702 String[] fi = jc.getFieldInfoName(indx);
703 out.append(fi[0].replace('/', '_'));
704 out.append('.').append(fi[1]).append(" = s.pop();");
710 int indx = readIntArg(byteCodes, i);
711 String[] fi = jc.getFieldInfoName(indx);
712 out.append("{ var v = s.pop(); s.pop().fld_")
713 .append(fi[1]).append(" = v; }");
717 case opc_checkcast: {
718 int indx = readIntArg(byteCodes, i);
719 final String type = jc.getClassName(indx);
720 if (!type.startsWith("[")) {
721 // no way to check arrays right now
722 out.append("if(s[s.length - 1].$instOf_")
723 .append(type.replace('/', '_'))
724 .append(" != 1) throw {};"); // XXX proper exception
729 case opc_instanceof: {
730 int indx = readIntArg(byteCodes, i);
731 final String type = jc.getClassName(indx);
732 out.append("s.push(s.pop().$instOf_")
733 .append(type.replace('/', '_'))
734 .append(" ? 1 : 0);");
739 out.append("{ var t = s.pop(); s = new Array(1); s[0] = t; throw t; }");
743 out.append("throw 'unknown bytecode " + c + "';");
748 for (int j = prev; j <= i; j++) {
750 final int cc = readByte(byteCodes, j);
751 out.append(Integer.toString(cc));
758 private int generateIf(byte[] byteCodes, int i, final String test) throws IOException {
759 int indx = i + readIntArg(byteCodes, i);
760 out.append("if (s.pop() ").append(test).append(" s.pop()) { gt = " + indx);
761 out.append("; continue; }");
765 private int readIntArg(byte[] byteCodes, int offsetInstruction) {
766 final int indxHi = byteCodes[offsetInstruction + 1] << 8;
767 final int indxLo = byteCodes[offsetInstruction + 2];
768 return (indxHi & 0xffffff00) | (indxLo & 0xff);
770 private int readInt4(byte[] byteCodes, int offsetInstruction) {
771 final int d = byteCodes[offsetInstruction + 0] << 24;
772 final int c = byteCodes[offsetInstruction + 1] << 16;
773 final int b = byteCodes[offsetInstruction + 2] << 8;
774 final int a = byteCodes[offsetInstruction + 3];
775 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
777 private int readByte(byte[] byteCodes, int offsetInstruction) {
778 return (byteCodes[offsetInstruction] + 256) % 256;
781 private static void countArgs(String descriptor, boolean[] hasReturnType, StringBuilder sig, StringBuilder cnt) {
783 Boolean count = null;
784 boolean array = false;
785 int firstPos = sig.length();
786 while (i < descriptor.length()) {
787 char ch = descriptor.charAt(i++);
811 if (ch == 'J' || ch == 'D') {
817 hasReturnType[0] = true;
818 sig.insert(firstPos, ch);
820 sig.insert(firstPos, 'A');
827 hasReturnType[0] = false;
828 sig.insert(firstPos, 'V');
831 int next = descriptor.indexOf(';', i);
837 sig.append(descriptor.substring(i, next).replace('/', '_'));
840 sig.insert(firstPos, descriptor.substring(i, next).replace('/', '_'));
841 sig.insert(firstPos, ch);
843 sig.insert(firstPos, 'A');
845 hasReturnType[0] = true;
853 break; // invalid character
858 private String findMethodName(MethodData m, StringBuilder cnt) {
859 StringBuilder name = new StringBuilder();
860 if ("<init>".equals(m.getName())) { // NOI18N
861 name.append("cons"); // NOI18N
862 } else if ("<clinit>".equals(m.getName())) { // NOI18N
863 name.append("class"); // NOI18N
865 name.append(m.getName());
868 boolean hasReturn[] = { false };
869 countArgs(findDescriptor(m.getInternalSig()), hasReturn, name, cnt);
870 return name.toString();
873 private String findMethodName(String[] mi, StringBuilder cnt, boolean[] hasReturn) {
874 StringBuilder name = new StringBuilder();
875 String descr = mi[2];//mi.getDescriptor();
877 if ("<init>".equals(nm)) { // NOI18N
878 name.append("cons"); // NOI18N
882 countArgs(findDescriptor(descr), hasReturn, name, cnt);
883 return name.toString();
886 private int invokeStaticMethod(byte[] byteCodes, int i, boolean isStatic)
888 int methodIndex = readIntArg(byteCodes, i);
889 String[] mi = jc.getFieldInfoName(methodIndex);
890 boolean[] hasReturn = { false };
891 StringBuilder cnt = new StringBuilder();
892 String mn = findMethodName(mi, cnt, hasReturn);
894 for (int j = cnt.length() - 1; j >= 0; j--) {
895 out.append("var v" + j).append(" = s.pop(); ");
899 out.append("s.push(");
901 final String in = mi[0];
902 out.append(in.replace('/', '_'));
903 out.append("(false).");
908 out.append("s.pop()");
911 for (int j = 0; j < cnt.length(); j++) {
925 private int invokeVirtualMethod(byte[] byteCodes, int i)
927 int methodIndex = readIntArg(byteCodes, i);
928 String[] mi = jc.getFieldInfoName(methodIndex);
929 boolean[] hasReturn = { false };
930 StringBuilder cnt = new StringBuilder();
931 String mn = findMethodName(mi, cnt, hasReturn);
933 for (int j = cnt.length() - 1; j >= 0; j--) {
934 out.append("var v" + j).append(" = s.pop(); ");
936 out.append("var self = s.pop(); ");
938 out.append("s.push(");
944 for (int j = 0; j < cnt.length(); j++) {
957 private void addReference(String cn) throws IOException {
958 if (requireReference(cn)) {
959 out.append(" /* needs ").append(cn).append(" */");
963 private void outType(String d, StringBuilder out) {
965 while (d.charAt(0) == '[') {
969 if (d.charAt(0) == 'L') {
970 assert d.charAt(d.length() - 1) == ';';
971 out.append(d.replace('/', '_').substring(0, d.length() - 1));
977 private String encodeConstant(int entryIndex) throws IOException {
978 String[] classRef = { null };
979 String s = jc.stringValue(entryIndex, classRef);
980 if (classRef[0] != null) {
981 addReference(classRef[0]);
986 private String findDescriptor(String d) {
987 return d.replace('[', 'A');
990 private boolean javaScriptBody(String prefix, MethodData m, boolean isStatic) throws IOException {
991 byte[] arr = m.findAnnotationData(true);
995 final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
996 class P extends AnnotationParser {
998 String[] args = new String[30];
1002 protected void visitAttr(String type, String attr, String value) {
1003 if (type.equals(jvmType)) {
1004 if ("body".equals(attr)) {
1006 } else if ("args".equals(attr)) {
1007 args[cnt++] = value;
1009 throw new IllegalArgumentException(attr);
1016 if (p.body == null) {
1019 StringBuilder cnt = new StringBuilder();
1020 out.append(prefix).append(findMethodName(m, cnt));
1021 out.append(" = function(");
1025 out.append(p.args[0]);
1032 for (int i = 0; i < cnt.length(); i++) {
1034 out.append(p.args[index]);
1038 out.append(") {").append("\n");
1040 out.append("\n}\n");
1043 private static String className(ClassData jc) {
1044 //return jc.getName().getInternalName().replace('/', '_');
1045 return jc.getClassName().replace('/', '_');
1048 private static String[] findAnnotation(
1049 byte[] arr, ClassData cd, final String className,
1050 final String... attrNames
1051 ) throws IOException {
1055 final String[] values = new String[attrNames.length];
1056 final boolean[] found = { false };
1057 final String jvmType = "L" + className.replace('.', '/') + ";";
1058 AnnotationParser ap = new AnnotationParser() {
1060 protected void visitAttr(String type, String attr, String value) {
1061 if (type.equals(jvmType)) {
1063 for (int i = 0; i < attrNames.length; i++) {
1064 if (attrNames[i].equals(attr)) {
1073 return found[0] ? values : null;
1076 private CharSequence initField(FieldData v) {
1077 final String is = v.getInternalSig();
1078 if (is.length() == 1) {
1079 switch (is.charAt(0)) {
1085 case 'I': return " = 0;";
1087 case 'D': return " = 0.0;";
1089 throw new IllegalStateException(is);
1095 private static void generateAnno(ClassData cd, final Appendable out, byte[] data) throws IOException {
1096 AnnotationParser ap = new AnnotationParser() {
1100 protected void visitAnnotationStart(String type) throws IOException {
1101 out.append('"').append(type).append("\" : {\n");
1106 protected void visitAnnotationEnd(String type) throws IOException {
1107 out.append("\n}\n");
1111 protected void visitAttr(String type, String attr, String value)
1112 throws IOException {
1116 out.append(attr).append(" : ").append(value);