Make sure the constructor property points to the real function that creates the object
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.constructor = CLS;");
111 out.append("\n p.$instOf_").append(className).append(" = true;");
112 for (String superInterface : jc.getSuperInterfaces()) {
113 out.append("\n p.$instOf_").append(superInterface.replace('/', '_')).append(" = true;");
116 out.append("\n if (arguments.length === 0) {");
117 out.append("\n if (!(this instanceof CLS)) {");
118 out.append("\n return new CLS();");
120 for (FieldData v : jc.getFields()) {
122 out.append("\n this.fld_").
123 append(v.getName()).append(initField(v));
126 out.append("\n return this;");
128 out.append("\n return arguments[0] ? new CLS() : CLS.prototype;");
130 StringBuilder sb = new StringBuilder();
131 for (String init : toInitilize.toArray()) {
132 sb.append("\n").append(init).append("();");
134 return sb.toString();
136 private void generateStaticMethod(String prefix, MethodData m, StringArray toInitilize) throws IOException {
137 if (javaScriptBody(prefix, m, true)) {
140 StringBuilder argsCnt = new StringBuilder();
141 final String mn = findMethodName(m, argsCnt);
142 out.append(prefix).append(mn).append(" = function");
143 if (mn.equals("classV")) {
144 toInitilize.add(className(jc) + "(false)." + mn);
148 for (int index = 0, i = 0; i < argsCnt.length(); i++) {
150 out.append("arg").append(String.valueOf(index));
152 final String desc = null;// XXX findDescriptor(args.get(i).getDescriptor());
153 if (argsCnt.charAt(i) == '1') {
159 out.append(") {").append("\n");
160 final byte[] code = m.getCode();
162 int len = m.getMaxLocals();
163 for (int index = argsCnt.length(), i = argsCnt.length(); i < len; i++) {
165 out.append("arg").append(String.valueOf(i)).append(";\n");
167 out.append(" var s = new Array();\n");
170 out.append(" /* no code found for ").append(m.getInternalSig()).append(" */\n");
175 private void generateInstanceMethod(String prefix, MethodData m) throws IOException {
176 if (javaScriptBody(prefix, m, false)) {
179 StringBuilder argsCnt = new StringBuilder();
180 final String mn = findMethodName(m, argsCnt);
181 out.append(prefix).append(mn).append(" = function");
184 for (int index = 1, i = 0; i < argsCnt.length(); i++) {
186 out.append("arg").append(String.valueOf(index));
187 if (argsCnt.charAt(i) == '1') {
193 out.append(") {").append("\n");
194 final byte[] code = m.getCode();
196 int len = m.getMaxLocals();
197 for (int index = argsCnt.length(), i = argsCnt.length(); i < len; i++) {
199 out.append("arg").append(String.valueOf(i + 1)).append(";\n");
201 out.append(";\n var s = new Array();\n");
204 out.append(" /* no code found for ").append(m.getInternalSig()).append(" */\n");
209 private void produceCode(byte[] byteCodes) throws IOException {
210 out.append("\n var gt = 0;\n for(;;) switch(gt) {\n");
211 for (int i = 0; i < byteCodes.length; i++) {
213 out.append(" case " + i).append(": ");
214 final int c = readByte(byteCodes, i);
221 out.append("s.push(arg0);");
228 out.append("s.push(arg1);");
235 out.append("s.push(arg2);");
242 out.append("s.push(arg3);");
249 final int indx = readByte(byteCodes, ++i);
250 out.append("s.push(arg").append(indx + ");");
258 final int indx = readByte(byteCodes, ++i);
259 out.append("arg" + indx).append(" = s.pop();");
267 out.append("arg0 = s.pop();");
274 out.append("arg1 = s.pop();");
281 out.append("arg2 = s.pop();");
288 out.append("arg3 = s.pop();");
294 out.append("s.push(s.pop() + s.pop());");
300 out.append("{ var tmp = s.pop(); s.push(s.pop() - tmp); }");
306 out.append("s.push(s.pop() * s.pop());");
310 out.append("{ var tmp = s.pop(); s.push(Math.floor(s.pop() / tmp)); }");
314 out.append("{ var tmp = s.pop(); s.push(s.pop() / tmp); }");
320 out.append("{ var d = s.pop(); s.push(s.pop() % d); }");
324 out.append("s.push(s.pop() & s.pop());");
328 out.append("s.push(s.pop() | s.pop());");
332 out.append("s.push(s.pop() ^ s.pop());");
338 out.append("s.push(- s.pop());");
342 out.append("{ var v = s.pop(); s.push(s.pop() << v); }");
346 out.append("{ var v = s.pop(); s.push(s.pop() >> v); }");
350 out.append("{ var v = s.pop(); s.push(s.pop() >>> v); }");
353 final int varIndx = readByte(byteCodes, ++i);
354 final int incrBy = byteCodes[++i];
356 out.append("arg" + varIndx).append("++;");
358 out.append("arg" + varIndx).append(" += " + incrBy).append(";");
363 out.append("return;");
370 out.append("return s.pop();");
381 out.append("/* number conversion */");
387 out.append("s.push(Math.floor(s.pop()));");
392 out.append("/* number conversion */");
394 case opc_aconst_null:
395 out.append("s.push(null);");
398 out.append("s.push(-1);");
404 out.append("s.push(0);");
410 out.append("s.push(1);");
414 out.append("s.push(2);");
417 out.append("s.push(3);");
420 out.append("s.push(4);");
423 out.append("s.push(5);");
426 int indx = readByte(byteCodes, ++i);
427 String v = encodeConstant(indx);
428 out.append("s.push(").append(v).append(");");
433 int indx = readIntArg(byteCodes, i);
435 String v = encodeConstant(indx);
436 out.append("s.push(").append(v).append(");");
444 out.append("{ var delta = s.pop() - s.pop(); s.push(delta < 0 ?-1 : (delta == 0 ? 0 : 1)); }");
448 i = generateIf(byteCodes, i, "===");
451 i = generateIf(byteCodes, i, "!=");
453 case opc_if_icmpeq: {
454 i = generateIf(byteCodes, i, "==");
458 int indx = i + readIntArg(byteCodes, i);
459 out.append("if (s.pop() == 0) { gt = " + indx);
460 out.append("; continue; }");
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; }");
499 case opc_ifnonnull: {
500 int indx = i + readIntArg(byteCodes, i);
501 out.append("if (s.pop() !== null) { gt = " + indx);
502 out.append("; continue; }");
507 int indx = i + readIntArg(byteCodes, i);
508 out.append("if (s.pop() === null) { gt = " + indx);
509 out.append("; continue; }");
514 i = generateIf(byteCodes, i, "!=");
517 i = generateIf(byteCodes, i, ">");
520 i = generateIf(byteCodes, i, ">=");
523 i = generateIf(byteCodes, i, "<");
526 i = generateIf(byteCodes, i, "<=");
529 int indx = i + readIntArg(byteCodes, i);
530 out.append("gt = " + indx).append("; continue;");
534 case opc_lookupswitch: {
535 int table = i / 4 * 4 + 4;
536 int dflt = i + readInt4(byteCodes, table);
538 int n = readInt4(byteCodes, table);
540 out.append("switch (s.pop()) {\n");
542 int cnstnt = readInt4(byteCodes, table);
544 int offset = i + readInt4(byteCodes, table);
546 out.append(" case " + cnstnt).append(": gt = " + offset).append("; continue;\n");
548 out.append(" default: gt = " + dflt).append("; continue;\n}");
552 case opc_tableswitch: {
553 int table = i / 4 * 4 + 4;
554 int dflt = i + readInt4(byteCodes, table);
556 int low = readInt4(byteCodes, table);
558 int high = readInt4(byteCodes, table);
560 out.append("switch (s.pop()) {\n");
561 while (low <= high) {
562 int offset = i + readInt4(byteCodes, table);
564 out.append(" case " + low).append(": gt = " + offset).append("; continue;\n");
567 out.append(" default: gt = " + dflt).append("; continue;\n}");
571 case opc_invokeinterface: {
572 i = invokeVirtualMethod(byteCodes, i) + 2;
575 case opc_invokevirtual:
576 i = invokeVirtualMethod(byteCodes, i);
578 case opc_invokespecial:
579 i = invokeStaticMethod(byteCodes, i, false);
581 case opc_invokestatic:
582 i = invokeStaticMethod(byteCodes, i, true);
585 int indx = readIntArg(byteCodes, i);
586 String ci = jc.getClassName(indx);
587 out.append("s.push(new ");
588 out.append(ci.replace('/','_'));
595 int type = byteCodes[i++];
596 out.append("s.push(new Array(s.pop()).fillNulls());");
599 case opc_anewarray: {
600 i += 2; // skip type of array
601 out.append("s.push(new Array(s.pop()).fillNulls());");
604 case opc_multianewarray: {
606 int dim = readByte(byteCodes, ++i);
607 out.append("{ var a0 = new Array(s.pop()).fillNulls();");
608 for (int d = 1; d < dim; d++) {
609 out.append("\n var l" + d).append(" = s.pop();");
610 out.append("\n for (var i" + d).append (" = 0; i" + d).
611 append(" < a" + (d - 1)).
612 append(".length; i" + d).append("++) {");
613 out.append("\n var a" + d).
614 append (" = new Array(l" + d).append(").fillNulls();");
615 out.append("\n a" + (d - 1)).append("[i" + d).append("] = a" + d).
618 for (int d = 1; d < dim; d++) {
621 out.append("\ns.push(a0); }");
624 case opc_arraylength:
625 out.append("s.push(s.pop().length);");
635 out.append("{ var value = s.pop(); var indx = s.pop(); s.pop()[indx] = value; }");
646 out.append("{ var indx = s.pop(); s.push(s.pop()[indx]); }");
650 out.append("s.pop();");
652 out.append("s.pop();");
655 out.append("s.push(s[s.length - 1]);");
658 out.append("{ var v1 = s.pop(); var v2 = s.pop(); s.push(v1); s.push(v2); s.push(v1); }");
661 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); }");
664 out.append("s.push(" + byteCodes[++i] + ");");
667 out.append("s.push(" + readIntArg(byteCodes, i) + ");");
671 int indx = readIntArg(byteCodes, i);
672 String[] fi = jc.getFieldInfoName(indx);
673 out.append("s.push(s.pop().fld_").
674 append(fi[1]).append(");");
678 case opc_getstatic: {
679 int indx = readIntArg(byteCodes, i);
680 String[] fi = jc.getFieldInfoName(indx);
681 out.append("s.push(").append(fi[0].replace('/', '_'));
682 out.append('.').append(fi[1]).append(");");
687 case opc_putstatic: {
688 int indx = readIntArg(byteCodes, i);
689 String[] fi = jc.getFieldInfoName(indx);
690 out.append(fi[0].replace('/', '_'));
691 out.append('.').append(fi[1]).append(" = s.pop();");
697 int indx = readIntArg(byteCodes, i);
698 String[] fi = jc.getFieldInfoName(indx);
699 out.append("{ var v = s.pop(); s.pop().fld_")
700 .append(fi[1]).append(" = v; }");
704 case opc_checkcast: {
705 int indx = readIntArg(byteCodes, i);
706 final String type = jc.getClassName(indx);
707 if (!type.startsWith("[")) {
708 // no way to check arrays right now
709 out.append("if(s[s.length - 1].$instOf_")
710 .append(type.replace('/', '_'))
711 .append(" != 1) throw {};"); // XXX proper exception
716 case opc_instanceof: {
717 int indx = readIntArg(byteCodes, i);
718 final String type = jc.getClassName(indx);
719 out.append("s.push(s.pop().$instOf_")
720 .append(type.replace('/', '_'))
721 .append(" ? 1 : 0);");
726 out.append("{ var t = s.pop(); s = new Array(1); s[0] = t; throw t; }");
730 out.append("throw 'unknown bytecode " + c + "';");
735 for (int j = prev; j <= i; j++) {
737 final int cc = readByte(byteCodes, j);
738 out.append(Integer.toString(cc));
745 private int generateIf(byte[] byteCodes, int i, final String test) throws IOException {
746 int indx = i + readIntArg(byteCodes, i);
747 out.append("if (s.pop() ").append(test).append(" s.pop()) { gt = " + indx);
748 out.append("; continue; }");
752 private int readIntArg(byte[] byteCodes, int offsetInstruction) {
753 final int indxHi = byteCodes[offsetInstruction + 1] << 8;
754 final int indxLo = byteCodes[offsetInstruction + 2];
755 return (indxHi & 0xffffff00) | (indxLo & 0xff);
757 private int readInt4(byte[] byteCodes, int offsetInstruction) {
758 final int d = byteCodes[offsetInstruction + 0] << 24;
759 final int c = byteCodes[offsetInstruction + 1] << 16;
760 final int b = byteCodes[offsetInstruction + 2] << 8;
761 final int a = byteCodes[offsetInstruction + 3];
762 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
764 private int readByte(byte[] byteCodes, int offsetInstruction) {
765 return (byteCodes[offsetInstruction] + 256) % 256;
768 private static void countArgs(String descriptor, boolean[] hasReturnType, StringBuilder sig, StringBuilder cnt) {
770 Boolean count = null;
771 boolean array = false;
772 int firstPos = sig.length();
773 while (i < descriptor.length()) {
774 char ch = descriptor.charAt(i++);
798 if (ch == 'J' || ch == 'D') {
804 hasReturnType[0] = true;
805 sig.insert(firstPos, ch);
807 sig.insert(firstPos, 'A');
814 hasReturnType[0] = false;
815 sig.insert(firstPos, 'V');
818 int next = descriptor.indexOf(';', i);
824 sig.append(descriptor.substring(i, next).replace('/', '_'));
827 sig.insert(firstPos, descriptor.substring(i, next).replace('/', '_'));
828 sig.insert(firstPos, ch);
830 sig.insert(firstPos, 'A');
832 hasReturnType[0] = true;
840 break; // invalid character
845 private String findMethodName(MethodData m, StringBuilder cnt) {
846 StringBuilder name = new StringBuilder();
847 if ("<init>".equals(m.getName())) { // NOI18N
848 name.append("cons"); // NOI18N
849 } else if ("<clinit>".equals(m.getName())) { // NOI18N
850 name.append("class"); // NOI18N
852 name.append(m.getName());
855 boolean hasReturn[] = { false };
856 countArgs(findDescriptor(m.getInternalSig()), hasReturn, name, cnt);
857 return name.toString();
860 private String findMethodName(String[] mi, StringBuilder cnt, boolean[] hasReturn) {
861 StringBuilder name = new StringBuilder();
862 String descr = mi[2];//mi.getDescriptor();
864 if ("<init>".equals(nm)) { // NOI18N
865 name.append("cons"); // NOI18N
869 countArgs(findDescriptor(descr), hasReturn, name, cnt);
870 return name.toString();
873 private int invokeStaticMethod(byte[] byteCodes, int i, boolean isStatic)
875 int methodIndex = readIntArg(byteCodes, i);
876 String[] mi = jc.getFieldInfoName(methodIndex);
877 boolean[] hasReturn = { false };
878 StringBuilder cnt = new StringBuilder();
879 String mn = findMethodName(mi, cnt, hasReturn);
881 for (int j = cnt.length() - 1; j >= 0; j--) {
882 out.append("var v" + j).append(" = s.pop(); ");
886 out.append("s.push(");
888 final String in = mi[0];
889 out.append(in.replace('/', '_'));
890 out.append("(false).");
895 out.append("s.pop()");
898 for (int j = 0; j < cnt.length(); j++) {
912 private int invokeVirtualMethod(byte[] byteCodes, int i)
914 int methodIndex = readIntArg(byteCodes, i);
915 String[] mi = jc.getFieldInfoName(methodIndex);
916 boolean[] hasReturn = { false };
917 StringBuilder cnt = new StringBuilder();
918 String mn = findMethodName(mi, cnt, hasReturn);
920 for (int j = cnt.length() - 1; j >= 0; j--) {
921 out.append("var v" + j).append(" = s.pop(); ");
923 out.append("var self = s.pop(); ");
925 out.append("s.push(");
931 for (int j = 0; j < cnt.length(); j++) {
944 private void addReference(String cn) throws IOException {
945 if (requireReference(cn)) {
946 out.append(" /* needs ").append(cn).append(" */");
950 private void outType(String d, StringBuilder out) {
952 while (d.charAt(0) == '[') {
956 if (d.charAt(0) == 'L') {
957 assert d.charAt(d.length() - 1) == ';';
958 out.append(d.replace('/', '_').substring(0, d.length() - 1));
964 private String encodeConstant(int entryIndex) {
965 String s = jc.stringValue(entryIndex, true);
969 private String findDescriptor(String d) {
970 return d.replace('[', 'A');
973 private boolean javaScriptBody(String prefix, MethodData m, boolean isStatic) throws IOException {
974 byte[] arr = m.findAnnotationData(true);
978 final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
979 class P extends AnnotationParser {
981 String[] args = new String[30];
985 protected void visitAttr(String type, String attr, String value) {
986 if (type.equals(jvmType)) {
987 if ("body".equals(attr)) {
989 } else if ("args".equals(attr)) {
992 throw new IllegalArgumentException(attr);
999 if (p.body == null) {
1002 StringBuilder cnt = new StringBuilder();
1003 out.append(prefix).append(findMethodName(m, cnt));
1004 out.append(" = function(");
1008 out.append(p.args[0]);
1015 for (int i = 0; i < cnt.length(); i++) {
1017 out.append(p.args[index]);
1021 out.append(") {").append("\n");
1023 out.append("\n}\n");
1026 private static String className(ClassData jc) {
1027 //return jc.getName().getInternalName().replace('/', '_');
1028 return jc.getClassName().replace('/', '_');
1031 private static String[] findAnnotation(
1032 byte[] arr, ClassData cd, final String className,
1033 final String... attrNames
1034 ) throws IOException {
1038 final String[] values = new String[attrNames.length];
1039 final boolean[] found = { false };
1040 final String jvmType = "L" + className.replace('.', '/') + ";";
1041 AnnotationParser ap = new AnnotationParser() {
1043 protected void visitAttr(String type, String attr, String value) {
1044 if (type.equals(jvmType)) {
1046 for (int i = 0; i < attrNames.length; i++) {
1047 if (attrNames[i].equals(attr)) {
1056 return found[0] ? values : null;
1059 private CharSequence initField(FieldData v) {
1060 final String is = v.getInternalSig();
1061 if (is.length() == 1) {
1062 switch (is.charAt(0)) {
1068 case 'I': return " = 0;";
1070 case 'D': return " = 0.0;";
1072 throw new IllegalStateException(is);