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\n").append(className);
78 out.append(" = function() {");
79 out.append("\n if (!").append(className).
80 append(".prototype.$instOf_").append(className).append(") {");
81 for (FieldData v : jc.getFields()) {
83 generateStaticField(v);
86 // ClassName sc = jc.getSuperClass();
87 String sc = jc.getSuperClassName(); // with _
89 out.append("\n var p = ").append(className)
90 .append(".prototype = ").
91 append(sc.replace('/', '_')).append("(true);");
93 out.append("\n var p = ").append(className).append(".prototype;");
95 for (MethodData m : jc.getMethods()) {
97 generateStaticMethod("\n p.", m, toInitilize);
99 generateInstanceMethod("\n p.", m);
102 out.append("\n p.$instOf_").append(className).append(" = true;");
103 for (String superInterface : jc.getSuperInterfaces()) {
104 out.append("\n p.$instOf_").append(superInterface.replace('/', '_')).append(" = true;");
106 out.append("\n if (arguments.length === 0) {");
107 out.append("\n return new ").append(className).append("();");
110 out.append("\n if (arguments.length === 0) {");
111 for (FieldData v : jc.getFields()) {
113 out.append("\n this.fld_").
114 append(v.getName()).append(initField(v));
117 out.append("\n return this;");
119 out.append("\n return new ").append(className).append(";");
121 StringBuilder sb = new StringBuilder();
122 for (String init : toInitilize.toArray()) {
123 sb.append("\n").append(init).append("();");
125 return sb.toString();
127 private void generateStaticMethod(String prefix, MethodData m, StringArray toInitilize) throws IOException {
128 if (javaScriptBody(prefix, m, true)) {
131 StringBuilder argsCnt = new StringBuilder();
132 final String mn = findMethodName(m, argsCnt);
133 out.append(prefix).append(mn).append(" = function");
134 if (mn.equals("classV")) {
135 toInitilize.add(className(jc) + "(true)." + mn);
139 for (int index = 0, i = 0; i < argsCnt.length(); i++) {
141 out.append("arg").append(String.valueOf(index));
143 final String desc = null;// XXX findDescriptor(args.get(i).getDescriptor());
144 if (argsCnt.charAt(i) == '1') {
150 out.append(") {").append("\n");
151 final byte[] code = m.getCode();
153 int len = m.getMaxLocals();
154 for (int index = argsCnt.length(), i = argsCnt.length(); i < len; i++) {
156 out.append("arg").append(String.valueOf(i)).append(";\n");
158 out.append(" var stack = new Array();\n");
161 out.append(" /* no code found for ").append(m.getInternalSig()).append(" */\n");
166 private void generateInstanceMethod(String prefix, MethodData m) throws IOException {
167 if (javaScriptBody(prefix, m, false)) {
170 StringBuilder argsCnt = new StringBuilder();
171 final String mn = findMethodName(m, argsCnt);
172 out.append(prefix).append(mn).append(" = function");
175 for (int index = 1, i = 0; i < argsCnt.length(); i++) {
177 out.append("arg").append(String.valueOf(index));
178 if (argsCnt.charAt(i) == '1') {
184 out.append(") {").append("\n");
185 final byte[] code = m.getCode();
187 int len = m.getMaxLocals();
188 for (int index = argsCnt.length(), i = argsCnt.length(); i < len; i++) {
190 out.append("arg").append(String.valueOf(i + 1)).append(";\n");
192 out.append(";\n var stack = new Array();\n");
195 out.append(" /* no code found for ").append(m.getInternalSig()).append(" */\n");
200 private void produceCode(byte[] byteCodes) throws IOException {
201 out.append("\n var gt = 0;\n for(;;) switch(gt) {\n");
202 for (int i = 0; i < byteCodes.length; i++) {
204 out.append(" case " + i).append(": ");
205 final int c = readByte(byteCodes, i);
212 out.append("stack.push(arg0);");
219 out.append("stack.push(arg1);");
226 out.append("stack.push(arg2);");
233 out.append("stack.push(arg3);");
240 final int indx = readByte(byteCodes, ++i);
241 out.append("stack.push(arg").append(indx + ");");
249 final int indx = readByte(byteCodes, ++i);
250 out.append("arg" + indx).append(" = stack.pop();");
258 out.append("arg0 = stack.pop();");
265 out.append("arg1 = stack.pop();");
272 out.append("arg2 = stack.pop();");
279 out.append("arg3 = stack.pop();");
285 out.append("stack.push(stack.pop() + stack.pop());");
291 out.append("{ var tmp = stack.pop(); stack.push(stack.pop() - tmp); }");
297 out.append("stack.push(stack.pop() * stack.pop());");
301 out.append("{ var tmp = stack.pop(); stack.push(Math.floor(stack.pop() / tmp)); }");
305 out.append("{ var tmp = stack.pop(); stack.push(stack.pop() / tmp); }");
311 out.append("{ var d = stack.pop(); stack.push(stack.pop() % d); }");
315 out.append("stack.push(stack.pop() & stack.pop());");
319 out.append("stack.push(stack.pop() | stack.pop());");
323 out.append("stack.push(stack.pop() ^ stack.pop());");
329 out.append("stack.push(- stack.pop());");
333 out.append("{ var v = stack.pop(); stack.push(stack.pop() << v); }");
337 out.append("{ var v = stack.pop(); stack.push(stack.pop() >> v); }");
341 out.append("{ var v = stack.pop(); stack.push(stack.pop() >>> v); }");
344 final int varIndx = readByte(byteCodes, ++i);
345 final int incrBy = byteCodes[++i];
347 out.append("arg" + varIndx).append("++;");
349 out.append("arg" + varIndx).append(" += " + incrBy).append(";");
354 out.append("return;");
361 out.append("return stack.pop();");
372 out.append("/* number conversion */");
378 out.append("stack.push(Math.floor(stack.pop()));");
383 out.append("/* number conversion */");
385 case opc_aconst_null:
386 out.append("stack.push(null);");
389 out.append("stack.push(-1);");
395 out.append("stack.push(0);");
401 out.append("stack.push(1);");
405 out.append("stack.push(2);");
408 out.append("stack.push(3);");
411 out.append("stack.push(4);");
414 out.append("stack.push(5);");
417 int indx = readByte(byteCodes, ++i);
418 String v = encodeConstant(indx);
419 out.append("stack.push(").append(v).append(");");
424 int indx = readIntArg(byteCodes, i);
426 String v = encodeConstant(indx);
427 out.append("stack.push(").append(v).append(");");
435 out.append("{ var delta = stack.pop() - stack.pop(); stack.push(delta < 0 ?-1 : (delta == 0 ? 0 : 1)); }");
439 i = generateIf(byteCodes, i, "===");
442 i = generateIf(byteCodes, i, "!=");
444 case opc_if_icmpeq: {
445 i = generateIf(byteCodes, i, "==");
449 int indx = i + readIntArg(byteCodes, i);
450 out.append("if (stack.pop() == 0) { gt = " + indx);
451 out.append("; continue; }");
456 int indx = i + readIntArg(byteCodes, i);
457 out.append("if (stack.pop() != 0) { gt = " + indx);
458 out.append("; continue; }");
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; }");
490 case opc_ifnonnull: {
491 int indx = i + readIntArg(byteCodes, i);
492 out.append("if (stack.pop() !== null) { gt = " + indx);
493 out.append("; continue; }");
498 int indx = i + readIntArg(byteCodes, i);
499 out.append("if (stack.pop() === null) { gt = " + indx);
500 out.append("; continue; }");
505 i = generateIf(byteCodes, i, "!=");
508 i = generateIf(byteCodes, i, ">");
511 i = generateIf(byteCodes, i, ">=");
514 i = generateIf(byteCodes, i, "<");
517 i = generateIf(byteCodes, i, "<=");
520 int indx = i + readIntArg(byteCodes, i);
521 out.append("gt = " + indx).append("; continue;");
525 case opc_lookupswitch: {
526 int table = i / 4 * 4 + 4;
527 int dflt = i + readInt4(byteCodes, table);
529 int n = readInt4(byteCodes, table);
531 out.append("switch (stack.pop()) {\n");
533 int cnstnt = readInt4(byteCodes, table);
535 int offset = i + readInt4(byteCodes, table);
537 out.append(" case " + cnstnt).append(": gt = " + offset).append("; continue;\n");
539 out.append(" default: gt = " + dflt).append("; continue;\n}");
543 case opc_tableswitch: {
544 int table = i / 4 * 4 + 4;
545 int dflt = i + readInt4(byteCodes, table);
547 int low = readInt4(byteCodes, table);
549 int high = readInt4(byteCodes, table);
551 out.append("switch (stack.pop()) {\n");
552 while (low <= high) {
553 int offset = i + readInt4(byteCodes, table);
555 out.append(" case " + low).append(": gt = " + offset).append("; continue;\n");
558 out.append(" default: gt = " + dflt).append("; continue;\n}");
562 case opc_invokeinterface: {
563 i = invokeVirtualMethod(byteCodes, i) + 2;
566 case opc_invokevirtual:
567 i = invokeVirtualMethod(byteCodes, i);
569 case opc_invokespecial:
570 i = invokeStaticMethod(byteCodes, i, false);
572 case opc_invokestatic:
573 i = invokeStaticMethod(byteCodes, i, true);
576 int indx = readIntArg(byteCodes, i);
577 String ci = jc.getClassName(indx);
578 out.append("stack.push(");
579 out.append("new ").append(ci.replace('/','_'));
586 int type = byteCodes[i++];
587 out.append("stack.push(new Array(stack.pop()).fillNulls());");
590 case opc_anewarray: {
591 i += 2; // skip type of array
592 out.append("stack.push(new Array(stack.pop()).fillNulls());");
595 case opc_multianewarray: {
597 int dim = readByte(byteCodes, ++i);
598 out.append("{ var a0 = new Array(stack.pop()).fillNulls();");
599 for (int d = 1; d < dim; d++) {
600 out.append("\n var l" + d).append(" = stack.pop();");
601 out.append("\n for (var i" + d).append (" = 0; i" + d).
602 append(" < a" + (d - 1)).
603 append(".length; i" + d).append("++) {");
604 out.append("\n var a" + d).
605 append (" = new Array(l" + d).append(").fillNulls();");
606 out.append("\n a" + (d - 1)).append("[i" + d).append("] = a" + d).
609 for (int d = 1; d < dim; d++) {
612 out.append("\nstack.push(a0); }");
615 case opc_arraylength:
616 out.append("stack.push(stack.pop().length);");
626 out.append("{ var value = stack.pop(); var indx = stack.pop(); stack.pop()[indx] = value; }");
637 out.append("{ var indx = stack.pop(); stack.push(stack.pop()[indx]); }");
641 out.append("stack.pop();");
643 out.append("stack.pop();");
646 out.append("stack.push(stack[stack.length - 1]);");
649 out.append("{ var v1 = stack.pop(); var v2 = stack.pop(); stack.push(v1); stack.push(v2); stack.push(v1); }");
652 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); }");
655 out.append("stack.push(" + byteCodes[++i] + ");");
658 out.append("stack.push(" + readIntArg(byteCodes, i) + ");");
662 int indx = readIntArg(byteCodes, i);
663 String[] fi = jc.getFieldInfoName(indx);
664 out.append("stack.push(stack.pop().fld_").
665 append(fi[1]).append(");");
669 case opc_getstatic: {
670 int indx = readIntArg(byteCodes, i);
671 String[] fi = jc.getFieldInfoName(indx);
672 out.append("stack.push(").append(fi[0].replace('/', '_'));
673 out.append('.').append(fi[1]).append(");");
678 case opc_putstatic: {
679 int indx = readIntArg(byteCodes, i);
680 String[] fi = jc.getFieldInfoName(indx);
681 out.append(fi[0].replace('/', '_'));
682 out.append('.').append(fi[1]).append(" = stack.pop();");
688 int indx = readIntArg(byteCodes, i);
689 String[] fi = jc.getFieldInfoName(indx);
690 out.append("{ var v = stack.pop(); stack.pop().fld_")
691 .append(fi[1]).append(" = v; }");
695 case opc_checkcast: {
696 int indx = readIntArg(byteCodes, i);
697 final String type = jc.getClassName(indx);
698 if (!type.startsWith("[")) {
699 // no way to check arrays right now
700 out.append("if(stack[stack.length - 1].$instOf_")
701 .append(type.replace('/', '_'))
702 .append(" != 1) throw {};"); // XXX proper exception
707 case opc_instanceof: {
708 int indx = readIntArg(byteCodes, i);
709 final String type = jc.getClassName(indx);
710 out.append("stack.push(stack.pop().$instOf_")
711 .append(type.replace('/', '_'))
712 .append(" ? 1 : 0);");
717 out.append("{ var t = stack.pop(); stack = new Array(1); stack[0] = t; throw t; }");
721 out.append("throw 'unknown bytecode " + c + "';");
726 for (int j = prev; j <= i; j++) {
728 final int cc = readByte(byteCodes, j);
729 out.append(Integer.toString(cc));
736 private int generateIf(byte[] byteCodes, int i, final String test) throws IOException {
737 int indx = i + readIntArg(byteCodes, i);
738 out.append("if (stack.pop() ").append(test).append(" stack.pop()) { gt = " + indx);
739 out.append("; continue; }");
743 private int readIntArg(byte[] byteCodes, int offsetInstruction) {
744 final int indxHi = byteCodes[offsetInstruction + 1] << 8;
745 final int indxLo = byteCodes[offsetInstruction + 2];
746 return (indxHi & 0xffffff00) | (indxLo & 0xff);
748 private int readInt4(byte[] byteCodes, int offsetInstruction) {
749 final int d = byteCodes[offsetInstruction + 0] << 24;
750 final int c = byteCodes[offsetInstruction + 1] << 16;
751 final int b = byteCodes[offsetInstruction + 2] << 8;
752 final int a = byteCodes[offsetInstruction + 3];
753 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
755 private int readByte(byte[] byteCodes, int offsetInstruction) {
756 return (byteCodes[offsetInstruction] + 256) % 256;
759 private static void countArgs(String descriptor, boolean[] hasReturnType, StringBuilder sig, StringBuilder cnt) {
761 Boolean count = null;
762 boolean array = false;
763 int firstPos = sig.length();
764 while (i < descriptor.length()) {
765 char ch = descriptor.charAt(i++);
789 if (ch == 'J' || ch == 'D') {
795 hasReturnType[0] = true;
796 sig.insert(firstPos, ch);
798 sig.insert(firstPos, 'A');
805 hasReturnType[0] = false;
806 sig.insert(firstPos, 'V');
809 int next = descriptor.indexOf(';', i);
815 sig.append(descriptor.substring(i, next).replace('/', '_'));
818 sig.insert(firstPos, descriptor.substring(i, next).replace('/', '_'));
819 sig.insert(firstPos, ch);
821 sig.insert(firstPos, 'A');
823 hasReturnType[0] = true;
831 break; // invalid character
836 private void generateStaticField(FieldData v) throws IOException {
838 .append(className(jc))
839 .append('.').append(v.getName()).append(initField(v));
842 private String findMethodName(MethodData m, StringBuilder cnt) {
843 StringBuilder name = new StringBuilder();
844 if ("<init>".equals(m.getName())) { // NOI18N
845 name.append("cons"); // NOI18N
846 } else if ("<clinit>".equals(m.getName())) { // NOI18N
847 name.append("class"); // NOI18N
849 name.append(m.getName());
852 boolean hasReturn[] = { false };
853 countArgs(findDescriptor(m.getInternalSig()), hasReturn, name, cnt);
854 return name.toString();
857 private String findMethodName(String[] mi, StringBuilder cnt, boolean[] hasReturn) {
858 StringBuilder name = new StringBuilder();
859 String descr = mi[2];//mi.getDescriptor();
861 if ("<init>".equals(nm)) { // NOI18N
862 name.append("cons"); // NOI18N
866 countArgs(findDescriptor(descr), hasReturn, name, cnt);
867 return name.toString();
870 private int invokeStaticMethod(byte[] byteCodes, int i, boolean isStatic)
872 int methodIndex = readIntArg(byteCodes, i);
873 String[] mi = jc.getFieldInfoName(methodIndex);
874 boolean[] hasReturn = { false };
875 StringBuilder cnt = new StringBuilder();
876 String mn = findMethodName(mi, cnt, hasReturn);
878 for (int j = cnt.length() - 1; j >= 0; j--) {
879 out.append("var v" + j).append(" = stack.pop(); ");
883 out.append("stack.push(");
885 final String in = mi[0];
886 out.append(in.replace('/', '_'));
887 out.append("(true).");
892 out.append("stack.pop()");
895 for (int j = 0; j < cnt.length(); j++) {
909 private int invokeVirtualMethod(byte[] byteCodes, int i)
911 int methodIndex = readIntArg(byteCodes, i);
912 String[] mi = jc.getFieldInfoName(methodIndex);
913 boolean[] hasReturn = { false };
914 StringBuilder cnt = new StringBuilder();
915 String mn = findMethodName(mi, cnt, hasReturn);
917 for (int j = cnt.length() - 1; j >= 0; j--) {
918 out.append("var v" + j).append(" = stack.pop(); ");
920 out.append("var self = stack.pop(); ");
922 out.append("stack.push(");
928 for (int j = 0; j < cnt.length(); j++) {
941 private void addReference(String cn) throws IOException {
942 if (requireReference(cn)) {
943 out.append(" /* needs ").append(cn).append(" */");
947 private void outType(String d, StringBuilder out) {
949 while (d.charAt(0) == '[') {
953 if (d.charAt(0) == 'L') {
954 assert d.charAt(d.length() - 1) == ';';
955 out.append(d.replace('/', '_').substring(0, d.length() - 1));
961 private String encodeConstant(int entryIndex) {
962 String s = jc.stringValue(entryIndex, true);
966 private String findDescriptor(String d) {
967 return d.replace('[', 'A');
970 private boolean javaScriptBody(String prefix, MethodData m, boolean isStatic) throws IOException {
971 byte[] arr = m.findAnnotationData(true);
975 final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
976 class P extends AnnotationParser {
978 String[] args = new String[30];
982 protected void visitAttr(String type, String attr, String value) {
983 if (type.equals(jvmType)) {
984 if ("body".equals(attr)) {
986 } else if ("args".equals(attr)) {
989 throw new IllegalArgumentException(attr);
996 if (p.body == null) {
999 StringBuilder cnt = new StringBuilder();
1000 out.append(prefix).append(findMethodName(m, cnt));
1001 out.append(" = function(");
1005 out.append(p.args[0]);
1012 for (int i = 0; i < cnt.length(); i++) {
1014 out.append(p.args[index]);
1018 out.append(") {").append("\n");
1020 out.append("\n}\n");
1023 private static String className(ClassData jc) {
1024 //return jc.getName().getInternalName().replace('/', '_');
1025 return jc.getClassName().replace('/', '_');
1028 private static String[] findAnnotation(
1029 byte[] arr, ClassData cd, final String className,
1030 final String... attrNames
1031 ) throws IOException {
1035 final String[] values = new String[attrNames.length];
1036 final boolean[] found = { false };
1037 final String jvmType = "L" + className.replace('.', '/') + ";";
1038 AnnotationParser ap = new AnnotationParser() {
1040 protected void visitAttr(String type, String attr, String value) {
1041 if (type.equals(jvmType)) {
1043 for (int i = 0; i < attrNames.length; i++) {
1044 if (attrNames[i].equals(attr)) {
1053 return found[0] ? values : null;
1056 private CharSequence initField(FieldData v) {
1057 final String is = v.getInternalSig();
1058 if (is.length() == 1) {
1059 switch (is.charAt(0)) {
1065 case 'I': return " = 0;";
1067 case 'D': return " = 0.0;";
1069 throw new IllegalStateException(is);