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 final String className = className(jc);
85 out.append("\nfunction ").append(className);
87 for (FieldData v : jc.getFields()) {
89 out.append("\n this.fld_").
90 append(v.getName()).append(initField(v));
93 out.append("\n}\n\nfunction ").append(className).append("_proto() {");
94 out.append("\n if (").append(className).
95 append(".prototype.$instOf_").append(className).append(") {");
96 out.append("\n return new ").append(className).append(";");
98 for (FieldData v : jc.getFields()) {
100 generateStaticField(v);
103 // ClassName sc = jc.getSuperClass();
104 String sc = jc.getSuperClassName(); // with _
106 out.append("\n var p = ").append(className)
107 .append(".prototype = ").
108 append(sc.replace('/', '_')).append("_proto();");
110 out.append("\n var p = ").append(className).append(".prototype;");
112 for (MethodData m : jc.getMethods()) {
113 if (!m.getName().contains("<cinit>")) {
114 generateMethodReference("\n p.", m);
117 out.append("\n p.$instOf_").append(className).append(" = true;");
118 for (String superInterface : jc.getSuperInterfaces()) {
119 out.append("\n p.$instOf_").append(superInterface.replace('/', '_')).append(" = true;");
121 out.append("\n return new ").append(className).append(";");
123 out.append("\n").append(className).append("_proto();");
124 StringBuilder sb = new StringBuilder();
125 for (String init : toInitilize.toArray()) {
126 sb.append("\n").append(init).append("();");
128 return sb.toString();
130 private void generateStaticMethod(MethodData m, StringArray toInitilize) throws IOException {
131 if (javaScriptBody(m, true)) {
134 StringBuilder argsCnt = new StringBuilder();
135 final String mn = findMethodName(m, argsCnt);
136 out.append("\nfunction ").append(
138 ).append('_').append(mn);
139 if (mn.equals("classV")) {
140 toInitilize.add(className(jc) + '_' + mn);
144 for (int index = 0, i = 0; i < argsCnt.length(); i++) {
146 out.append("arg").append(String.valueOf(index));
148 final String desc = null;// XXX findDescriptor(args.get(i).getDescriptor());
149 if (argsCnt.charAt(i) == '1') {
155 out.append(") {").append("\n");
156 final byte[] code = m.getCode();
158 int len = m.getMaxLocals();
159 for (int index = argsCnt.length(), i = argsCnt.length(); i < len; i++) {
161 out.append("arg").append(String.valueOf(i)).append(";\n");
163 out.append(" var stack = new Array();\n");
166 out.append(" /* no code found for ").append(m.getInternalSig()).append(" */\n");
171 private void generateMethodReference(String prefix, MethodData m) throws IOException {
172 final String name = findMethodName(m, new StringBuilder());
173 out.append(prefix).append(name).append(" = ")
174 .append(className(jc))
175 .append('_').append(name).append(";");
178 private void generateInstanceMethod(MethodData m) throws IOException {
179 if (javaScriptBody(m, false)) {
182 StringBuilder argsCnt = new StringBuilder();
183 out.append("\nfunction ").append(
185 ).append('_').append(findMethodName(m, argsCnt));
188 for (int index = 1, i = 0; i < argsCnt.length(); i++) {
190 out.append("arg").append(String.valueOf(index));
191 if (argsCnt.charAt(i) == '1') {
197 out.append(") {").append("\n");
198 final byte[] code = m.getCode();
200 int len = m.getMaxLocals();
201 for (int index = argsCnt.length(), i = argsCnt.length(); i < len; i++) {
203 out.append("arg").append(String.valueOf(i + 1)).append(";\n");
205 out.append(";\n var stack = new Array();\n");
208 out.append(" /* no code found for ").append(m.getInternalSig()).append(" */\n");
213 private void produceCode(byte[] byteCodes) throws IOException {
214 out.append("\n var gt = 0;\n for(;;) switch(gt) {\n");
215 for (int i = 0; i < byteCodes.length; i++) {
217 out.append(" case " + i).append(": ");
218 final int c = readByte(byteCodes, i);
225 out.append("stack.push(arg0);");
232 out.append("stack.push(arg1);");
239 out.append("stack.push(arg2);");
246 out.append("stack.push(arg3);");
253 final int indx = readByte(byteCodes, ++i);
254 out.append("stack.push(arg").append(indx + ");");
262 final int indx = readByte(byteCodes, ++i);
263 out.append("arg" + indx).append(" = stack.pop();");
271 out.append("arg0 = stack.pop();");
278 out.append("arg1 = stack.pop();");
285 out.append("arg2 = stack.pop();");
292 out.append("arg3 = stack.pop();");
298 out.append("stack.push(stack.pop() + stack.pop());");
304 out.append("{ var tmp = stack.pop(); stack.push(stack.pop() - tmp); }");
310 out.append("stack.push(stack.pop() * stack.pop());");
314 out.append("{ var tmp = stack.pop(); stack.push(Math.floor(stack.pop() / tmp)); }");
318 out.append("{ var tmp = stack.pop(); stack.push(stack.pop() / tmp); }");
324 out.append("{ var d = stack.pop(); stack.push(stack.pop() % d); }");
328 out.append("stack.push(stack.pop() & stack.pop());");
332 out.append("stack.push(stack.pop() | stack.pop());");
336 out.append("stack.push(stack.pop() ^ stack.pop());");
342 out.append("stack.push(- stack.pop());");
346 out.append("{ var v = stack.pop(); stack.push(stack.pop() << v); }");
350 out.append("{ var v = stack.pop(); stack.push(stack.pop() >> v); }");
354 out.append("{ var v = stack.pop(); stack.push(stack.pop() >>> v); }");
357 final int varIndx = readByte(byteCodes, ++i);
358 final int incrBy = byteCodes[++i];
360 out.append("arg" + varIndx).append("++;");
362 out.append("arg" + varIndx).append(" += " + incrBy).append(";");
367 out.append("return;");
374 out.append("return stack.pop();");
385 out.append("/* number conversion */");
391 out.append("stack.push(Math.floor(stack.pop()));");
396 out.append("/* number conversion */");
398 case opc_aconst_null:
399 out.append("stack.push(null);");
402 out.append("stack.push(-1);");
408 out.append("stack.push(0);");
414 out.append("stack.push(1);");
418 out.append("stack.push(2);");
421 out.append("stack.push(3);");
424 out.append("stack.push(4);");
427 out.append("stack.push(5);");
430 int indx = readByte(byteCodes, ++i);
431 String v = encodeConstant(indx);
432 out.append("stack.push(").append(v).append(");");
437 int indx = readIntArg(byteCodes, i);
439 String v = encodeConstant(indx);
440 out.append("stack.push(").append(v).append(");");
448 out.append("{ var delta = stack.pop() - stack.pop(); stack.push(delta < 0 ?-1 : (delta == 0 ? 0 : 1)); }");
452 i = generateIf(byteCodes, i, "===");
455 i = generateIf(byteCodes, i, "!=");
457 case opc_if_icmpeq: {
458 i = generateIf(byteCodes, i, "==");
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; }");
490 int indx = i + readIntArg(byteCodes, i);
491 out.append("if (stack.pop() > 0) { gt = " + indx);
492 out.append("; continue; }");
497 int indx = i + readIntArg(byteCodes, i);
498 out.append("if (stack.pop() >= 0) { gt = " + indx);
499 out.append("; continue; }");
503 case opc_ifnonnull: {
504 int indx = i + readIntArg(byteCodes, i);
505 out.append("if (stack.pop() !== null) { gt = " + indx);
506 out.append("; continue; }");
511 int indx = i + readIntArg(byteCodes, i);
512 out.append("if (stack.pop() === null) { gt = " + indx);
513 out.append("; continue; }");
518 i = generateIf(byteCodes, i, "!=");
521 i = generateIf(byteCodes, i, ">");
524 i = generateIf(byteCodes, i, ">=");
527 i = generateIf(byteCodes, i, "<");
530 i = generateIf(byteCodes, i, "<=");
533 int indx = i + readIntArg(byteCodes, i);
534 out.append("gt = " + indx).append("; continue;");
538 case opc_lookupswitch: {
539 int table = i / 4 * 4 + 4;
540 int dflt = i + readInt4(byteCodes, table);
542 int n = readInt4(byteCodes, table);
544 out.append("switch (stack.pop()) {\n");
546 int cnstnt = readInt4(byteCodes, table);
548 int offset = i + readInt4(byteCodes, table);
550 out.append(" case " + cnstnt).append(": gt = " + offset).append("; continue;\n");
552 out.append(" default: gt = " + dflt).append("; continue;\n}");
556 case opc_tableswitch: {
557 int table = i / 4 * 4 + 4;
558 int dflt = i + readInt4(byteCodes, table);
560 int low = readInt4(byteCodes, table);
562 int high = readInt4(byteCodes, table);
564 out.append("switch (stack.pop()) {\n");
565 while (low <= high) {
566 int offset = i + readInt4(byteCodes, table);
568 out.append(" case " + low).append(": gt = " + offset).append("; continue;\n");
571 out.append(" default: gt = " + dflt).append("; continue;\n}");
575 case opc_invokeinterface: {
576 i = invokeVirtualMethod(byteCodes, i) + 2;
579 case opc_invokevirtual:
580 i = invokeVirtualMethod(byteCodes, i);
582 case opc_invokespecial:
583 i = invokeStaticMethod(byteCodes, i, false);
585 case opc_invokestatic:
586 i = invokeStaticMethod(byteCodes, i, true);
589 int indx = readIntArg(byteCodes, i);
590 String ci = jc.getClassName(indx);
591 out.append("stack.push(");
592 out.append("new ").append(ci.replace('/','_'));
599 int type = byteCodes[i++];
600 out.append("stack.push(new Array(stack.pop()).fillNulls());");
603 case opc_anewarray: {
604 i += 2; // skip type of array
605 out.append("stack.push(new Array(stack.pop()).fillNulls());");
608 case opc_multianewarray: {
610 int dim = readByte(byteCodes, ++i);
611 out.append("{ var a0 = new Array(stack.pop()).fillNulls();");
612 for (int d = 1; d < dim; d++) {
613 out.append("\n var l" + d).append(" = stack.pop();");
614 out.append("\n for (var i" + d).append (" = 0; i" + d).
615 append(" < a" + (d - 1)).
616 append(".length; i" + d).append("++) {");
617 out.append("\n var a" + d).
618 append (" = new Array(l" + d).append(").fillNulls();");
619 out.append("\n a" + (d - 1)).append("[i" + d).append("] = a" + d).
622 for (int d = 1; d < dim; d++) {
625 out.append("\nstack.push(a0); }");
628 case opc_arraylength:
629 out.append("stack.push(stack.pop().length);");
639 out.append("{ var value = stack.pop(); var indx = stack.pop(); stack.pop()[indx] = value; }");
650 out.append("{ var indx = stack.pop(); stack.push(stack.pop()[indx]); }");
654 out.append("stack.pop();");
656 out.append("stack.pop();");
659 out.append("stack.push(stack[stack.length - 1]);");
662 out.append("{ var v1 = stack.pop(); var v2 = stack.pop(); stack.push(v1); stack.push(v2); stack.push(v1); }");
665 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); }");
668 out.append("stack.push(" + byteCodes[++i] + ");");
671 out.append("stack.push(" + readIntArg(byteCodes, i) + ");");
675 int indx = readIntArg(byteCodes, i);
676 String[] fi = jc.getFieldInfoName(indx);
677 out.append("stack.push(stack.pop().fld_").
678 append(fi[1]).append(");");
682 case opc_getstatic: {
683 int indx = readIntArg(byteCodes, i);
684 String[] fi = jc.getFieldInfoName(indx);
685 out.append("stack.push(").append(fi[0].replace('/', '_'));
686 out.append('.').append(fi[1]).append(");");
691 case opc_putstatic: {
692 int indx = readIntArg(byteCodes, i);
693 String[] fi = jc.getFieldInfoName(indx);
694 out.append(fi[0].replace('/', '_'));
695 out.append('.').append(fi[1]).append(" = stack.pop();");
701 int indx = readIntArg(byteCodes, i);
702 String[] fi = jc.getFieldInfoName(indx);
703 out.append("{ var v = stack.pop(); stack.pop().fld_")
704 .append(fi[1]).append(" = v; }");
708 case opc_checkcast: {
709 int indx = readIntArg(byteCodes, i);
710 final String type = jc.getClassName(indx);
711 if (!type.startsWith("[")) {
712 // no way to check arrays right now
713 out.append("if(stack[stack.length - 1].$instOf_")
714 .append(type.replace('/', '_'))
715 .append(" != 1) throw {};"); // XXX proper exception
720 case opc_instanceof: {
721 int indx = readIntArg(byteCodes, i);
722 final String type = jc.getClassName(indx);
723 out.append("stack.push(stack.pop().$instOf_")
724 .append(type.replace('/', '_'))
725 .append(" ? 1 : 0);");
730 out.append("{ var t = stack.pop(); stack = new Array(1); stack[0] = t; throw t; }");
734 out.append("throw 'unknown bytecode " + c + "';");
739 for (int j = prev; j <= i; j++) {
741 final int cc = readByte(byteCodes, j);
742 out.append(Integer.toString(cc));
749 private int generateIf(byte[] byteCodes, int i, final String test) throws IOException {
750 int indx = i + readIntArg(byteCodes, i);
751 out.append("if (stack.pop() ").append(test).append(" stack.pop()) { gt = " + indx);
752 out.append("; continue; }");
756 private int readIntArg(byte[] byteCodes, int offsetInstruction) {
757 final int indxHi = byteCodes[offsetInstruction + 1] << 8;
758 final int indxLo = byteCodes[offsetInstruction + 2];
759 return (indxHi & 0xffffff00) | (indxLo & 0xff);
761 private int readInt4(byte[] byteCodes, int offsetInstruction) {
762 final int d = byteCodes[offsetInstruction + 0] << 24;
763 final int c = byteCodes[offsetInstruction + 1] << 16;
764 final int b = byteCodes[offsetInstruction + 2] << 8;
765 final int a = byteCodes[offsetInstruction + 3];
766 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
768 private int readByte(byte[] byteCodes, int offsetInstruction) {
769 return (byteCodes[offsetInstruction] + 256) % 256;
772 private static void countArgs(String descriptor, boolean[] hasReturnType, StringBuilder sig, StringBuilder cnt) {
774 Boolean count = null;
775 boolean array = false;
776 int firstPos = sig.length();
777 while (i < descriptor.length()) {
778 char ch = descriptor.charAt(i++);
802 if (ch == 'J' || ch == 'D') {
808 hasReturnType[0] = true;
809 sig.insert(firstPos, ch);
811 sig.insert(firstPos, 'A');
818 hasReturnType[0] = false;
819 sig.insert(firstPos, 'V');
822 int next = descriptor.indexOf(';', i);
828 sig.append(descriptor.substring(i, next).replace('/', '_'));
831 sig.insert(firstPos, descriptor.substring(i, next).replace('/', '_'));
832 sig.insert(firstPos, ch);
834 sig.insert(firstPos, 'A');
836 hasReturnType[0] = true;
844 break; // invalid character
849 private void generateStaticField(FieldData v) throws IOException {
851 .append(className(jc))
852 .append('.').append(v.getName()).append(initField(v));
855 private String findMethodName(MethodData m, StringBuilder cnt) {
856 StringBuilder name = new StringBuilder();
857 if ("<init>".equals(m.getName())) { // NOI18N
858 name.append("cons"); // NOI18N
859 } else if ("<clinit>".equals(m.getName())) { // NOI18N
860 name.append("class"); // NOI18N
862 name.append(m.getName());
865 boolean hasReturn[] = { false };
866 countArgs(findDescriptor(m.getInternalSig()), hasReturn, name, cnt);
867 return name.toString();
870 private String findMethodName(String[] mi, StringBuilder cnt, boolean[] hasReturn) {
871 StringBuilder name = new StringBuilder();
872 String descr = mi[2];//mi.getDescriptor();
874 if ("<init>".equals(nm)) { // NOI18N
875 name.append("cons"); // NOI18N
879 countArgs(findDescriptor(descr), hasReturn, name, cnt);
880 return name.toString();
883 private int invokeStaticMethod(byte[] byteCodes, int i, boolean isStatic)
885 int methodIndex = readIntArg(byteCodes, i);
886 String[] mi = jc.getFieldInfoName(methodIndex);
887 boolean[] hasReturn = { false };
888 StringBuilder cnt = new StringBuilder();
889 String mn = findMethodName(mi, cnt, hasReturn);
891 for (int j = cnt.length() - 1; j >= 0; j--) {
892 out.append("var v" + j).append(" = stack.pop(); ");
896 out.append("stack.push(");
898 final String in = mi[0];
899 out.append(in.replace('/', '_'));
900 out.append(".prototype.");
905 out.append("stack.pop()");
908 for (int j = 0; j < cnt.length(); j++) {
922 private int invokeVirtualMethod(byte[] byteCodes, int i)
924 int methodIndex = readIntArg(byteCodes, i);
925 String[] mi = jc.getFieldInfoName(methodIndex);
926 boolean[] hasReturn = { false };
927 StringBuilder cnt = new StringBuilder();
928 String mn = findMethodName(mi, cnt, hasReturn);
930 for (int j = cnt.length() - 1; j >= 0; j--) {
931 out.append("var v" + j).append(" = stack.pop(); ");
933 out.append("var self = stack.pop(); ");
935 out.append("stack.push(");
941 for (int j = 0; j < cnt.length(); j++) {
954 private void addReference(String cn) throws IOException {
955 if (requireReference(cn)) {
956 out.append(" /* needs ").append(cn).append(" */");
960 private void outType(String d, StringBuilder out) {
962 while (d.charAt(0) == '[') {
966 if (d.charAt(0) == 'L') {
967 assert d.charAt(d.length() - 1) == ';';
968 out.append(d.replace('/', '_').substring(0, d.length() - 1));
974 private String encodeConstant(int entryIndex) {
975 String s = jc.stringValue(entryIndex, true);
979 private String findDescriptor(String d) {
980 return d.replace('[', 'A');
983 private boolean javaScriptBody(MethodData m, boolean isStatic) throws IOException {
984 byte[] arr = m.findAnnotationData(true);
988 final String jvmType = "L" + JavaScriptBody.class.getName().replace('.', '/') + ";";
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("\nfunction ").append(className(jc)).append('_').
1014 append(findMethodName(m, cnt));
1019 out.append(p.args[0]);
1026 for (int i = 0; i < cnt.length(); i++) {
1028 out.append(p.args[index]);
1032 out.append(") {").append("\n");
1034 out.append("\n}\n");
1037 private static String className(ClassData jc) {
1038 //return jc.getName().getInternalName().replace('/', '_');
1039 return jc.getClassName().replace('/', '_');
1042 private static String[] findAnnotation(
1043 byte[] arr, ClassData cd, final String className,
1044 final String... attrNames
1045 ) throws IOException {
1049 final String[] values = new String[attrNames.length];
1050 final boolean[] found = { false };
1051 final String jvmType = "L" + className.replace('.', '/') + ";";
1052 AnnotationParser ap = new AnnotationParser() {
1054 protected void visitAttr(String type, String attr, String value) {
1055 if (type.equals(jvmType)) {
1057 for (int i = 0; i < attrNames.length; i++) {
1058 if (attrNames[i].equals(attr)) {
1067 return found[0] ? values : null;
1070 private CharSequence initField(FieldData v) {
1071 final String is = v.getInternalSig();
1072 if (is.length() == 1) {
1073 switch (is.charAt(0)) {
1079 case 'I': return " = 0;";
1081 case 'D': return " = 0.0;";
1083 throw new IllegalStateException(is);