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 static org.apidesign.javap.RuntimeConstants.*;
29 /** Translator of the code inside class files to JavaScript.
31 * @author Jaroslav Tulach <jtulach@netbeans.org>
33 public abstract class ByteCodeToJavaScript {
35 private final Appendable out;
37 protected ByteCodeToJavaScript(Appendable out) {
41 /* Collects additional required resources.
43 * @param internalClassName classes that were referenced and should be loaded in order the
44 * generated JavaScript code works properly. The names are in internal
45 * JVM form so String is <code>java/lang/String</code>.
47 protected abstract boolean requireReference(String internalClassName);
50 * @param resourcePath name of resources to read
52 protected abstract void requireScript(String resourcePath);
55 * Converts a given class file to a JavaScript version.
57 * @param classFile input stream with code of the .class file
58 * @return the initialization code for this class, if any. Otherwise <code>null</code>
60 * @throws IOException if something goes wrong during read or write or translating
63 public String compile(InputStream classFile) throws IOException {
64 this.jc = new ClassData(classFile);
65 byte[] arrData = jc.findAnnotationData(true);
66 String[] arr = findAnnotation(arrData, jc,
67 "org.apidesign.bck2brwsr.core.ExtraJavaScript",
68 "resource", "processByteCode"
71 requireScript(arr[0]);
72 if ("0".equals(arr[1])) {
76 StringArray toInitilize = new StringArray();
77 for (MethodData m : jc.getMethods()) {
79 generateStaticMethod(m, toInitilize);
81 generateInstanceMethod(m);
84 for (FieldData v : jc.getFields()) {
86 generateStaticField(v);
90 final String className = className(jc);
91 out.append("\nfunction ").append(className);
93 for (FieldData v : jc.getFields()) {
95 out.append("\n this.fld_").
96 append(v.getName()).append(initField(v));
99 out.append("\n}\n\nfunction ").append(className).append("_proto() {");
100 out.append("\n if (").append(className).
101 append(".prototype.$instOf_").append(className).append(") {");
102 out.append("\n return new ").append(className).append(";");
104 // ClassName sc = jc.getSuperClass();
105 String sc = jc.getSuperClassName(); // with _
107 out.append("\n var p = ").append(className)
108 .append(".prototype = ").
109 append(sc.replace('/', '_')).append("_proto();");
111 out.append("\n var p = ").append(className).append(".prototype;");
113 for (MethodData m : jc.getMethods()) {
114 if (!m.getName().contains("<init>") && !m.getName().contains("<cinit>")) {
115 generateMethodReference("\n p.", m);
118 out.append("\n p.$instOf_").append(className).append(" = true;");
119 for (String superInterface : jc.getSuperInterfaces()) {
120 out.append("\n p.$instOf_").append(superInterface.replace('/', '_')).append(" = true;");
122 out.append("\n return new ").append(className).append(";");
124 out.append("\n").append(className).append("_proto();");
125 StringBuilder sb = new StringBuilder();
126 for (String init : toInitilize.toArray()) {
127 sb.append("\n").append(init).append("();");
129 return sb.toString();
131 private void generateStaticMethod(MethodData m, StringArray toInitilize) throws IOException {
132 if (javaScriptBody(m, true)) {
135 StringBuilder argsCnt = new StringBuilder();
136 final String mn = findMethodName(m, argsCnt);
137 out.append("\nfunction ").append(
139 ).append('_').append(mn);
140 if (mn.equals("classV")) {
141 toInitilize.add(className(jc) + '_' + mn);
145 for (int index = 0, i = 0; i < argsCnt.length(); i++) {
147 out.append("arg").append(String.valueOf(index));
149 final String desc = null;// XXX findDescriptor(args.get(i).getDescriptor());
150 if (argsCnt.charAt(i) == '1') {
156 out.append(") {").append("\n");
157 final byte[] code = m.getCode();
159 int len = m.getMaxLocals();
160 for (int index = argsCnt.length(), i = argsCnt.length(); i < len; i++) {
162 out.append("arg").append(String.valueOf(i)).append(";\n");
164 out.append(" var stack = new Array();\n");
167 out.append(" /* no code found for ").append(m.getInternalSig()).append(" */\n");
172 private void generateMethodReference(String prefix, MethodData m) throws IOException {
173 final String name = findMethodName(m, new StringBuilder());
174 out.append(prefix).append(name).append(" = ")
175 .append(className(jc))
176 .append('_').append(name).append(";");
179 private void generateInstanceMethod(MethodData m) throws IOException {
180 if (javaScriptBody(m, false)) {
183 StringBuilder argsCnt = new StringBuilder();
184 out.append("\nfunction ").append(
186 ).append('_').append(findMethodName(m, argsCnt));
189 for (int index = 1, i = 0; i < argsCnt.length(); i++) {
191 out.append("arg").append(String.valueOf(index));
192 if (argsCnt.charAt(i) == '1') {
198 out.append(") {").append("\n");
199 final byte[] code = m.getCode();
201 int len = m.getMaxLocals();
202 for (int index = argsCnt.length(), i = argsCnt.length(); i < len; i++) {
204 out.append("arg").append(String.valueOf(i + 1)).append(";\n");
206 out.append(";\n var stack = new Array();\n");
209 out.append(" /* no code found for ").append(m.getInternalSig()).append(" */\n");
214 private void produceCode(byte[] byteCodes) throws IOException {
215 out.append("\n var gt = 0;\n for(;;) switch(gt) {\n");
216 for (int i = 0; i < byteCodes.length; i++) {
218 out.append(" case " + i).append(": ");
219 final int c = readByte(byteCodes, i);
226 out.append("stack.push(arg0);");
233 out.append("stack.push(arg1);");
240 out.append("stack.push(arg2);");
247 out.append("stack.push(arg3);");
254 final int indx = readByte(byteCodes, ++i);
255 out.append("stack.push(arg").append(indx + ");");
263 final int indx = readByte(byteCodes, ++i);
264 out.append("arg" + indx).append(" = stack.pop();");
272 out.append("arg0 = stack.pop();");
279 out.append("arg1 = stack.pop();");
286 out.append("arg2 = stack.pop();");
293 out.append("arg3 = stack.pop();");
299 out.append("stack.push(stack.pop() + stack.pop());");
305 out.append("{ var tmp = stack.pop(); stack.push(stack.pop() - tmp); }");
311 out.append("stack.push(stack.pop() * stack.pop());");
315 out.append("{ var tmp = stack.pop(); stack.push(Math.floor(stack.pop() / tmp)); }");
319 out.append("{ var tmp = stack.pop(); stack.push(stack.pop() / tmp); }");
325 out.append("{ var d = stack.pop(); stack.push(stack.pop() % d); }");
329 out.append("stack.push(stack.pop() & stack.pop());");
333 out.append("stack.push(stack.pop() | stack.pop());");
337 out.append("stack.push(stack.pop() ^ stack.pop());");
343 out.append("stack.push(- stack.pop());");
347 out.append("{ var v = stack.pop(); stack.push(stack.pop() << v); }");
351 out.append("{ var v = stack.pop(); stack.push(stack.pop() >> v); }");
355 out.append("{ var v = stack.pop(); stack.push(stack.pop() >>> v); }");
358 final int varIndx = readByte(byteCodes, ++i);
359 final int incrBy = byteCodes[++i];
361 out.append("arg" + varIndx).append("++;");
363 out.append("arg" + varIndx).append(" += " + incrBy).append(";");
368 out.append("return;");
375 out.append("return stack.pop();");
386 out.append("/* number conversion */");
392 out.append("stack.push(Math.floor(stack.pop()));");
397 out.append("/* number conversion */");
399 case opc_aconst_null:
400 out.append("stack.push(null);");
403 out.append("stack.push(-1);");
409 out.append("stack.push(0);");
415 out.append("stack.push(1);");
419 out.append("stack.push(2);");
422 out.append("stack.push(3);");
425 out.append("stack.push(4);");
428 out.append("stack.push(5);");
431 int indx = readByte(byteCodes, ++i);
432 String v = encodeConstant(indx);
433 out.append("stack.push(").append(v).append(");");
438 int indx = readIntArg(byteCodes, i);
440 String v = encodeConstant(indx);
441 out.append("stack.push(").append(v).append(");");
449 out.append("{ var delta = stack.pop() - stack.pop(); stack.push(delta < 0 ?-1 : (delta == 0 ? 0 : 1)); }");
453 i = generateIf(byteCodes, i, "===");
456 i = generateIf(byteCodes, i, "!=");
458 case opc_if_icmpeq: {
459 i = generateIf(byteCodes, i, "==");
463 int indx = i + readIntArg(byteCodes, i);
464 out.append("if (stack.pop() == 0) { gt = " + indx);
465 out.append("; continue; }");
470 int indx = i + readIntArg(byteCodes, i);
471 out.append("if (stack.pop() != 0) { gt = " + indx);
472 out.append("; continue; }");
477 int indx = i + readIntArg(byteCodes, i);
478 out.append("if (stack.pop() < 0) { gt = " + indx);
479 out.append("; continue; }");
484 int indx = i + readIntArg(byteCodes, i);
485 out.append("if (stack.pop() <= 0) { gt = " + indx);
486 out.append("; continue; }");
491 int indx = i + readIntArg(byteCodes, i);
492 out.append("if (stack.pop() > 0) { gt = " + indx);
493 out.append("; continue; }");
498 int indx = i + readIntArg(byteCodes, i);
499 out.append("if (stack.pop() >= 0) { gt = " + indx);
500 out.append("; continue; }");
504 case opc_ifnonnull: {
505 int indx = i + readIntArg(byteCodes, i);
506 out.append("if (stack.pop() !== null) { gt = " + indx);
507 out.append("; continue; }");
512 int indx = i + readIntArg(byteCodes, i);
513 out.append("if (stack.pop() === null) { gt = " + indx);
514 out.append("; continue; }");
519 i = generateIf(byteCodes, i, "!=");
522 i = generateIf(byteCodes, i, ">");
525 i = generateIf(byteCodes, i, ">=");
528 i = generateIf(byteCodes, i, "<");
531 i = generateIf(byteCodes, i, "<=");
534 int indx = i + readIntArg(byteCodes, i);
535 out.append("gt = " + indx).append("; continue;");
539 case opc_lookupswitch: {
540 int table = i / 4 * 4 + 4;
541 int dflt = i + readInt4(byteCodes, table);
543 int n = readInt4(byteCodes, table);
545 out.append("switch (stack.pop()) {\n");
547 int cnstnt = readInt4(byteCodes, table);
549 int offset = i + readInt4(byteCodes, table);
551 out.append(" case " + cnstnt).append(": gt = " + offset).append("; continue;\n");
553 out.append(" default: gt = " + dflt).append("; continue;\n}");
557 case opc_tableswitch: {
558 int table = i / 4 * 4 + 4;
559 int dflt = i + readInt4(byteCodes, table);
561 int low = readInt4(byteCodes, table);
563 int high = readInt4(byteCodes, table);
565 out.append("switch (stack.pop()) {\n");
566 while (low <= high) {
567 int offset = i + readInt4(byteCodes, table);
569 out.append(" case " + low).append(": gt = " + offset).append("; continue;\n");
572 out.append(" default: gt = " + dflt).append("; continue;\n}");
576 case opc_invokeinterface: {
577 i = invokeVirtualMethod(byteCodes, i) + 2;
580 case opc_invokevirtual:
581 i = invokeVirtualMethod(byteCodes, i);
583 case opc_invokespecial:
584 i = invokeStaticMethod(byteCodes, i, false);
586 case opc_invokestatic:
587 i = invokeStaticMethod(byteCodes, i, true);
590 int indx = readIntArg(byteCodes, i);
591 String ci = jc.getClassName(indx);
592 out.append("stack.push(");
593 out.append("new ").append(ci.replace('/','_'));
600 int type = byteCodes[i++];
601 out.append("stack.push(new Array(stack.pop()).fillNulls());");
604 case opc_anewarray: {
605 i += 2; // skip type of array
606 out.append("stack.push(new Array(stack.pop()).fillNulls());");
609 case opc_multianewarray: {
611 int dim = readByte(byteCodes, ++i);
612 out.append("{ var a0 = new Array(stack.pop()).fillNulls();");
613 for (int d = 1; d < dim; d++) {
614 out.append("\n var l" + d).append(" = stack.pop();");
615 out.append("\n for (var i" + d).append (" = 0; i" + d).
616 append(" < a" + (d - 1)).
617 append(".length; i" + d).append("++) {");
618 out.append("\n var a" + d).
619 append (" = new Array(l" + d).append(").fillNulls();");
620 out.append("\n a" + (d - 1)).append("[i" + d).append("] = a" + d).
623 for (int d = 1; d < dim; d++) {
626 out.append("\nstack.push(a0); }");
629 case opc_arraylength:
630 out.append("stack.push(stack.pop().length);");
640 out.append("{ var value = stack.pop(); var indx = stack.pop(); stack.pop()[indx] = value; }");
651 out.append("{ var indx = stack.pop(); stack.push(stack.pop()[indx]); }");
655 out.append("stack.pop();");
657 out.append("stack.pop();");
660 out.append("stack.push(stack[stack.length - 1]);");
663 out.append("{ var v1 = stack.pop(); var v2 = stack.pop(); stack.push(v1); stack.push(v2); stack.push(v1); }");
666 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); }");
669 out.append("stack.push(" + byteCodes[++i] + ");");
672 out.append("stack.push(" + readIntArg(byteCodes, i) + ");");
676 int indx = readIntArg(byteCodes, i);
677 String[] fi = jc.getFieldInfoName(indx);
678 out.append("stack.push(stack.pop().fld_").
679 append(fi[1]).append(");");
683 case opc_getstatic: {
684 int indx = readIntArg(byteCodes, i);
685 String[] fi = jc.getFieldInfoName(indx);
686 out.append("stack.push(").append(fi[0].replace('/', '_'));
687 out.append('_').append(fi[1]).append(");");
692 case opc_putstatic: {
693 int indx = readIntArg(byteCodes, i);
694 String[] fi = jc.getFieldInfoName(indx);
695 out.append(fi[0].replace('/', '_'));
696 out.append('_').append(fi[1]).append(" = stack.pop();");
702 int indx = readIntArg(byteCodes, i);
703 String[] fi = jc.getFieldInfoName(indx);
704 out.append("{ var v = stack.pop(); stack.pop().fld_")
705 .append(fi[1]).append(" = v; }");
709 case opc_checkcast: {
710 int indx = readIntArg(byteCodes, i);
711 final String type = jc.getClassName(indx);
712 if (!type.startsWith("[")) {
713 // no way to check arrays right now
714 out.append("if(stack[stack.length - 1].$instOf_")
715 .append(type.replace('/', '_'))
716 .append(" != 1) throw {};"); // XXX proper exception
721 case opc_instanceof: {
722 int indx = readIntArg(byteCodes, i);
723 final String type = jc.getClassName(indx);
724 out.append("stack.push(stack.pop().$instOf_")
725 .append(type.replace('/', '_'))
726 .append(" ? 1 : 0);");
731 out.append("{ var t = stack.pop(); stack = new Array(1); stack[0] = t; throw t; }");
735 out.append("throw 'unknown bytecode " + c + "';");
740 for (int j = prev; j <= i; j++) {
742 final int cc = readByte(byteCodes, j);
743 out.append(Integer.toString(cc));
750 private int generateIf(byte[] byteCodes, int i, final String test) throws IOException {
751 int indx = i + readIntArg(byteCodes, i);
752 out.append("if (stack.pop() ").append(test).append(" stack.pop()) { gt = " + indx);
753 out.append("; continue; }");
757 private int readIntArg(byte[] byteCodes, int offsetInstruction) {
758 final int indxHi = byteCodes[offsetInstruction + 1] << 8;
759 final int indxLo = byteCodes[offsetInstruction + 2];
760 return (indxHi & 0xffffff00) | (indxLo & 0xff);
762 private int readInt4(byte[] byteCodes, int offsetInstruction) {
763 final int d = byteCodes[offsetInstruction + 0] << 24;
764 final int c = byteCodes[offsetInstruction + 1] << 16;
765 final int b = byteCodes[offsetInstruction + 2] << 8;
766 final int a = byteCodes[offsetInstruction + 3];
767 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
769 private int readByte(byte[] byteCodes, int offsetInstruction) {
770 return (byteCodes[offsetInstruction] + 256) % 256;
773 private static void countArgs(String descriptor, boolean[] hasReturnType, StringBuilder sig, StringBuilder cnt) {
775 Boolean count = null;
776 boolean array = false;
777 int firstPos = sig.length();
778 while (i < descriptor.length()) {
779 char ch = descriptor.charAt(i++);
803 if (ch == 'J' || ch == 'D') {
809 hasReturnType[0] = true;
810 sig.insert(firstPos, ch);
812 sig.insert(firstPos, 'A');
819 hasReturnType[0] = false;
820 sig.insert(firstPos, 'V');
823 int next = descriptor.indexOf(';', i);
829 sig.append(descriptor.substring(i, next).replace('/', '_'));
832 sig.insert(firstPos, descriptor.substring(i, next).replace('/', '_'));
833 sig.insert(firstPos, ch);
835 sig.insert(firstPos, 'A');
837 hasReturnType[0] = true;
845 break; // invalid character
850 private void generateStaticField(FieldData v) throws IOException {
852 .append(className(jc))
853 .append('_').append(v.getName()).append(initField(v));
856 private String findMethodName(MethodData m, StringBuilder cnt) {
857 StringBuilder name = new StringBuilder();
858 if ("<init>".equals(m.getName())) { // NOI18N
859 name.append("cons"); // NOI18N
860 } else if ("<clinit>".equals(m.getName())) { // NOI18N
861 name.append("class"); // NOI18N
863 name.append(m.getName());
866 boolean hasReturn[] = { false };
867 countArgs(findDescriptor(m.getInternalSig()), hasReturn, name, cnt);
868 return name.toString();
871 private String findMethodName(String[] mi, StringBuilder cnt, boolean[] hasReturn) {
872 StringBuilder name = new StringBuilder();
873 String descr = mi[2];//mi.getDescriptor();
875 if ("<init>".equals(nm)) { // NOI18N
876 name.append("cons"); // NOI18N
880 countArgs(findDescriptor(descr), hasReturn, name, cnt);
881 return name.toString();
884 private int invokeStaticMethod(byte[] byteCodes, int i, boolean isStatic)
886 int methodIndex = readIntArg(byteCodes, i);
887 String[] mi = jc.getFieldInfoName(methodIndex);
888 boolean[] hasReturn = { false };
889 StringBuilder cnt = new StringBuilder();
890 String mn = findMethodName(mi, cnt, hasReturn);
892 for (int j = cnt.length() - 1; j >= 0; j--) {
893 out.append("var v" + j).append(" = stack.pop(); ");
897 out.append("stack.push(");
899 final String in = mi[0];
900 out.append(in.replace('/', '_'));
902 out.append(".prototype.");
910 out.append("stack.pop()");
913 for (int j = 0; j < cnt.length(); j++) {
927 private int invokeVirtualMethod(byte[] byteCodes, int i)
929 int methodIndex = readIntArg(byteCodes, i);
930 String[] mi = jc.getFieldInfoName(methodIndex);
931 boolean[] hasReturn = { false };
932 StringBuilder cnt = new StringBuilder();
933 String mn = findMethodName(mi, cnt, hasReturn);
935 for (int j = cnt.length() - 1; j >= 0; j--) {
936 out.append("var v" + j).append(" = stack.pop(); ");
938 out.append("var self = stack.pop(); ");
940 out.append("stack.push(");
946 for (int j = 0; j < cnt.length(); j++) {
959 private void addReference(String cn) throws IOException {
960 if (requireReference(cn)) {
961 out.append(" /* needs ").append(cn).append(" */");
965 private void outType(String d, StringBuilder out) {
967 while (d.charAt(0) == '[') {
971 if (d.charAt(0) == 'L') {
972 assert d.charAt(d.length() - 1) == ';';
973 out.append(d.replace('/', '_').substring(0, d.length() - 1));
979 private String encodeConstant(int entryIndex) {
980 String s = jc.stringValue(entryIndex, true);
984 private String findDescriptor(String d) {
985 return d.replace('[', 'A');
988 private boolean javaScriptBody(MethodData m, boolean isStatic) throws IOException {
989 byte[] arr = m.findAnnotationData(true);
993 final String jvmType = "L" + JavaScriptBody.class.getName().replace('.', '/') + ";";
994 class P extends AnnotationParser {
996 String[] args = new String[30];
1000 protected void visitAttr(String type, String attr, String value) {
1001 if (type.equals(jvmType)) {
1002 if ("body".equals(attr)) {
1004 } else if ("args".equals(attr)) {
1005 args[cnt++] = value;
1007 throw new IllegalArgumentException(attr);
1014 if (p.body == null) {
1017 StringBuilder cnt = new StringBuilder();
1018 out.append("\nfunction ").append(className(jc)).append('_').
1019 append(findMethodName(m, cnt));
1024 out.append(p.args[0]);
1031 for (int i = 0; i < cnt.length(); i++) {
1033 out.append(p.args[index]);
1037 out.append(") {").append("\n");
1039 out.append("\n}\n");
1042 private static String className(ClassData jc) {
1043 //return jc.getName().getInternalName().replace('/', '_');
1044 return jc.getClassName().replace('/', '_');
1047 private static String[] findAnnotation(
1048 byte[] arr, ClassData cd, final String className,
1049 final String... attrNames
1050 ) throws IOException {
1054 final String[] values = new String[attrNames.length];
1055 final boolean[] found = { false };
1056 final String jvmType = "L" + className.replace('.', '/') + ";";
1057 AnnotationParser ap = new AnnotationParser() {
1059 protected void visitAttr(String type, String attr, String value) {
1060 if (type.equals(jvmType)) {
1062 for (int i = 0; i < attrNames.length; i++) {
1063 if (attrNames[i].equals(attr)) {
1072 return found[0] ? values : null;
1075 private CharSequence initField(FieldData v) {
1076 final String is = v.getInternalSig();
1077 if (is.length() == 1) {
1078 switch (is.charAt(0)) {
1084 case 'I': return " = 0;";
1086 case 'D': return " = 0.0;";
1088 throw new IllegalStateException(is);