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;");
123 out.append("\n if (arguments.length === 0) {");
124 out.append("\n if (!(this instanceof CLS)) {");
125 out.append("\n return new CLS();");
127 for (FieldData v : jc.getFields()) {
129 out.append("\n this.fld_").
130 append(v.getName()).append(initField(v));
133 out.append("\n return this;");
135 out.append("\n return arguments[0] ? new CLS() : CLS.prototype;");
137 StringBuilder sb = new StringBuilder();
138 for (String init : toInitilize.toArray()) {
139 sb.append("\n").append(init).append("();");
141 return sb.toString();
143 private void generateStaticMethod(String prefix, MethodData m, StringArray toInitilize) throws IOException {
144 if (javaScriptBody(prefix, m, true)) {
147 StringBuilder argsCnt = new StringBuilder();
148 final String mn = findMethodName(m, argsCnt);
149 out.append(prefix).append(mn).append(" = function");
150 if (mn.equals("classV")) {
151 toInitilize.add(className(jc) + "(false)." + mn);
155 for (int index = 0, i = 0; i < argsCnt.length(); i++) {
157 out.append("arg").append(String.valueOf(index));
159 final String desc = null;// XXX findDescriptor(args.get(i).getDescriptor());
160 if (argsCnt.charAt(i) == '1') {
166 out.append(") {").append("\n");
167 final byte[] code = m.getCode();
169 int len = m.getMaxLocals();
170 for (int index = argsCnt.length(), i = argsCnt.length(); i < len; i++) {
172 out.append("arg").append(String.valueOf(i)).append(";\n");
174 out.append(" var s = new Array();\n");
177 out.append(" /* no code found for ").append(m.getInternalSig()).append(" */\n");
182 private void generateInstanceMethod(String prefix, MethodData m) throws IOException {
183 if (javaScriptBody(prefix, m, false)) {
186 StringBuilder argsCnt = new StringBuilder();
187 final String mn = findMethodName(m, argsCnt);
188 out.append(prefix).append(mn).append(" = function");
191 for (int index = 1, i = 0; i < argsCnt.length(); i++) {
193 out.append("arg").append(String.valueOf(index));
194 if (argsCnt.charAt(i) == '1') {
200 out.append(") {").append("\n");
201 final byte[] code = m.getCode();
203 int len = m.getMaxLocals();
204 for (int index = argsCnt.length(), i = argsCnt.length(); i < len; i++) {
206 out.append("arg").append(String.valueOf(i + 1)).append(";\n");
208 out.append(";\n var s = new Array();\n");
211 out.append(" /* no code found for ").append(m.getInternalSig()).append(" */\n");
216 private void produceCode(byte[] byteCodes) throws IOException {
217 out.append("\n var gt = 0;\n for(;;) switch(gt) {\n");
218 for (int i = 0; i < byteCodes.length; i++) {
220 out.append(" case " + i).append(": ");
221 final int c = readByte(byteCodes, i);
228 out.append("s.push(arg0);");
235 out.append("s.push(arg1);");
242 out.append("s.push(arg2);");
249 out.append("s.push(arg3);");
256 final int indx = readByte(byteCodes, ++i);
257 out.append("s.push(arg").append(indx + ");");
265 final int indx = readByte(byteCodes, ++i);
266 out.append("arg" + indx).append(" = s.pop();");
274 out.append("arg0 = s.pop();");
281 out.append("arg1 = s.pop();");
288 out.append("arg2 = s.pop();");
295 out.append("arg3 = s.pop();");
301 out.append("s.push(s.pop() + s.pop());");
307 out.append("{ var tmp = s.pop(); s.push(s.pop() - tmp); }");
313 out.append("s.push(s.pop() * s.pop());");
317 out.append("{ var tmp = s.pop(); s.push(Math.floor(s.pop() / tmp)); }");
321 out.append("{ var tmp = s.pop(); s.push(s.pop() / tmp); }");
327 out.append("{ var d = s.pop(); s.push(s.pop() % d); }");
331 out.append("s.push(s.pop() & s.pop());");
335 out.append("s.push(s.pop() | s.pop());");
339 out.append("s.push(s.pop() ^ s.pop());");
345 out.append("s.push(- s.pop());");
349 out.append("{ var v = s.pop(); s.push(s.pop() << v); }");
353 out.append("{ var v = s.pop(); s.push(s.pop() >> v); }");
357 out.append("{ var v = s.pop(); s.push(s.pop() >>> v); }");
360 final int varIndx = readByte(byteCodes, ++i);
361 final int incrBy = byteCodes[++i];
363 out.append("arg" + varIndx).append("++;");
365 out.append("arg" + varIndx).append(" += " + incrBy).append(";");
370 out.append("return;");
377 out.append("return s.pop();");
388 out.append("/* number conversion */");
394 out.append("s.push(Math.floor(s.pop()));");
399 out.append("/* number conversion */");
401 case opc_aconst_null:
402 out.append("s.push(null);");
405 out.append("s.push(-1);");
411 out.append("s.push(0);");
417 out.append("s.push(1);");
421 out.append("s.push(2);");
424 out.append("s.push(3);");
427 out.append("s.push(4);");
430 out.append("s.push(5);");
433 int indx = readByte(byteCodes, ++i);
434 String v = encodeConstant(indx);
435 out.append("s.push(").append(v).append(");");
440 int indx = readIntArg(byteCodes, i);
442 String v = encodeConstant(indx);
443 out.append("s.push(").append(v).append(");");
451 out.append("{ var delta = s.pop() - s.pop(); s.push(delta < 0 ?-1 : (delta == 0 ? 0 : 1)); }");
455 i = generateIf(byteCodes, i, "===");
458 i = generateIf(byteCodes, i, "!=");
460 case opc_if_icmpeq: {
461 i = generateIf(byteCodes, i, "==");
465 int indx = i + readIntArg(byteCodes, i);
466 out.append("if (s.pop() == 0) { gt = " + indx);
467 out.append("; continue; }");
472 int indx = i + readIntArg(byteCodes, i);
473 out.append("if (s.pop() != 0) { gt = " + indx);
474 out.append("; continue; }");
479 int indx = i + readIntArg(byteCodes, i);
480 out.append("if (s.pop() < 0) { gt = " + indx);
481 out.append("; continue; }");
486 int indx = i + readIntArg(byteCodes, i);
487 out.append("if (s.pop() <= 0) { gt = " + indx);
488 out.append("; continue; }");
493 int indx = i + readIntArg(byteCodes, i);
494 out.append("if (s.pop() > 0) { gt = " + indx);
495 out.append("; continue; }");
500 int indx = i + readIntArg(byteCodes, i);
501 out.append("if (s.pop() >= 0) { gt = " + indx);
502 out.append("; continue; }");
506 case opc_ifnonnull: {
507 int indx = i + readIntArg(byteCodes, i);
508 out.append("if (s.pop() !== null) { gt = " + indx);
509 out.append("; continue; }");
514 int indx = i + readIntArg(byteCodes, i);
515 out.append("if (s.pop() === null) { gt = " + indx);
516 out.append("; continue; }");
521 i = generateIf(byteCodes, i, "!=");
524 i = generateIf(byteCodes, i, ">");
527 i = generateIf(byteCodes, i, ">=");
530 i = generateIf(byteCodes, i, "<");
533 i = generateIf(byteCodes, i, "<=");
536 int indx = i + readIntArg(byteCodes, i);
537 out.append("gt = " + indx).append("; continue;");
541 case opc_lookupswitch: {
542 int table = i / 4 * 4 + 4;
543 int dflt = i + readInt4(byteCodes, table);
545 int n = readInt4(byteCodes, table);
547 out.append("switch (s.pop()) {\n");
549 int cnstnt = readInt4(byteCodes, table);
551 int offset = i + readInt4(byteCodes, table);
553 out.append(" case " + cnstnt).append(": gt = " + offset).append("; continue;\n");
555 out.append(" default: gt = " + dflt).append("; continue;\n}");
559 case opc_tableswitch: {
560 int table = i / 4 * 4 + 4;
561 int dflt = i + readInt4(byteCodes, table);
563 int low = readInt4(byteCodes, table);
565 int high = readInt4(byteCodes, table);
567 out.append("switch (s.pop()) {\n");
568 while (low <= high) {
569 int offset = i + readInt4(byteCodes, table);
571 out.append(" case " + low).append(": gt = " + offset).append("; continue;\n");
574 out.append(" default: gt = " + dflt).append("; continue;\n}");
578 case opc_invokeinterface: {
579 i = invokeVirtualMethod(byteCodes, i) + 2;
582 case opc_invokevirtual:
583 i = invokeVirtualMethod(byteCodes, i);
585 case opc_invokespecial:
586 i = invokeStaticMethod(byteCodes, i, false);
588 case opc_invokestatic:
589 i = invokeStaticMethod(byteCodes, i, true);
592 int indx = readIntArg(byteCodes, i);
593 String ci = jc.getClassName(indx);
594 out.append("s.push(new ");
595 out.append(ci.replace('/','_'));
602 int type = byteCodes[i++];
603 out.append("s.push(new Array(s.pop()).fillNulls());");
606 case opc_anewarray: {
607 i += 2; // skip type of array
608 out.append("s.push(new Array(s.pop()).fillNulls());");
611 case opc_multianewarray: {
613 int dim = readByte(byteCodes, ++i);
614 out.append("{ var a0 = new Array(s.pop()).fillNulls();");
615 for (int d = 1; d < dim; d++) {
616 out.append("\n var l" + d).append(" = s.pop();");
617 out.append("\n for (var i" + d).append (" = 0; i" + d).
618 append(" < a" + (d - 1)).
619 append(".length; i" + d).append("++) {");
620 out.append("\n var a" + d).
621 append (" = new Array(l" + d).append(").fillNulls();");
622 out.append("\n a" + (d - 1)).append("[i" + d).append("] = a" + d).
625 for (int d = 1; d < dim; d++) {
628 out.append("\ns.push(a0); }");
631 case opc_arraylength:
632 out.append("s.push(s.pop().length);");
642 out.append("{ var value = s.pop(); var indx = s.pop(); s.pop()[indx] = value; }");
653 out.append("{ var indx = s.pop(); s.push(s.pop()[indx]); }");
657 out.append("s.pop();");
659 out.append("s.pop();");
662 out.append("s.push(s[s.length - 1]);");
665 out.append("{ var v1 = s.pop(); var v2 = s.pop(); s.push(v1); s.push(v2); s.push(v1); }");
668 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); }");
671 out.append("s.push(" + byteCodes[++i] + ");");
674 out.append("s.push(" + readIntArg(byteCodes, i) + ");");
678 int indx = readIntArg(byteCodes, i);
679 String[] fi = jc.getFieldInfoName(indx);
680 out.append("s.push(s.pop().fld_").
681 append(fi[1]).append(");");
685 case opc_getstatic: {
686 int indx = readIntArg(byteCodes, i);
687 String[] fi = jc.getFieldInfoName(indx);
688 out.append("s.push(").append(fi[0].replace('/', '_'));
689 out.append('.').append(fi[1]).append(");");
694 case opc_putstatic: {
695 int indx = readIntArg(byteCodes, i);
696 String[] fi = jc.getFieldInfoName(indx);
697 out.append(fi[0].replace('/', '_'));
698 out.append('.').append(fi[1]).append(" = s.pop();");
704 int indx = readIntArg(byteCodes, i);
705 String[] fi = jc.getFieldInfoName(indx);
706 out.append("{ var v = s.pop(); s.pop().fld_")
707 .append(fi[1]).append(" = v; }");
711 case opc_checkcast: {
712 int indx = readIntArg(byteCodes, i);
713 final String type = jc.getClassName(indx);
714 if (!type.startsWith("[")) {
715 // no way to check arrays right now
716 out.append("if(s[s.length - 1].$instOf_")
717 .append(type.replace('/', '_'))
718 .append(" != 1) throw {};"); // XXX proper exception
723 case opc_instanceof: {
724 int indx = readIntArg(byteCodes, i);
725 final String type = jc.getClassName(indx);
726 out.append("s.push(s.pop().$instOf_")
727 .append(type.replace('/', '_'))
728 .append(" ? 1 : 0);");
733 out.append("{ var t = s.pop(); s = new Array(1); s[0] = t; throw t; }");
737 out.append("throw 'unknown bytecode " + c + "';");
742 for (int j = prev; j <= i; j++) {
744 final int cc = readByte(byteCodes, j);
745 out.append(Integer.toString(cc));
752 private int generateIf(byte[] byteCodes, int i, final String test) throws IOException {
753 int indx = i + readIntArg(byteCodes, i);
754 out.append("if (s.pop() ").append(test).append(" s.pop()) { gt = " + indx);
755 out.append("; continue; }");
759 private int readIntArg(byte[] byteCodes, int offsetInstruction) {
760 final int indxHi = byteCodes[offsetInstruction + 1] << 8;
761 final int indxLo = byteCodes[offsetInstruction + 2];
762 return (indxHi & 0xffffff00) | (indxLo & 0xff);
764 private int readInt4(byte[] byteCodes, int offsetInstruction) {
765 final int d = byteCodes[offsetInstruction + 0] << 24;
766 final int c = byteCodes[offsetInstruction + 1] << 16;
767 final int b = byteCodes[offsetInstruction + 2] << 8;
768 final int a = byteCodes[offsetInstruction + 3];
769 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
771 private int readByte(byte[] byteCodes, int offsetInstruction) {
772 return (byteCodes[offsetInstruction] + 256) % 256;
775 private static void countArgs(String descriptor, boolean[] hasReturnType, StringBuilder sig, StringBuilder cnt) {
777 Boolean count = null;
778 boolean array = false;
779 int firstPos = sig.length();
780 while (i < descriptor.length()) {
781 char ch = descriptor.charAt(i++);
805 if (ch == 'J' || ch == 'D') {
811 hasReturnType[0] = true;
812 sig.insert(firstPos, ch);
814 sig.insert(firstPos, 'A');
821 hasReturnType[0] = false;
822 sig.insert(firstPos, 'V');
825 int next = descriptor.indexOf(';', i);
831 sig.append(descriptor.substring(i, next).replace('/', '_'));
834 sig.insert(firstPos, descriptor.substring(i, next).replace('/', '_'));
835 sig.insert(firstPos, ch);
837 sig.insert(firstPos, 'A');
839 hasReturnType[0] = true;
847 break; // invalid character
852 private String findMethodName(MethodData m, StringBuilder cnt) {
853 StringBuilder name = new StringBuilder();
854 if ("<init>".equals(m.getName())) { // NOI18N
855 name.append("cons"); // NOI18N
856 } else if ("<clinit>".equals(m.getName())) { // NOI18N
857 name.append("class"); // NOI18N
859 name.append(m.getName());
862 boolean hasReturn[] = { false };
863 countArgs(findDescriptor(m.getInternalSig()), hasReturn, name, cnt);
864 return name.toString();
867 private String findMethodName(String[] mi, StringBuilder cnt, boolean[] hasReturn) {
868 StringBuilder name = new StringBuilder();
869 String descr = mi[2];//mi.getDescriptor();
871 if ("<init>".equals(nm)) { // NOI18N
872 name.append("cons"); // NOI18N
876 countArgs(findDescriptor(descr), hasReturn, name, cnt);
877 return name.toString();
880 private int invokeStaticMethod(byte[] byteCodes, int i, boolean isStatic)
882 int methodIndex = readIntArg(byteCodes, i);
883 String[] mi = jc.getFieldInfoName(methodIndex);
884 boolean[] hasReturn = { false };
885 StringBuilder cnt = new StringBuilder();
886 String mn = findMethodName(mi, cnt, hasReturn);
888 for (int j = cnt.length() - 1; j >= 0; j--) {
889 out.append("var v" + j).append(" = s.pop(); ");
893 out.append("s.push(");
895 final String in = mi[0];
896 out.append(in.replace('/', '_'));
897 out.append("(false).");
902 out.append("s.pop()");
905 for (int j = 0; j < cnt.length(); j++) {
919 private int invokeVirtualMethod(byte[] byteCodes, int i)
921 int methodIndex = readIntArg(byteCodes, i);
922 String[] mi = jc.getFieldInfoName(methodIndex);
923 boolean[] hasReturn = { false };
924 StringBuilder cnt = new StringBuilder();
925 String mn = findMethodName(mi, cnt, hasReturn);
927 for (int j = cnt.length() - 1; j >= 0; j--) {
928 out.append("var v" + j).append(" = s.pop(); ");
930 out.append("var self = s.pop(); ");
932 out.append("s.push(");
938 for (int j = 0; j < cnt.length(); j++) {
951 private void addReference(String cn) throws IOException {
952 if (requireReference(cn)) {
953 out.append(" /* needs ").append(cn).append(" */");
957 private void outType(String d, StringBuilder out) {
959 while (d.charAt(0) == '[') {
963 if (d.charAt(0) == 'L') {
964 assert d.charAt(d.length() - 1) == ';';
965 out.append(d.replace('/', '_').substring(0, d.length() - 1));
971 private String encodeConstant(int entryIndex) throws IOException {
972 String[] classRef = { null };
973 String s = jc.stringValue(entryIndex, classRef);
974 if (classRef[0] != null) {
975 addReference(classRef[0]);
980 private String findDescriptor(String d) {
981 return d.replace('[', 'A');
984 private boolean javaScriptBody(String prefix, MethodData m, boolean isStatic) throws IOException {
985 byte[] arr = m.findAnnotationData(true);
989 final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
990 class P extends AnnotationParser {
992 String[] args = new String[30];
996 protected void visitAttr(String type, String attr, String value) {
997 if (type.equals(jvmType)) {
998 if ("body".equals(attr)) {
1000 } else if ("args".equals(attr)) {
1001 args[cnt++] = value;
1003 throw new IllegalArgumentException(attr);
1010 if (p.body == null) {
1013 StringBuilder cnt = new StringBuilder();
1014 out.append(prefix).append(findMethodName(m, cnt));
1015 out.append(" = function(");
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);