Ability to control prototypes. Making sure any JavaScript Object is instance of Java 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 String[] proto = findAnnotation(arrData, jc,
86 "org.apidesign.bck2brwsr.core.JavaScriptPrototype",
87 "container", "prototype"
89 StringArray toInitilize = new StringArray();
90 final String className = className(jc);
91 out.append("\n\n").append(assignClass(className));
92 out.append("function CLS() {");
93 out.append("\n if (!CLS.prototype.$instOf_").append(className).append(") {");
94 for (FieldData v : jc.getFields()) {
96 out.append("\n CLS.").append(v.getName()).append(initField(v));
100 String sc = jc.getSuperClassName(); // with _
101 out.append("\n var p = CLS.prototype = ").
102 append(sc.replace('/', '_')).append("(true);");
103 out.append("\n var c = p;");
105 out.append("\n var p = ").append(proto[1]).append(";");
106 out.append("\n var c = ").append(proto[0]).append(";");
108 for (MethodData m : jc.getMethods()) {
110 generateStaticMethod("\n c.", m, toInitilize);
112 generateInstanceMethod("\n c.", m);
115 out.append("\n c.constructor = CLS;");
116 out.append("\n c.$instOf_").append(className).append(" = true;");
117 for (String superInterface : jc.getSuperInterfaces()) {
118 out.append("\n c.$instOf_").append(superInterface.replace('/', '_')).append(" = true;");
121 out.append("\n if (arguments.length === 0) {");
122 out.append("\n if (!(this instanceof CLS)) {");
123 out.append("\n return new CLS();");
125 for (FieldData v : jc.getFields()) {
127 out.append("\n this.fld_").
128 append(v.getName()).append(initField(v));
131 out.append("\n return this;");
133 out.append("\n return arguments[0] ? new CLS() : CLS.prototype;");
135 StringBuilder sb = new StringBuilder();
136 for (String init : toInitilize.toArray()) {
137 sb.append("\n").append(init).append("();");
139 return sb.toString();
141 private void generateStaticMethod(String prefix, MethodData m, StringArray toInitilize) throws IOException {
142 if (javaScriptBody(prefix, m, true)) {
145 StringBuilder argsCnt = new StringBuilder();
146 final String mn = findMethodName(m, argsCnt);
147 out.append(prefix).append(mn).append(" = function");
148 if (mn.equals("classV")) {
149 toInitilize.add(className(jc) + "(false)." + mn);
153 for (int index = 0, i = 0; i < argsCnt.length(); i++) {
155 out.append("arg").append(String.valueOf(index));
157 final String desc = null;// XXX findDescriptor(args.get(i).getDescriptor());
158 if (argsCnt.charAt(i) == '1') {
164 out.append(") {").append("\n");
165 final byte[] code = m.getCode();
167 int len = m.getMaxLocals();
168 for (int index = argsCnt.length(), i = argsCnt.length(); i < len; i++) {
170 out.append("arg").append(String.valueOf(i)).append(";\n");
172 out.append(" var s = new Array();\n");
175 out.append(" throw 'no code found for ").append(m.getInternalSig()).append("';\n");
180 private void generateInstanceMethod(String prefix, MethodData m) throws IOException {
181 if (javaScriptBody(prefix, m, false)) {
184 StringBuilder argsCnt = new StringBuilder();
185 final String mn = findMethodName(m, argsCnt);
186 out.append(prefix).append(mn).append(" = function");
189 for (int index = 1, i = 0; i < argsCnt.length(); i++) {
191 out.append("arg").append(String.valueOf(index));
192 if (argsCnt.charAt(i) == '1') {
198 out.append(") {").append("\n");
199 final byte[] code = m.getCode();
201 int len = m.getMaxLocals();
202 for (int index = argsCnt.length(), i = argsCnt.length(); i < len; i++) {
204 out.append("arg").append(String.valueOf(i + 1)).append(";\n");
206 out.append(";\n var s = new Array();\n");
209 out.append(" throw 'no code found for ").append(m.getInternalSig()).append("';\n");
214 private void produceCode(byte[] byteCodes) throws IOException {
215 out.append("\n var gt = 0;\n for(;;) switch(gt) {\n");
216 for (int i = 0; i < byteCodes.length; i++) {
218 out.append(" case " + i).append(": ");
219 final int c = readByte(byteCodes, i);
226 out.append("s.push(arg0);");
233 out.append("s.push(arg1);");
240 out.append("s.push(arg2);");
247 out.append("s.push(arg3);");
254 final int indx = readByte(byteCodes, ++i);
255 out.append("s.push(arg").append(indx + ");");
263 final int indx = readByte(byteCodes, ++i);
264 out.append("arg" + indx).append(" = s.pop();");
272 out.append("arg0 = s.pop();");
279 out.append("arg1 = s.pop();");
286 out.append("arg2 = s.pop();");
293 out.append("arg3 = s.pop();");
299 out.append("s.push(s.pop() + s.pop());");
305 out.append("{ var tmp = s.pop(); s.push(s.pop() - tmp); }");
311 out.append("s.push(s.pop() * s.pop());");
315 out.append("{ var tmp = s.pop(); s.push(Math.floor(s.pop() / tmp)); }");
319 out.append("{ var tmp = s.pop(); s.push(s.pop() / tmp); }");
325 out.append("{ var d = s.pop(); s.push(s.pop() % d); }");
329 out.append("s.push(s.pop() & s.pop());");
333 out.append("s.push(s.pop() | s.pop());");
337 out.append("s.push(s.pop() ^ s.pop());");
343 out.append("s.push(- s.pop());");
347 out.append("{ var v = s.pop(); s.push(s.pop() << v); }");
351 out.append("{ var v = s.pop(); s.push(s.pop() >> v); }");
355 out.append("{ var v = s.pop(); s.push(s.pop() >>> v); }");
358 final int varIndx = readByte(byteCodes, ++i);
359 final int incrBy = byteCodes[++i];
361 out.append("arg" + varIndx).append("++;");
363 out.append("arg" + varIndx).append(" += " + incrBy).append(";");
368 out.append("return;");
375 out.append("return s.pop();");
386 out.append("/* number conversion */");
392 out.append("s.push(Math.floor(s.pop()));");
397 out.append("/* number conversion */");
399 case opc_aconst_null:
400 out.append("s.push(null);");
403 out.append("s.push(-1);");
409 out.append("s.push(0);");
415 out.append("s.push(1);");
419 out.append("s.push(2);");
422 out.append("s.push(3);");
425 out.append("s.push(4);");
428 out.append("s.push(5);");
431 int indx = readByte(byteCodes, ++i);
432 String v = encodeConstant(indx);
433 out.append("s.push(").append(v).append(");");
438 int indx = readIntArg(byteCodes, i);
440 String v = encodeConstant(indx);
441 out.append("s.push(").append(v).append(");");
449 out.append("{ var delta = s.pop() - s.pop(); s.push(delta < 0 ?-1 : (delta == 0 ? 0 : 1)); }");
453 i = generateIf(byteCodes, i, "===");
456 i = generateIf(byteCodes, i, "!=");
458 case opc_if_icmpeq: {
459 i = generateIf(byteCodes, i, "==");
463 int indx = i + readIntArg(byteCodes, i);
464 out.append("if (s.pop() == 0) { gt = " + indx);
465 out.append("; continue; }");
470 int indx = i + readIntArg(byteCodes, i);
471 out.append("if (s.pop() != 0) { gt = " + indx);
472 out.append("; continue; }");
477 int indx = i + readIntArg(byteCodes, i);
478 out.append("if (s.pop() < 0) { gt = " + indx);
479 out.append("; continue; }");
484 int indx = i + readIntArg(byteCodes, i);
485 out.append("if (s.pop() <= 0) { gt = " + indx);
486 out.append("; continue; }");
491 int indx = i + readIntArg(byteCodes, i);
492 out.append("if (s.pop() > 0) { gt = " + indx);
493 out.append("; continue; }");
498 int indx = i + readIntArg(byteCodes, i);
499 out.append("if (s.pop() >= 0) { gt = " + indx);
500 out.append("; continue; }");
504 case opc_ifnonnull: {
505 int indx = i + readIntArg(byteCodes, i);
506 out.append("if (s.pop() !== null) { gt = " + indx);
507 out.append("; continue; }");
512 int indx = i + readIntArg(byteCodes, i);
513 out.append("if (s.pop() === null) { gt = " + indx);
514 out.append("; continue; }");
519 i = generateIf(byteCodes, i, "!=");
522 i = generateIf(byteCodes, i, ">");
525 i = generateIf(byteCodes, i, ">=");
528 i = generateIf(byteCodes, i, "<");
531 i = generateIf(byteCodes, i, "<=");
534 int indx = i + readIntArg(byteCodes, i);
535 out.append("gt = " + indx).append("; continue;");
539 case opc_lookupswitch: {
540 int table = i / 4 * 4 + 4;
541 int dflt = i + readInt4(byteCodes, table);
543 int n = readInt4(byteCodes, table);
545 out.append("switch (s.pop()) {\n");
547 int cnstnt = readInt4(byteCodes, table);
549 int offset = i + readInt4(byteCodes, table);
551 out.append(" case " + cnstnt).append(": gt = " + offset).append("; continue;\n");
553 out.append(" default: gt = " + dflt).append("; continue;\n}");
557 case opc_tableswitch: {
558 int table = i / 4 * 4 + 4;
559 int dflt = i + readInt4(byteCodes, table);
561 int low = readInt4(byteCodes, table);
563 int high = readInt4(byteCodes, table);
565 out.append("switch (s.pop()) {\n");
566 while (low <= high) {
567 int offset = i + readInt4(byteCodes, table);
569 out.append(" case " + low).append(": gt = " + offset).append("; continue;\n");
572 out.append(" default: gt = " + dflt).append("; continue;\n}");
576 case opc_invokeinterface: {
577 i = invokeVirtualMethod(byteCodes, i) + 2;
580 case opc_invokevirtual:
581 i = invokeVirtualMethod(byteCodes, i);
583 case opc_invokespecial:
584 i = invokeStaticMethod(byteCodes, i, false);
586 case opc_invokestatic:
587 i = invokeStaticMethod(byteCodes, i, true);
590 int indx = readIntArg(byteCodes, i);
591 String ci = jc.getClassName(indx);
592 out.append("s.push(new ");
593 out.append(ci.replace('/','_'));
600 int type = byteCodes[i++];
601 out.append("s.push(new Array(s.pop()).fillNulls());");
604 case opc_anewarray: {
605 i += 2; // skip type of array
606 out.append("s.push(new Array(s.pop()).fillNulls());");
609 case opc_multianewarray: {
611 int dim = readByte(byteCodes, ++i);
612 out.append("{ var a0 = new Array(s.pop()).fillNulls();");
613 for (int d = 1; d < dim; d++) {
614 out.append("\n var l" + d).append(" = s.pop();");
615 out.append("\n for (var i" + d).append (" = 0; i" + d).
616 append(" < a" + (d - 1)).
617 append(".length; i" + d).append("++) {");
618 out.append("\n var a" + d).
619 append (" = new Array(l" + d).append(").fillNulls();");
620 out.append("\n a" + (d - 1)).append("[i" + d).append("] = a" + d).
623 for (int d = 1; d < dim; d++) {
626 out.append("\ns.push(a0); }");
629 case opc_arraylength:
630 out.append("s.push(s.pop().length);");
640 out.append("{ var value = s.pop(); var indx = s.pop(); s.pop()[indx] = value; }");
651 out.append("{ var indx = s.pop(); s.push(s.pop()[indx]); }");
655 out.append("s.pop();");
657 out.append("s.pop();");
660 out.append("s.push(s[s.length - 1]);");
663 out.append("{ var v1 = s.pop(); var v2 = s.pop(); s.push(v1); s.push(v2); s.push(v1); }");
666 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); }");
669 out.append("s.push(" + byteCodes[++i] + ");");
672 out.append("s.push(" + readIntArg(byteCodes, i) + ");");
676 int indx = readIntArg(byteCodes, i);
677 String[] fi = jc.getFieldInfoName(indx);
678 out.append("s.push(s.pop().fld_").
679 append(fi[1]).append(");");
683 case opc_getstatic: {
684 int indx = readIntArg(byteCodes, i);
685 String[] fi = jc.getFieldInfoName(indx);
686 out.append("s.push(").append(fi[0].replace('/', '_'));
687 out.append('.').append(fi[1]).append(");");
692 case opc_putstatic: {
693 int indx = readIntArg(byteCodes, i);
694 String[] fi = jc.getFieldInfoName(indx);
695 out.append(fi[0].replace('/', '_'));
696 out.append('.').append(fi[1]).append(" = s.pop();");
702 int indx = readIntArg(byteCodes, i);
703 String[] fi = jc.getFieldInfoName(indx);
704 out.append("{ var v = s.pop(); s.pop().fld_")
705 .append(fi[1]).append(" = v; }");
709 case opc_checkcast: {
710 int indx = readIntArg(byteCodes, i);
711 final String type = jc.getClassName(indx);
712 if (!type.startsWith("[")) {
713 // no way to check arrays right now
714 out.append("if(s[s.length - 1].$instOf_")
715 .append(type.replace('/', '_'))
716 .append(" != 1) throw {};"); // XXX proper exception
721 case opc_instanceof: {
722 int indx = readIntArg(byteCodes, i);
723 final String type = jc.getClassName(indx);
724 out.append("s.push(s.pop().$instOf_")
725 .append(type.replace('/', '_'))
726 .append(" ? 1 : 0);");
731 out.append("{ var t = s.pop(); s = new Array(1); s[0] = t; throw t; }");
735 out.append("throw 'unknown bytecode " + c + "';");
740 for (int j = prev; j <= i; j++) {
742 final int cc = readByte(byteCodes, j);
743 out.append(Integer.toString(cc));
750 private int generateIf(byte[] byteCodes, int i, final String test) throws IOException {
751 int indx = i + readIntArg(byteCodes, i);
752 out.append("if (s.pop() ").append(test).append(" s.pop()) { gt = " + indx);
753 out.append("; continue; }");
757 private int readIntArg(byte[] byteCodes, int offsetInstruction) {
758 final int indxHi = byteCodes[offsetInstruction + 1] << 8;
759 final int indxLo = byteCodes[offsetInstruction + 2];
760 return (indxHi & 0xffffff00) | (indxLo & 0xff);
762 private int readInt4(byte[] byteCodes, int offsetInstruction) {
763 final int d = byteCodes[offsetInstruction + 0] << 24;
764 final int c = byteCodes[offsetInstruction + 1] << 16;
765 final int b = byteCodes[offsetInstruction + 2] << 8;
766 final int a = byteCodes[offsetInstruction + 3];
767 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
769 private int readByte(byte[] byteCodes, int offsetInstruction) {
770 return (byteCodes[offsetInstruction] + 256) % 256;
773 private static void countArgs(String descriptor, boolean[] hasReturnType, StringBuilder sig, StringBuilder cnt) {
775 Boolean count = null;
776 boolean array = false;
777 int firstPos = sig.length();
778 while (i < descriptor.length()) {
779 char ch = descriptor.charAt(i++);
803 if (ch == 'J' || ch == 'D') {
809 hasReturnType[0] = true;
810 sig.insert(firstPos, ch);
812 sig.insert(firstPos, 'A');
819 hasReturnType[0] = false;
820 sig.insert(firstPos, 'V');
823 int next = descriptor.indexOf(';', i);
829 sig.append(descriptor.substring(i, next).replace('/', '_'));
832 sig.insert(firstPos, descriptor.substring(i, next).replace('/', '_'));
833 sig.insert(firstPos, ch);
835 sig.insert(firstPos, 'A');
837 hasReturnType[0] = true;
845 break; // invalid character
850 private String findMethodName(MethodData m, StringBuilder cnt) {
851 StringBuilder name = new StringBuilder();
852 if ("<init>".equals(m.getName())) { // NOI18N
853 name.append("cons"); // NOI18N
854 } else if ("<clinit>".equals(m.getName())) { // NOI18N
855 name.append("class"); // NOI18N
857 name.append(m.getName());
860 boolean hasReturn[] = { false };
861 countArgs(findDescriptor(m.getInternalSig()), hasReturn, name, cnt);
862 return name.toString();
865 private String findMethodName(String[] mi, StringBuilder cnt, boolean[] hasReturn) {
866 StringBuilder name = new StringBuilder();
867 String descr = mi[2];//mi.getDescriptor();
869 if ("<init>".equals(nm)) { // NOI18N
870 name.append("cons"); // NOI18N
874 countArgs(findDescriptor(descr), hasReturn, name, cnt);
875 return name.toString();
878 private int invokeStaticMethod(byte[] byteCodes, int i, boolean isStatic)
880 int methodIndex = readIntArg(byteCodes, i);
881 String[] mi = jc.getFieldInfoName(methodIndex);
882 boolean[] hasReturn = { false };
883 StringBuilder cnt = new StringBuilder();
884 String mn = findMethodName(mi, cnt, hasReturn);
886 for (int j = cnt.length() - 1; j >= 0; j--) {
887 out.append("var v" + j).append(" = s.pop(); ");
891 out.append("s.push(");
893 final String in = mi[0];
894 out.append(in.replace('/', '_'));
895 out.append("(false).");
900 out.append("s.pop()");
903 for (int j = 0; j < cnt.length(); j++) {
917 private int invokeVirtualMethod(byte[] byteCodes, int i)
919 int methodIndex = readIntArg(byteCodes, i);
920 String[] mi = jc.getFieldInfoName(methodIndex);
921 boolean[] hasReturn = { false };
922 StringBuilder cnt = new StringBuilder();
923 String mn = findMethodName(mi, cnt, hasReturn);
925 for (int j = cnt.length() - 1; j >= 0; j--) {
926 out.append("var v" + j).append(" = s.pop(); ");
928 out.append("var self = s.pop(); ");
930 out.append("s.push(");
936 for (int j = 0; j < cnt.length(); j++) {
949 private void addReference(String cn) throws IOException {
950 if (requireReference(cn)) {
951 out.append(" /* needs ").append(cn).append(" */");
955 private void outType(String d, StringBuilder out) {
957 while (d.charAt(0) == '[') {
961 if (d.charAt(0) == 'L') {
962 assert d.charAt(d.length() - 1) == ';';
963 out.append(d.replace('/', '_').substring(0, d.length() - 1));
969 private String encodeConstant(int entryIndex) {
970 String s = jc.stringValue(entryIndex, true);
974 private String findDescriptor(String d) {
975 return d.replace('[', 'A');
978 private boolean javaScriptBody(String prefix, MethodData m, boolean isStatic) throws IOException {
979 byte[] arr = m.findAnnotationData(true);
983 final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
984 class P extends AnnotationParser {
986 String[] args = new String[30];
990 protected void visitAttr(String type, String attr, String value) {
991 if (type.equals(jvmType)) {
992 if ("body".equals(attr)) {
994 } else if ("args".equals(attr)) {
997 throw new IllegalArgumentException(attr);
1004 if (p.body == null) {
1007 StringBuilder cnt = new StringBuilder();
1008 out.append(prefix).append(findMethodName(m, cnt));
1009 out.append(" = function(");
1013 out.append(p.args[0]);
1020 for (int i = 0; i < cnt.length(); i++) {
1022 out.append(p.args[index]);
1026 out.append(") {").append("\n");
1028 out.append("\n}\n");
1031 private static String className(ClassData jc) {
1032 //return jc.getName().getInternalName().replace('/', '_');
1033 return jc.getClassName().replace('/', '_');
1036 private static String[] findAnnotation(
1037 byte[] arr, ClassData cd, final String className,
1038 final String... attrNames
1039 ) throws IOException {
1043 final String[] values = new String[attrNames.length];
1044 final boolean[] found = { false };
1045 final String jvmType = "L" + className.replace('.', '/') + ";";
1046 AnnotationParser ap = new AnnotationParser() {
1048 protected void visitAttr(String type, String attr, String value) {
1049 if (type.equals(jvmType)) {
1051 for (int i = 0; i < attrNames.length; i++) {
1052 if (attrNames[i].equals(attr)) {
1061 return found[0] ? values : null;
1064 private CharSequence initField(FieldData v) {
1065 final String is = v.getInternalSig();
1066 if (is.length() == 1) {
1067 switch (is.charAt(0)) {
1073 case 'I': return " = 0;";
1075 case 'D': return " = 0.0;";
1077 throw new IllegalStateException(is);