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 p = CLS.prototype = ").
99 append(sc.replace('/', '_')).append("(true);");
101 out.append("\n var p = CLS.prototype;");
103 for (MethodData m : jc.getMethods()) {
105 generateStaticMethod("\n p.", m, toInitilize);
107 generateInstanceMethod("\n p.", m);
110 out.append("\n p.$instOf_").append(className).append(" = true;");
111 for (String superInterface : jc.getSuperInterfaces()) {
112 out.append("\n p.$instOf_").append(superInterface.replace('/', '_')).append(" = true;");
114 out.append("\n CLS.$class = java_lang_Class(true);");
115 out.append("\n CLS.$class.jvmName = '").append(jc.getClassName()).append("';");
116 out.append("\n if (arguments.length === 0) {");
117 out.append("\n return new CLS();");
120 out.append("\n if (arguments.length === 0) {");
121 for (FieldData v : jc.getFields()) {
123 out.append("\n this.fld_").
124 append(v.getName()).append(initField(v));
127 out.append("\n return this;");
129 out.append("\n return new CLS;");
131 StringBuilder sb = new StringBuilder();
132 for (String init : toInitilize.toArray()) {
133 sb.append("\n").append(init).append("();");
135 return sb.toString();
137 private void generateStaticMethod(String prefix, MethodData m, StringArray toInitilize) throws IOException {
138 if (javaScriptBody(prefix, m, true)) {
141 StringBuilder argsCnt = new StringBuilder();
142 final String mn = findMethodName(m, argsCnt);
143 out.append(prefix).append(mn).append(" = function");
144 if (mn.equals("classV")) {
145 toInitilize.add(className(jc) + "(true)." + mn);
149 for (int index = 0, i = 0; i < argsCnt.length(); i++) {
151 out.append("arg").append(String.valueOf(index));
153 final String desc = null;// XXX findDescriptor(args.get(i).getDescriptor());
154 if (argsCnt.charAt(i) == '1') {
160 out.append(") {").append("\n");
161 final byte[] code = m.getCode();
163 int len = m.getMaxLocals();
164 for (int index = argsCnt.length(), i = argsCnt.length(); i < len; i++) {
166 out.append("arg").append(String.valueOf(i)).append(";\n");
168 out.append(" var s = new Array();\n");
171 out.append(" /* no code found for ").append(m.getInternalSig()).append(" */\n");
176 private void generateInstanceMethod(String prefix, MethodData m) throws IOException {
177 if (javaScriptBody(prefix, m, false)) {
180 StringBuilder argsCnt = new StringBuilder();
181 final String mn = findMethodName(m, argsCnt);
182 out.append(prefix).append(mn).append(" = function");
185 for (int index = 1, i = 0; i < argsCnt.length(); i++) {
187 out.append("arg").append(String.valueOf(index));
188 if (argsCnt.charAt(i) == '1') {
194 out.append(") {").append("\n");
195 final byte[] code = m.getCode();
197 int len = m.getMaxLocals();
198 for (int index = argsCnt.length(), i = argsCnt.length(); i < len; i++) {
200 out.append("arg").append(String.valueOf(i + 1)).append(";\n");
202 out.append(";\n var s = new Array();\n");
205 out.append(" /* no code found for ").append(m.getInternalSig()).append(" */\n");
210 private void produceCode(byte[] byteCodes) throws IOException {
211 out.append("\n var gt = 0;\n for(;;) switch(gt) {\n");
212 for (int i = 0; i < byteCodes.length; i++) {
214 out.append(" case " + i).append(": ");
215 final int c = readByte(byteCodes, i);
222 out.append("s.push(arg0);");
229 out.append("s.push(arg1);");
236 out.append("s.push(arg2);");
243 out.append("s.push(arg3);");
250 final int indx = readByte(byteCodes, ++i);
251 out.append("s.push(arg").append(indx + ");");
259 final int indx = readByte(byteCodes, ++i);
260 out.append("arg" + indx).append(" = s.pop();");
268 out.append("arg0 = s.pop();");
275 out.append("arg1 = s.pop();");
282 out.append("arg2 = s.pop();");
289 out.append("arg3 = s.pop();");
295 out.append("s.push(s.pop() + s.pop());");
301 out.append("{ var tmp = s.pop(); s.push(s.pop() - tmp); }");
307 out.append("s.push(s.pop() * s.pop());");
311 out.append("{ var tmp = s.pop(); s.push(Math.floor(s.pop() / tmp)); }");
315 out.append("{ var tmp = s.pop(); s.push(s.pop() / tmp); }");
321 out.append("{ var d = s.pop(); s.push(s.pop() % d); }");
325 out.append("s.push(s.pop() & s.pop());");
329 out.append("s.push(s.pop() | s.pop());");
333 out.append("s.push(s.pop() ^ s.pop());");
339 out.append("s.push(- s.pop());");
343 out.append("{ var v = s.pop(); s.push(s.pop() << v); }");
347 out.append("{ var v = s.pop(); s.push(s.pop() >> v); }");
351 out.append("{ var v = s.pop(); s.push(s.pop() >>> v); }");
354 final int varIndx = readByte(byteCodes, ++i);
355 final int incrBy = byteCodes[++i];
357 out.append("arg" + varIndx).append("++;");
359 out.append("arg" + varIndx).append(" += " + incrBy).append(";");
364 out.append("return;");
371 out.append("return s.pop();");
382 out.append("/* number conversion */");
388 out.append("s.push(Math.floor(s.pop()));");
393 out.append("/* number conversion */");
395 case opc_aconst_null:
396 out.append("s.push(null);");
399 out.append("s.push(-1);");
405 out.append("s.push(0);");
411 out.append("s.push(1);");
415 out.append("s.push(2);");
418 out.append("s.push(3);");
421 out.append("s.push(4);");
424 out.append("s.push(5);");
427 int indx = readByte(byteCodes, ++i);
428 String v = encodeConstant(indx);
429 out.append("s.push(").append(v).append(");");
434 int indx = readIntArg(byteCodes, i);
436 String v = encodeConstant(indx);
437 out.append("s.push(").append(v).append(");");
445 out.append("{ var delta = s.pop() - s.pop(); s.push(delta < 0 ?-1 : (delta == 0 ? 0 : 1)); }");
449 i = generateIf(byteCodes, i, "===");
452 i = generateIf(byteCodes, i, "!=");
454 case opc_if_icmpeq: {
455 i = generateIf(byteCodes, i, "==");
459 int indx = i + readIntArg(byteCodes, i);
460 out.append("if (s.pop() == 0) { gt = " + indx);
461 out.append("; continue; }");
466 int indx = i + readIntArg(byteCodes, i);
467 out.append("if (s.pop() != 0) { gt = " + indx);
468 out.append("; continue; }");
473 int indx = i + readIntArg(byteCodes, i);
474 out.append("if (s.pop() < 0) { gt = " + indx);
475 out.append("; continue; }");
480 int indx = i + readIntArg(byteCodes, i);
481 out.append("if (s.pop() <= 0) { gt = " + indx);
482 out.append("; continue; }");
487 int indx = i + readIntArg(byteCodes, i);
488 out.append("if (s.pop() > 0) { gt = " + indx);
489 out.append("; continue; }");
494 int indx = i + readIntArg(byteCodes, i);
495 out.append("if (s.pop() >= 0) { gt = " + indx);
496 out.append("; continue; }");
500 case opc_ifnonnull: {
501 int indx = i + readIntArg(byteCodes, i);
502 out.append("if (s.pop() !== null) { gt = " + indx);
503 out.append("; continue; }");
508 int indx = i + readIntArg(byteCodes, i);
509 out.append("if (s.pop() === null) { gt = " + indx);
510 out.append("; continue; }");
515 i = generateIf(byteCodes, i, "!=");
518 i = generateIf(byteCodes, i, ">");
521 i = generateIf(byteCodes, i, ">=");
524 i = generateIf(byteCodes, i, "<");
527 i = generateIf(byteCodes, i, "<=");
530 int indx = i + readIntArg(byteCodes, i);
531 out.append("gt = " + indx).append("; continue;");
535 case opc_lookupswitch: {
536 int table = i / 4 * 4 + 4;
537 int dflt = i + readInt4(byteCodes, table);
539 int n = readInt4(byteCodes, table);
541 out.append("switch (s.pop()) {\n");
543 int cnstnt = readInt4(byteCodes, table);
545 int offset = i + readInt4(byteCodes, table);
547 out.append(" case " + cnstnt).append(": gt = " + offset).append("; continue;\n");
549 out.append(" default: gt = " + dflt).append("; continue;\n}");
553 case opc_tableswitch: {
554 int table = i / 4 * 4 + 4;
555 int dflt = i + readInt4(byteCodes, table);
557 int low = readInt4(byteCodes, table);
559 int high = readInt4(byteCodes, table);
561 out.append("switch (s.pop()) {\n");
562 while (low <= high) {
563 int offset = i + readInt4(byteCodes, table);
565 out.append(" case " + low).append(": gt = " + offset).append("; continue;\n");
568 out.append(" default: gt = " + dflt).append("; continue;\n}");
572 case opc_invokeinterface: {
573 i = invokeVirtualMethod(byteCodes, i) + 2;
576 case opc_invokevirtual:
577 i = invokeVirtualMethod(byteCodes, i);
579 case opc_invokespecial:
580 i = invokeStaticMethod(byteCodes, i, false);
582 case opc_invokestatic:
583 i = invokeStaticMethod(byteCodes, i, true);
586 int indx = readIntArg(byteCodes, i);
587 String ci = jc.getClassName(indx);
588 out.append("s.push(");
589 out.append("new ").append(ci.replace('/','_'));
596 int type = byteCodes[i++];
597 out.append("s.push(new Array(s.pop()).fillNulls());");
600 case opc_anewarray: {
601 i += 2; // skip type of array
602 out.append("s.push(new Array(s.pop()).fillNulls());");
605 case opc_multianewarray: {
607 int dim = readByte(byteCodes, ++i);
608 out.append("{ var a0 = new Array(s.pop()).fillNulls();");
609 for (int d = 1; d < dim; d++) {
610 out.append("\n var l" + d).append(" = s.pop();");
611 out.append("\n for (var i" + d).append (" = 0; i" + d).
612 append(" < a" + (d - 1)).
613 append(".length; i" + d).append("++) {");
614 out.append("\n var a" + d).
615 append (" = new Array(l" + d).append(").fillNulls();");
616 out.append("\n a" + (d - 1)).append("[i" + d).append("] = a" + d).
619 for (int d = 1; d < dim; d++) {
622 out.append("\ns.push(a0); }");
625 case opc_arraylength:
626 out.append("s.push(s.pop().length);");
636 out.append("{ var value = s.pop(); var indx = s.pop(); s.pop()[indx] = value; }");
647 out.append("{ var indx = s.pop(); s.push(s.pop()[indx]); }");
651 out.append("s.pop();");
653 out.append("s.pop();");
656 out.append("s.push(s[s.length - 1]);");
659 out.append("{ var v1 = s.pop(); var v2 = s.pop(); s.push(v1); s.push(v2); s.push(v1); }");
662 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); }");
665 out.append("s.push(" + byteCodes[++i] + ");");
668 out.append("s.push(" + readIntArg(byteCodes, i) + ");");
672 int indx = readIntArg(byteCodes, i);
673 String[] fi = jc.getFieldInfoName(indx);
674 out.append("s.push(s.pop().fld_").
675 append(fi[1]).append(");");
679 case opc_getstatic: {
680 int indx = readIntArg(byteCodes, i);
681 String[] fi = jc.getFieldInfoName(indx);
682 out.append("s.push(").append(fi[0].replace('/', '_'));
683 out.append('.').append(fi[1]).append(");");
688 case opc_putstatic: {
689 int indx = readIntArg(byteCodes, i);
690 String[] fi = jc.getFieldInfoName(indx);
691 out.append(fi[0].replace('/', '_'));
692 out.append('.').append(fi[1]).append(" = s.pop();");
698 int indx = readIntArg(byteCodes, i);
699 String[] fi = jc.getFieldInfoName(indx);
700 out.append("{ var v = s.pop(); s.pop().fld_")
701 .append(fi[1]).append(" = v; }");
705 case opc_checkcast: {
706 int indx = readIntArg(byteCodes, i);
707 final String type = jc.getClassName(indx);
708 if (!type.startsWith("[")) {
709 // no way to check arrays right now
710 out.append("if(s[s.length - 1].$instOf_")
711 .append(type.replace('/', '_'))
712 .append(" != 1) throw {};"); // XXX proper exception
717 case opc_instanceof: {
718 int indx = readIntArg(byteCodes, i);
719 final String type = jc.getClassName(indx);
720 out.append("s.push(s.pop().$instOf_")
721 .append(type.replace('/', '_'))
722 .append(" ? 1 : 0);");
727 out.append("{ var t = s.pop(); s = new Array(1); s[0] = t; throw t; }");
731 out.append("throw 'unknown bytecode " + c + "';");
736 for (int j = prev; j <= i; j++) {
738 final int cc = readByte(byteCodes, j);
739 out.append(Integer.toString(cc));
746 private int generateIf(byte[] byteCodes, int i, final String test) throws IOException {
747 int indx = i + readIntArg(byteCodes, i);
748 out.append("if (s.pop() ").append(test).append(" s.pop()) { gt = " + indx);
749 out.append("; continue; }");
753 private int readIntArg(byte[] byteCodes, int offsetInstruction) {
754 final int indxHi = byteCodes[offsetInstruction + 1] << 8;
755 final int indxLo = byteCodes[offsetInstruction + 2];
756 return (indxHi & 0xffffff00) | (indxLo & 0xff);
758 private int readInt4(byte[] byteCodes, int offsetInstruction) {
759 final int d = byteCodes[offsetInstruction + 0] << 24;
760 final int c = byteCodes[offsetInstruction + 1] << 16;
761 final int b = byteCodes[offsetInstruction + 2] << 8;
762 final int a = byteCodes[offsetInstruction + 3];
763 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
765 private int readByte(byte[] byteCodes, int offsetInstruction) {
766 return (byteCodes[offsetInstruction] + 256) % 256;
769 private static void countArgs(String descriptor, boolean[] hasReturnType, StringBuilder sig, StringBuilder cnt) {
771 Boolean count = null;
772 boolean array = false;
773 int firstPos = sig.length();
774 while (i < descriptor.length()) {
775 char ch = descriptor.charAt(i++);
799 if (ch == 'J' || ch == 'D') {
805 hasReturnType[0] = true;
806 sig.insert(firstPos, ch);
808 sig.insert(firstPos, 'A');
815 hasReturnType[0] = false;
816 sig.insert(firstPos, 'V');
819 int next = descriptor.indexOf(';', i);
825 sig.append(descriptor.substring(i, next).replace('/', '_'));
828 sig.insert(firstPos, descriptor.substring(i, next).replace('/', '_'));
829 sig.insert(firstPos, ch);
831 sig.insert(firstPos, 'A');
833 hasReturnType[0] = true;
841 break; // invalid character
846 private String findMethodName(MethodData m, StringBuilder cnt) {
847 StringBuilder name = new StringBuilder();
848 if ("<init>".equals(m.getName())) { // NOI18N
849 name.append("cons"); // NOI18N
850 } else if ("<clinit>".equals(m.getName())) { // NOI18N
851 name.append("class"); // NOI18N
853 name.append(m.getName());
856 boolean hasReturn[] = { false };
857 countArgs(findDescriptor(m.getInternalSig()), hasReturn, name, cnt);
858 return name.toString();
861 private String findMethodName(String[] mi, StringBuilder cnt, boolean[] hasReturn) {
862 StringBuilder name = new StringBuilder();
863 String descr = mi[2];//mi.getDescriptor();
865 if ("<init>".equals(nm)) { // NOI18N
866 name.append("cons"); // NOI18N
870 countArgs(findDescriptor(descr), hasReturn, name, cnt);
871 return name.toString();
874 private int invokeStaticMethod(byte[] byteCodes, int i, boolean isStatic)
876 int methodIndex = readIntArg(byteCodes, i);
877 String[] mi = jc.getFieldInfoName(methodIndex);
878 boolean[] hasReturn = { false };
879 StringBuilder cnt = new StringBuilder();
880 String mn = findMethodName(mi, cnt, hasReturn);
882 for (int j = cnt.length() - 1; j >= 0; j--) {
883 out.append("var v" + j).append(" = s.pop(); ");
887 out.append("s.push(");
889 final String in = mi[0];
890 out.append(in.replace('/', '_'));
891 out.append("(true).");
896 out.append("s.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(" = s.pop(); ");
924 out.append("var self = s.pop(); ");
926 out.append("s.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(String prefix, MethodData m, boolean isStatic) throws IOException {
975 byte[] arr = m.findAnnotationData(true);
979 final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
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(prefix).append(findMethodName(m, cnt));
1005 out.append(" = function(");
1009 out.append(p.args[0]);
1016 for (int i = 0; i < cnt.length(); i++) {
1018 out.append(p.args[index]);
1022 out.append(") {").append("\n");
1024 out.append("\n}\n");
1027 private static String className(ClassData jc) {
1028 //return jc.getName().getInternalName().replace('/', '_');
1029 return jc.getClassName().replace('/', '_');
1032 private static String[] findAnnotation(
1033 byte[] arr, ClassData cd, final String className,
1034 final String... attrNames
1035 ) throws IOException {
1039 final String[] values = new String[attrNames.length];
1040 final boolean[] found = { false };
1041 final String jvmType = "L" + className.replace('.', '/') + ";";
1042 AnnotationParser ap = new AnnotationParser() {
1044 protected void visitAttr(String type, String attr, String value) {
1045 if (type.equals(jvmType)) {
1047 for (int i = 0; i < attrNames.length; i++) {
1048 if (attrNames[i].equals(attr)) {
1057 return found[0] ? values : null;
1060 private CharSequence initField(FieldData v) {
1061 final String is = v.getInternalSig();
1062 if (is.length() == 1) {
1063 switch (is.charAt(0)) {
1069 case 'I': return " = 0;";
1071 case 'D': return " = 0.0;";
1073 throw new IllegalStateException(is);