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.ExtraJavaScript;
23 import org.apidesign.bck2brwsr.core.JavaScriptBody;
24 import org.apidesign.javap.AnnotationParser;
25 import org.apidesign.javap.ClassData;
26 import org.apidesign.javap.FieldData;
27 import org.apidesign.javap.MethodData;
28 import static org.apidesign.javap.RuntimeConstants.*;
30 /** Translator of the code inside class files to JavaScript.
32 * @author Jaroslav Tulach <jtulach@netbeans.org>
34 public abstract class ByteCodeToJavaScript {
36 private final Appendable out;
38 protected ByteCodeToJavaScript(Appendable out) {
42 /* Collects additional required resources.
44 * @param internalClassName classes that were referenced and should be loaded in order the
45 * generated JavaScript code works properly. The names are in internal
46 * JVM form so String is <code>java/lang/String</code>.
48 protected abstract boolean requireReference(String internalClassName);
51 * @param resourcePath name of resources to read
53 protected abstract void requireScript(String resourcePath);
56 * Converts a given class file to a JavaScript version.
58 * @param classFile input stream with code of the .class file
59 * @return the initialization code for this class, if any. Otherwise <code>null</code>
61 * @throws IOException if something goes wrong during read or write or translating
64 public String compile(InputStream classFile) throws IOException {
65 this.jc = new ClassData(classFile);
66 byte[] arrData = jc.findAnnotationData(true);
67 String[] arr = findAnnotation(arrData, jc, ExtraJavaScript.class.getName(), "resource", "processByteCode");
69 requireScript(arr[0]);
70 if ("0".equals(arr[1])) {
74 StringArray toInitilize = new StringArray();
75 for (MethodData m : jc.getMethods()) {
77 generateStaticMethod(m, toInitilize);
79 generateInstanceMethod(m);
82 for (FieldData v : jc.getFields()) {
84 generateStaticField(v);
88 final String className = className(jc);
89 out.append("\nfunction ").append(className);
91 for (FieldData v : jc.getFields()) {
93 out.append("\n this.fld_").
94 append(v.getName()).append(" = 0;");
97 out.append("\n}\n\nfunction ").append(className).append("_proto() {");
98 out.append("\n if (").append(className).
99 append(".prototype.$instOf_").append(className).append(") {");
100 out.append("\n return new ").append(className).append(";");
102 // ClassName sc = jc.getSuperClass();
103 String sc = jc.getSuperClassName(); // with _
105 out.append("\n var p = ").append(className)
106 .append(".prototype = ").
107 append(sc.replace('/', '_')).append("_proto();");
109 out.append("\n var p = ").append(className).append(".prototype;");
111 for (MethodData m : jc.getMethods()) {
112 if (!m.getName().contains("<init>") && !m.getName().contains("<cinit>")) {
113 generateMethodReference("\n p.", m);
116 out.append("\n p.$instOf_").append(className).append(" = true;");
117 for (String superInterface : jc.getSuperInterfaces()) {
118 out.append("\n p.$instOf_").append(superInterface.replace('/', '_')).append(" = true;");
120 out.append("\n return new ").append(className).append(";");
122 out.append("\n").append(className).append("_proto();");
123 StringBuilder sb = new StringBuilder();
124 for (String init : toInitilize.toArray()) {
125 sb.append("\n").append(init).append("();");
127 return sb.toString();
129 private void generateStaticMethod(MethodData m, StringArray toInitilize) throws IOException {
130 if (javaScriptBody(m, true)) {
133 StringBuilder argsCnt = new StringBuilder();
134 final String mn = findMethodName(m, argsCnt);
135 out.append("\nfunction ").append(
137 ).append('_').append(mn);
138 if (mn.equals("classV")) {
139 toInitilize.add(className(jc) + '_' + mn);
143 for (int index = 0, i = 0; i < argsCnt.length(); i++) {
145 out.append("arg").append(String.valueOf(index));
147 final String desc = null;// XXX findDescriptor(args.get(i).getDescriptor());
148 if (argsCnt.charAt(i) == '1') {
154 out.append(") {").append("\n");
155 final byte[] code = m.getCode();
157 int len = m.getMaxLocals();
158 for (int index = argsCnt.length(), i = argsCnt.length(); i < len; i++) {
160 out.append("arg").append(String.valueOf(i)).append(";\n");
162 out.append(" var stack = new Array();\n");
165 out.append(" /* no code found for ").append(m.getInternalSig()).append(" */\n");
170 private void generateMethodReference(String prefix, MethodData m) throws IOException {
171 final String name = findMethodName(m, new StringBuilder());
172 out.append(prefix).append(name).append(" = ")
173 .append(className(jc))
174 .append('_').append(name).append(";");
177 private void generateInstanceMethod(MethodData m) throws IOException {
178 if (javaScriptBody(m, false)) {
181 StringBuilder argsCnt = new StringBuilder();
182 out.append("\nfunction ").append(
184 ).append('_').append(findMethodName(m, argsCnt));
187 for (int index = 1, i = 0; i < argsCnt.length(); i++) {
189 out.append("arg").append(String.valueOf(index));
190 if (argsCnt.charAt(i) == '1') {
196 out.append(") {").append("\n");
197 final byte[] code = m.getCode();
199 int len = m.getMaxLocals();
200 for (int index = argsCnt.length(), i = argsCnt.length(); i < len; i++) {
202 out.append("arg").append(String.valueOf(i + 1)).append(";\n");
204 out.append(";\n var stack = new Array();\n");
207 out.append(" /* no code found for ").append(m.getInternalSig()).append(" */\n");
212 private void produceCode(byte[] byteCodes) throws IOException {
213 out.append("\n var gt = 0;\n for(;;) switch(gt) {\n");
214 for (int i = 0; i < byteCodes.length; i++) {
216 out.append(" case " + i).append(": ");
217 final int c = readByte(byteCodes, i);
224 out.append("stack.push(arg0);");
231 out.append("stack.push(arg1);");
238 out.append("stack.push(arg2);");
245 out.append("stack.push(arg3);");
252 final int indx = readByte(byteCodes, ++i);
253 out.append("stack.push(arg").append(indx + ");");
261 final int indx = readByte(byteCodes, ++i);
262 out.append("arg" + indx).append(" = stack.pop();");
270 out.append("arg0 = stack.pop();");
277 out.append("arg1 = stack.pop();");
284 out.append("arg2 = stack.pop();");
291 out.append("arg3 = stack.pop();");
297 out.append("stack.push(stack.pop() + stack.pop());");
303 out.append("{ var tmp = stack.pop(); stack.push(stack.pop() - tmp); }");
309 out.append("stack.push(stack.pop() * stack.pop());");
313 out.append("{ var tmp = stack.pop(); stack.push(Math.floor(stack.pop() / tmp)); }");
317 out.append("{ var tmp = stack.pop(); stack.push(stack.pop() / tmp); }");
321 out.append("stack.push(stack.pop() & stack.pop());");
325 out.append("stack.push(stack.pop() | stack.pop());");
329 out.append("stack.push(stack.pop() ^ stack.pop());");
335 out.append("stack.push(- stack.pop());");
339 out.append("{ var v = stack.pop(); stack.push(stack.pop() << v); }");
343 out.append("{ var v = stack.pop(); stack.push(stack.pop() >> v); }");
347 out.append("{ var v = stack.pop(); stack.push(stack.pop() >>> v); }");
350 final int varIndx = readByte(byteCodes, ++i);
351 final int incrBy = byteCodes[++i];
353 out.append("arg" + varIndx).append("++;");
355 out.append("arg" + varIndx).append(" += " + incrBy).append(";");
360 out.append("return;");
367 out.append("return stack.pop();");
378 out.append("/* number conversion */");
384 out.append("stack.push(Math.floor(stack.pop()));");
389 out.append("/* number conversion */");
391 case opc_aconst_null:
392 out.append("stack.push(null);");
395 out.append("stack.push(-1);");
401 out.append("stack.push(0);");
407 out.append("stack.push(1);");
411 out.append("stack.push(2);");
414 out.append("stack.push(3);");
417 out.append("stack.push(4);");
420 out.append("stack.push(5);");
423 int indx = readByte(byteCodes, ++i);
424 String v = encodeConstant(indx);
425 out.append("stack.push(").append(v).append(");");
430 int indx = readIntArg(byteCodes, i);
432 String v = encodeConstant(indx);
433 out.append("stack.push(").append(v).append(");");
441 out.append("{ var delta = stack.pop() - stack.pop(); stack.push(delta < 0 ?-1 : (delta == 0 ? 0 : 1)); }");
445 i = generateIf(byteCodes, i, "===");
448 i = generateIf(byteCodes, i, "!=");
450 case opc_if_icmpeq: {
451 i = generateIf(byteCodes, i, "==");
455 int indx = i + readIntArg(byteCodes, i);
456 out.append("if (stack.pop() == 0) { gt = " + indx);
457 out.append("; continue; }");
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; }");
496 case opc_ifnonnull: {
497 int indx = i + readIntArg(byteCodes, i);
498 out.append("if (stack.pop()) { gt = " + indx);
499 out.append("; continue; }");
504 int indx = i + readIntArg(byteCodes, i);
505 out.append("if (!stack.pop()) { gt = " + indx);
506 out.append("; continue; }");
511 i = generateIf(byteCodes, i, "!=");
514 i = generateIf(byteCodes, i, ">");
517 i = generateIf(byteCodes, i, ">=");
520 i = generateIf(byteCodes, i, "<");
523 i = generateIf(byteCodes, i, "<=");
526 int indx = i + readIntArg(byteCodes, i);
527 out.append("gt = " + indx).append("; continue;");
531 case opc_lookupswitch: {
532 int table = i / 4 * 4 + 4;
533 int dflt = i + readInt4(byteCodes, table);
535 int n = readInt4(byteCodes, table);
537 out.append("switch (stack.pop()) {\n");
539 int cnstnt = readInt4(byteCodes, table);
541 int offset = i + readInt4(byteCodes, table);
543 out.append(" case " + cnstnt).append(": gt = " + offset).append("; continue;\n");
545 out.append(" default: gt = " + dflt).append("; continue;\n}");
549 case opc_tableswitch: {
550 int table = i / 4 * 4 + 4;
551 int dflt = i + readInt4(byteCodes, table);
553 int low = readInt4(byteCodes, table);
555 int high = readInt4(byteCodes, table);
557 out.append("switch (stack.pop()) {\n");
558 while (low <= high) {
559 int offset = i + readInt4(byteCodes, table);
561 out.append(" case " + low).append(": gt = " + offset).append("; continue;\n");
564 out.append(" default: gt = " + dflt).append("; continue;\n}");
568 case opc_invokeinterface: {
569 i = invokeVirtualMethod(byteCodes, i) + 2;
572 case opc_invokevirtual:
573 i = invokeVirtualMethod(byteCodes, i);
575 case opc_invokespecial:
576 i = invokeStaticMethod(byteCodes, i, false);
578 case opc_invokestatic:
579 i = invokeStaticMethod(byteCodes, i, true);
582 int indx = readIntArg(byteCodes, i);
583 String ci = jc.getClassName(indx);
584 out.append("stack.push(");
585 out.append("new ").append(ci.replace('/','_'));
592 int type = byteCodes[i++];
593 out.append("stack.push(new Array(stack.pop()));");
596 case opc_anewarray: {
597 i += 2; // skip type of array
598 out.append("stack.push(new Array(stack.pop()));");
601 case opc_multianewarray: {
603 int dim = readByte(byteCodes, ++i);
604 out.append("{ var a0 = new Array(stack.pop());");
605 for (int d = 1; d < dim; d++) {
606 out.append("\n var l" + d).append(" = stack.pop();");
607 out.append("\n for (var i" + d).append (" = 0; i" + d).
608 append(" < a" + (d - 1)).
609 append(".length; i" + d).append("++) {");
610 out.append("\n var a" + d).
611 append (" = new Array(l" + d).append(");");
612 out.append("\n a" + (d - 1)).append("[i" + d).append("] = a" + d).
615 for (int d = 1; d < dim; d++) {
618 out.append("\nstack.push(a0); }");
621 case opc_arraylength:
622 out.append("stack.push(stack.pop().length);");
632 out.append("{ var value = stack.pop(); var indx = stack.pop(); stack.pop()[indx] = value; }");
643 out.append("{ var indx = stack.pop(); stack.push(stack.pop()[indx]); }");
647 out.append("stack.pop();");
649 out.append("stack.pop();");
652 out.append("stack.push(stack[stack.length - 1]);");
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(" = 0;");
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('/', '_'));
888 out.append(".prototype.");
896 out.append("stack.pop()");
899 for (int j = 0; j < cnt.length(); j++) {
913 private int invokeVirtualMethod(byte[] byteCodes, int i)
915 int methodIndex = readIntArg(byteCodes, i);
916 String[] mi = jc.getFieldInfoName(methodIndex);
917 boolean[] hasReturn = { false };
918 StringBuilder cnt = new StringBuilder();
919 String mn = findMethodName(mi, cnt, hasReturn);
921 for (int j = cnt.length() - 1; j >= 0; j--) {
922 out.append("var v" + j).append(" = stack.pop(); ");
924 out.append("var self = stack.pop(); ");
926 out.append("stack.push(");
932 for (int j = 0; j < cnt.length(); j++) {
945 private void addReference(String cn) throws IOException {
946 if (requireReference(cn)) {
947 out.append(" /* needs ").append(cn).append(" */");
951 private void outType(String d, StringBuilder out) {
953 while (d.charAt(0) == '[') {
957 if (d.charAt(0) == 'L') {
958 assert d.charAt(d.length() - 1) == ';';
959 out.append(d.replace('/', '_').substring(0, d.length() - 1));
965 private String encodeConstant(int entryIndex) {
966 String s = jc.stringValue(entryIndex, true);
970 private String findDescriptor(String d) {
971 return d.replace('[', 'A');
974 private boolean javaScriptBody(MethodData m, boolean isStatic) throws IOException {
975 byte[] arr = m.findAnnotationData(true);
979 final String jvmType = "L" + JavaScriptBody.class.getName().replace('.', '/') + ";";
980 class P extends AnnotationParser {
982 String[] args = new String[30];
986 protected void visitAttr(String type, String attr, String value) {
987 if (type.equals(jvmType)) {
988 if ("body".equals(attr)) {
990 } else if ("args".equals(attr)) {
993 throw new IllegalArgumentException(attr);
1000 if (p.body == null) {
1003 StringBuilder cnt = new StringBuilder();
1004 out.append("\nfunction ").append(className(jc)).append('_').
1005 append(findMethodName(m, cnt));
1010 out.append(p.args[0]);
1017 for (int i = 0; i < cnt.length(); i++) {
1019 out.append(p.args[index]);
1023 out.append(") {").append("\n");
1025 out.append("\n}\n");
1028 private static String className(ClassData jc) {
1029 //return jc.getName().getInternalName().replace('/', '_');
1030 return jc.getClassName().replace('/', '_');
1033 private static String[] findAnnotation(
1034 byte[] arr, ClassData cd, final String className,
1035 final String... attrNames
1036 ) throws IOException {
1040 final String[] values = new String[attrNames.length];
1041 final boolean[] found = { false };
1042 final String jvmType = "L" + className.replace('.', '/') + ";";
1043 AnnotationParser ap = new AnnotationParser() {
1045 protected void visitAttr(String type, String attr, String value) {
1046 if (type.equals(jvmType)) {
1048 for (int i = 0; i < attrNames.length; i++) {
1049 if (attrNames[i].equals(attr)) {
1058 return found[0] ? values : null;