Rewriting String to use more of @JavaScriptBody & co.
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 = CLS.prototype = ").append(proto[1]).append(";");
106 out.append("\n var c = ").append(proto[0]).append(";");
108 for (MethodData m : jc.getMethods()) {
109 byte[] onlyArr = m.findAnnotationData(true);
110 String[] only = findAnnotation(onlyArr, jc,
111 "org.apidesign.bck2brwsr.core.JavaScriptOnly",
115 if (only[0] != null && only[1] != null) {
116 out.append("\n p.").append(only[0]).append(" = ")
117 .append(only[1]).append(";");
122 generateStaticMethod("\n c.", m, toInitilize);
124 generateInstanceMethod("\n c.", m);
127 out.append("\n c.constructor = CLS;");
128 out.append("\n c.$instOf_").append(className).append(" = true;");
129 for (String superInterface : jc.getSuperInterfaces()) {
130 out.append("\n c.$instOf_").append(superInterface.replace('/', '_')).append(" = true;");
133 out.append("\n if (arguments.length === 0) {");
134 out.append("\n if (!(this instanceof CLS)) {");
135 out.append("\n return new CLS();");
137 for (FieldData v : jc.getFields()) {
138 byte[] onlyArr = v.findAnnotationData(true);
139 String[] only = findAnnotation(onlyArr, jc,
140 "org.apidesign.bck2brwsr.core.JavaScriptOnly",
144 if (only[0] != null && only[1] != null) {
145 out.append("\n p.").append(only[0]).append(" = ")
146 .append(only[1]).append(";");
151 out.append("\n this.fld_").
152 append(v.getName()).append(initField(v));
155 out.append("\n return this;");
157 out.append("\n return arguments[0] ? new CLS() : CLS.prototype;");
159 StringBuilder sb = new StringBuilder();
160 for (String init : toInitilize.toArray()) {
161 sb.append("\n").append(init).append("();");
163 return sb.toString();
165 private void generateStaticMethod(String prefix, MethodData m, StringArray toInitilize) throws IOException {
166 if (javaScriptBody(prefix, m, true)) {
169 StringBuilder argsCnt = new StringBuilder();
170 final String mn = findMethodName(m, argsCnt);
171 out.append(prefix).append(mn).append(" = function");
172 if (mn.equals("classV")) {
173 toInitilize.add(className(jc) + "(false)." + mn);
177 for (int index = 0, i = 0; i < argsCnt.length(); i++) {
179 out.append("arg").append(String.valueOf(index));
181 final String desc = null;// XXX findDescriptor(args.get(i).getDescriptor());
182 if (argsCnt.charAt(i) == '1') {
188 out.append(") {").append("\n");
189 final byte[] code = m.getCode();
191 int len = m.getMaxLocals();
192 for (int index = argsCnt.length(), i = argsCnt.length(); i < len; i++) {
194 out.append("arg").append(String.valueOf(i)).append(";\n");
196 out.append(" var s = new Array();\n");
199 out.append(" throw 'no code found for ").append(m.getInternalSig()).append("';\n");
204 private void generateInstanceMethod(String prefix, MethodData m) throws IOException {
205 if (javaScriptBody(prefix, m, false)) {
208 StringBuilder argsCnt = new StringBuilder();
209 final String mn = findMethodName(m, argsCnt);
210 out.append(prefix).append(mn).append(" = function");
213 for (int index = 1, i = 0; i < argsCnt.length(); i++) {
215 out.append("arg").append(String.valueOf(index));
216 if (argsCnt.charAt(i) == '1') {
222 out.append(") {").append("\n");
223 final byte[] code = m.getCode();
225 int len = m.getMaxLocals();
226 for (int index = argsCnt.length(), i = argsCnt.length(); i < len; i++) {
228 out.append("arg").append(String.valueOf(i + 1)).append(";\n");
230 out.append(";\n var s = new Array();\n");
233 out.append(" throw 'no code found for ").append(m.getInternalSig()).append("';\n");
238 private void produceCode(byte[] byteCodes) throws IOException {
239 out.append("\n var gt = 0;\n for(;;) switch(gt) {\n");
240 for (int i = 0; i < byteCodes.length; i++) {
242 out.append(" case " + i).append(": ");
243 final int c = readByte(byteCodes, i);
250 out.append("s.push(arg0);");
257 out.append("s.push(arg1);");
264 out.append("s.push(arg2);");
271 out.append("s.push(arg3);");
278 final int indx = readByte(byteCodes, ++i);
279 out.append("s.push(arg").append(indx + ");");
287 final int indx = readByte(byteCodes, ++i);
288 out.append("arg" + indx).append(" = s.pop();");
296 out.append("arg0 = s.pop();");
303 out.append("arg1 = s.pop();");
310 out.append("arg2 = s.pop();");
317 out.append("arg3 = s.pop();");
323 out.append("s.push(s.pop() + s.pop());");
329 out.append("{ var tmp = s.pop(); s.push(s.pop() - tmp); }");
335 out.append("s.push(s.pop() * s.pop());");
339 out.append("{ var tmp = s.pop(); s.push(Math.floor(s.pop() / tmp)); }");
343 out.append("{ var tmp = s.pop(); s.push(s.pop() / tmp); }");
349 out.append("{ var d = s.pop(); s.push(s.pop() % d); }");
353 out.append("s.push(s.pop() & s.pop());");
357 out.append("s.push(s.pop() | s.pop());");
361 out.append("s.push(s.pop() ^ s.pop());");
367 out.append("s.push(- s.pop());");
371 out.append("{ var v = s.pop(); s.push(s.pop() << v); }");
375 out.append("{ var v = s.pop(); s.push(s.pop() >> v); }");
379 out.append("{ var v = s.pop(); s.push(s.pop() >>> v); }");
382 final int varIndx = readByte(byteCodes, ++i);
383 final int incrBy = byteCodes[++i];
385 out.append("arg" + varIndx).append("++;");
387 out.append("arg" + varIndx).append(" += " + incrBy).append(";");
392 out.append("return;");
399 out.append("return s.pop();");
410 out.append("/* number conversion */");
416 out.append("s.push(Math.floor(s.pop()));");
421 out.append("/* number conversion */");
423 case opc_aconst_null:
424 out.append("s.push(null);");
427 out.append("s.push(-1);");
433 out.append("s.push(0);");
439 out.append("s.push(1);");
443 out.append("s.push(2);");
446 out.append("s.push(3);");
449 out.append("s.push(4);");
452 out.append("s.push(5);");
455 int indx = readByte(byteCodes, ++i);
456 String v = encodeConstant(indx);
457 out.append("s.push(").append(v).append(");");
462 int indx = readIntArg(byteCodes, i);
464 String v = encodeConstant(indx);
465 out.append("s.push(").append(v).append(");");
473 out.append("{ var delta = s.pop() - s.pop(); s.push(delta < 0 ?-1 : (delta == 0 ? 0 : 1)); }");
477 i = generateIf(byteCodes, i, "===");
480 i = generateIf(byteCodes, i, "!=");
482 case opc_if_icmpeq: {
483 i = generateIf(byteCodes, i, "==");
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; }");
501 int indx = i + readIntArg(byteCodes, i);
502 out.append("if (s.pop() < 0) { gt = " + indx);
503 out.append("; continue; }");
508 int indx = i + readIntArg(byteCodes, i);
509 out.append("if (s.pop() <= 0) { gt = " + indx);
510 out.append("; continue; }");
515 int indx = i + readIntArg(byteCodes, i);
516 out.append("if (s.pop() > 0) { gt = " + indx);
517 out.append("; continue; }");
522 int indx = i + readIntArg(byteCodes, i);
523 out.append("if (s.pop() >= 0) { gt = " + indx);
524 out.append("; continue; }");
528 case opc_ifnonnull: {
529 int indx = i + readIntArg(byteCodes, i);
530 out.append("if (s.pop() !== null) { gt = " + indx);
531 out.append("; continue; }");
536 int indx = i + readIntArg(byteCodes, i);
537 out.append("if (s.pop() === null) { gt = " + indx);
538 out.append("; continue; }");
543 i = generateIf(byteCodes, i, "!=");
546 i = generateIf(byteCodes, i, ">");
549 i = generateIf(byteCodes, i, ">=");
552 i = generateIf(byteCodes, i, "<");
555 i = generateIf(byteCodes, i, "<=");
558 int indx = i + readIntArg(byteCodes, i);
559 out.append("gt = " + indx).append("; continue;");
563 case opc_lookupswitch: {
564 int table = i / 4 * 4 + 4;
565 int dflt = i + readInt4(byteCodes, table);
567 int n = readInt4(byteCodes, table);
569 out.append("switch (s.pop()) {\n");
571 int cnstnt = readInt4(byteCodes, table);
573 int offset = i + readInt4(byteCodes, table);
575 out.append(" case " + cnstnt).append(": gt = " + offset).append("; continue;\n");
577 out.append(" default: gt = " + dflt).append("; continue;\n}");
581 case opc_tableswitch: {
582 int table = i / 4 * 4 + 4;
583 int dflt = i + readInt4(byteCodes, table);
585 int low = readInt4(byteCodes, table);
587 int high = readInt4(byteCodes, table);
589 out.append("switch (s.pop()) {\n");
590 while (low <= high) {
591 int offset = i + readInt4(byteCodes, table);
593 out.append(" case " + low).append(": gt = " + offset).append("; continue;\n");
596 out.append(" default: gt = " + dflt).append("; continue;\n}");
600 case opc_invokeinterface: {
601 i = invokeVirtualMethod(byteCodes, i) + 2;
604 case opc_invokevirtual:
605 i = invokeVirtualMethod(byteCodes, i);
607 case opc_invokespecial:
608 i = invokeStaticMethod(byteCodes, i, false);
610 case opc_invokestatic:
611 i = invokeStaticMethod(byteCodes, i, true);
614 int indx = readIntArg(byteCodes, i);
615 String ci = jc.getClassName(indx);
616 out.append("s.push(new ");
617 out.append(ci.replace('/','_'));
624 int type = byteCodes[i++];
625 out.append("s.push(new Array(s.pop()).fillNulls());");
628 case opc_anewarray: {
629 i += 2; // skip type of array
630 out.append("s.push(new Array(s.pop()).fillNulls());");
633 case opc_multianewarray: {
635 int dim = readByte(byteCodes, ++i);
636 out.append("{ var a0 = new Array(s.pop()).fillNulls();");
637 for (int d = 1; d < dim; d++) {
638 out.append("\n var l" + d).append(" = s.pop();");
639 out.append("\n for (var i" + d).append (" = 0; i" + d).
640 append(" < a" + (d - 1)).
641 append(".length; i" + d).append("++) {");
642 out.append("\n var a" + d).
643 append (" = new Array(l" + d).append(").fillNulls();");
644 out.append("\n a" + (d - 1)).append("[i" + d).append("] = a" + d).
647 for (int d = 1; d < dim; d++) {
650 out.append("\ns.push(a0); }");
653 case opc_arraylength:
654 out.append("s.push(s.pop().length);");
664 out.append("{ var value = s.pop(); var indx = s.pop(); s.pop()[indx] = value; }");
675 out.append("{ var indx = s.pop(); s.push(s.pop()[indx]); }");
679 out.append("s.pop();");
681 out.append("s.pop();");
684 out.append("s.push(s[s.length - 1]);");
687 out.append("{ var v1 = s.pop(); var v2 = s.pop(); s.push(v1); s.push(v2); s.push(v1); }");
690 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); }");
693 out.append("s.push(" + byteCodes[++i] + ");");
696 out.append("s.push(" + readIntArg(byteCodes, i) + ");");
700 int indx = readIntArg(byteCodes, i);
701 String[] fi = jc.getFieldInfoName(indx);
702 out.append("s.push(s.pop().fld_").
703 append(fi[1]).append(");");
707 case opc_getstatic: {
708 int indx = readIntArg(byteCodes, i);
709 String[] fi = jc.getFieldInfoName(indx);
710 out.append("s.push(").append(fi[0].replace('/', '_'));
711 out.append('.').append(fi[1]).append(");");
716 case opc_putstatic: {
717 int indx = readIntArg(byteCodes, i);
718 String[] fi = jc.getFieldInfoName(indx);
719 out.append(fi[0].replace('/', '_'));
720 out.append('.').append(fi[1]).append(" = s.pop();");
726 int indx = readIntArg(byteCodes, i);
727 String[] fi = jc.getFieldInfoName(indx);
728 out.append("{ var v = s.pop(); s.pop().fld_")
729 .append(fi[1]).append(" = v; }");
733 case opc_checkcast: {
734 int indx = readIntArg(byteCodes, i);
735 final String type = jc.getClassName(indx);
736 if (!type.startsWith("[")) {
737 // no way to check arrays right now
738 out.append("if(s[s.length - 1].$instOf_")
739 .append(type.replace('/', '_'))
740 .append(" != 1) throw {};"); // XXX proper exception
745 case opc_instanceof: {
746 int indx = readIntArg(byteCodes, i);
747 final String type = jc.getClassName(indx);
748 out.append("s.push(s.pop().$instOf_")
749 .append(type.replace('/', '_'))
750 .append(" ? 1 : 0);");
755 out.append("{ var t = s.pop(); s = new Array(1); s[0] = t; throw t; }");
759 out.append("throw 'unknown bytecode " + c + "';");
764 for (int j = prev; j <= i; j++) {
766 final int cc = readByte(byteCodes, j);
767 out.append(Integer.toString(cc));
774 private int generateIf(byte[] byteCodes, int i, final String test) throws IOException {
775 int indx = i + readIntArg(byteCodes, i);
776 out.append("if (s.pop() ").append(test).append(" s.pop()) { gt = " + indx);
777 out.append("; continue; }");
781 private int readIntArg(byte[] byteCodes, int offsetInstruction) {
782 final int indxHi = byteCodes[offsetInstruction + 1] << 8;
783 final int indxLo = byteCodes[offsetInstruction + 2];
784 return (indxHi & 0xffffff00) | (indxLo & 0xff);
786 private int readInt4(byte[] byteCodes, int offsetInstruction) {
787 final int d = byteCodes[offsetInstruction + 0] << 24;
788 final int c = byteCodes[offsetInstruction + 1] << 16;
789 final int b = byteCodes[offsetInstruction + 2] << 8;
790 final int a = byteCodes[offsetInstruction + 3];
791 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
793 private int readByte(byte[] byteCodes, int offsetInstruction) {
794 return (byteCodes[offsetInstruction] + 256) % 256;
797 private static void countArgs(String descriptor, boolean[] hasReturnType, StringBuilder sig, StringBuilder cnt) {
799 Boolean count = null;
800 boolean array = false;
801 int firstPos = sig.length();
802 while (i < descriptor.length()) {
803 char ch = descriptor.charAt(i++);
827 if (ch == 'J' || ch == 'D') {
833 hasReturnType[0] = true;
834 sig.insert(firstPos, ch);
836 sig.insert(firstPos, 'A');
843 hasReturnType[0] = false;
844 sig.insert(firstPos, 'V');
847 int next = descriptor.indexOf(';', i);
853 sig.append(descriptor.substring(i, next).replace('/', '_'));
856 sig.insert(firstPos, descriptor.substring(i, next).replace('/', '_'));
857 sig.insert(firstPos, ch);
859 sig.insert(firstPos, 'A');
861 hasReturnType[0] = true;
869 break; // invalid character
874 private String findMethodName(MethodData m, StringBuilder cnt) {
875 StringBuilder name = new StringBuilder();
876 if ("<init>".equals(m.getName())) { // NOI18N
877 name.append("cons"); // NOI18N
878 } else if ("<clinit>".equals(m.getName())) { // NOI18N
879 name.append("class"); // NOI18N
881 name.append(m.getName());
884 boolean hasReturn[] = { false };
885 countArgs(findDescriptor(m.getInternalSig()), hasReturn, name, cnt);
886 return name.toString();
889 private String findMethodName(String[] mi, StringBuilder cnt, boolean[] hasReturn) {
890 StringBuilder name = new StringBuilder();
891 String descr = mi[2];//mi.getDescriptor();
893 if ("<init>".equals(nm)) { // NOI18N
894 name.append("cons"); // NOI18N
898 countArgs(findDescriptor(descr), hasReturn, name, cnt);
899 return name.toString();
902 private int invokeStaticMethod(byte[] byteCodes, int i, boolean isStatic)
904 int methodIndex = readIntArg(byteCodes, i);
905 String[] mi = jc.getFieldInfoName(methodIndex);
906 boolean[] hasReturn = { false };
907 StringBuilder cnt = new StringBuilder();
908 String mn = findMethodName(mi, cnt, hasReturn);
910 for (int j = cnt.length() - 1; j >= 0; j--) {
911 out.append("var v" + j).append(" = s.pop(); ");
915 out.append("s.push(");
917 final String in = mi[0];
918 out.append(in.replace('/', '_'));
919 out.append("(false).");
924 out.append("s.pop()");
927 for (int j = 0; j < cnt.length(); j++) {
941 private int invokeVirtualMethod(byte[] byteCodes, int i)
943 int methodIndex = readIntArg(byteCodes, i);
944 String[] mi = jc.getFieldInfoName(methodIndex);
945 boolean[] hasReturn = { false };
946 StringBuilder cnt = new StringBuilder();
947 String mn = findMethodName(mi, cnt, hasReturn);
949 for (int j = cnt.length() - 1; j >= 0; j--) {
950 out.append("var v" + j).append(" = s.pop(); ");
952 out.append("var self = s.pop(); ");
954 out.append("s.push(");
960 for (int j = 0; j < cnt.length(); j++) {
973 private void addReference(String cn) throws IOException {
974 if (requireReference(cn)) {
975 out.append(" /* needs ").append(cn).append(" */");
979 private void outType(String d, StringBuilder out) {
981 while (d.charAt(0) == '[') {
985 if (d.charAt(0) == 'L') {
986 assert d.charAt(d.length() - 1) == ';';
987 out.append(d.replace('/', '_').substring(0, d.length() - 1));
993 private String encodeConstant(int entryIndex) {
994 String s = jc.stringValue(entryIndex, true);
998 private String findDescriptor(String d) {
999 return d.replace('[', 'A');
1002 private boolean javaScriptBody(String prefix, MethodData m, boolean isStatic) throws IOException {
1003 byte[] arr = m.findAnnotationData(true);
1007 final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
1008 class P extends AnnotationParser {
1010 String[] args = new String[30];
1014 protected void visitAttr(String type, String attr, String value) {
1015 if (type.equals(jvmType)) {
1016 if ("body".equals(attr)) {
1018 } else if ("args".equals(attr)) {
1019 args[cnt++] = value;
1021 throw new IllegalArgumentException(attr);
1028 if (p.body == null) {
1031 StringBuilder cnt = new StringBuilder();
1032 out.append(prefix).append(findMethodName(m, cnt));
1033 out.append(" = function(");
1037 out.append(p.args[0]);
1044 for (int i = 0; i < cnt.length(); i++) {
1046 out.append(p.args[index]);
1050 out.append(") {").append("\n");
1052 out.append("\n}\n");
1055 private static String className(ClassData jc) {
1056 //return jc.getName().getInternalName().replace('/', '_');
1057 return jc.getClassName().replace('/', '_');
1060 private static String[] findAnnotation(
1061 byte[] arr, ClassData cd, final String className,
1062 final String... attrNames
1063 ) throws IOException {
1067 final String[] values = new String[attrNames.length];
1068 final boolean[] found = { false };
1069 final String jvmType = "L" + className.replace('.', '/') + ";";
1070 AnnotationParser ap = new AnnotationParser() {
1072 protected void visitAttr(String type, String attr, String value) {
1073 if (type.equals(jvmType)) {
1075 for (int i = 0; i < attrNames.length; i++) {
1076 if (attrNames[i].equals(attr)) {
1085 return found[0] ? values : null;
1088 private CharSequence initField(FieldData v) {
1089 final String is = v.getInternalSig();
1090 if (is.length() == 1) {
1091 switch (is.charAt(0)) {
1097 case 'I': return " = 0;";
1099 case 'D': return " = 0.0;";
1101 throw new IllegalStateException(is);