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);
54 * Converts a given class file to a JavaScript version.
56 * @param classFile input stream with code of the .class file
57 * @return the initialization code for this class, if any. Otherwise <code>null</code>
59 * @throws IOException if something goes wrong during read or write or translating
62 public String compile(InputStream classFile) throws IOException {
63 this.jc = new ClassData(classFile);
64 byte[] arrData = jc.findAnnotationData(true);
65 String[] arr = findAnnotation(arrData, jc,
66 "org.apidesign.bck2brwsr.core.ExtraJavaScript",
67 "resource", "processByteCode"
70 requireScript(arr[0]);
71 if ("0".equals(arr[1])) {
75 StringArray toInitilize = new StringArray();
76 final String className = className(jc);
77 out.append("\nfunction ").append(className);
79 for (FieldData v : jc.getFields()) {
81 out.append("\n this.fld_").
82 append(v.getName()).append(initField(v));
86 out.append("\n\nfunction ").append(className).append("_proto() {");
87 out.append("\n if (").append(className).
88 append(".prototype.$instOf_").append(className).append(") {");
89 out.append("\n return new ").append(className).append(";");
91 for (FieldData v : jc.getFields()) {
93 generateStaticField(v);
96 // ClassName sc = jc.getSuperClass();
97 String sc = jc.getSuperClassName(); // with _
99 out.append("\n var p = ").append(className)
100 .append(".prototype = ").
101 append(sc.replace('/', '_')).append("_proto();");
103 out.append("\n var p = ").append(className).append(".prototype;");
105 for (MethodData m : jc.getMethods()) {
107 generateStaticMethod("\n p.", m, toInitilize);
109 generateInstanceMethod("\n p.", m);
112 out.append("\n p.$instOf_").append(className).append(" = true;");
113 for (String superInterface : jc.getSuperInterfaces()) {
114 out.append("\n p.$instOf_").append(superInterface.replace('/', '_')).append(" = true;");
116 out.append("\n return new ").append(className).append(";");
118 out.append("\n").append(className).append("_proto();");
119 StringBuilder sb = new StringBuilder();
120 for (String init : toInitilize.toArray()) {
121 sb.append("\n").append(init).append("();");
123 return sb.toString();
125 private void generateStaticMethod(String prefix, MethodData m, StringArray toInitilize) throws IOException {
126 if (javaScriptBody(prefix, m, true)) {
129 StringBuilder argsCnt = new StringBuilder();
130 final String mn = findMethodName(m, argsCnt);
131 out.append(prefix).append(mn).append(" = function");
132 if (mn.equals("classV")) {
133 toInitilize.add(className(jc) + "_proto()." + mn);
137 for (int index = 0, i = 0; i < argsCnt.length(); i++) {
139 out.append("arg").append(String.valueOf(index));
141 final String desc = null;// XXX findDescriptor(args.get(i).getDescriptor());
142 if (argsCnt.charAt(i) == '1') {
148 out.append(") {").append("\n");
149 final byte[] code = m.getCode();
151 int len = m.getMaxLocals();
152 for (int index = argsCnt.length(), i = argsCnt.length(); i < len; i++) {
154 out.append("arg").append(String.valueOf(i)).append(";\n");
156 out.append(" var stack = new Array();\n");
159 out.append(" /* no code found for ").append(m.getInternalSig()).append(" */\n");
164 private void generateInstanceMethod(String prefix, MethodData m) throws IOException {
165 if (javaScriptBody(prefix, m, false)) {
168 StringBuilder argsCnt = new StringBuilder();
169 final String mn = findMethodName(m, argsCnt);
170 out.append(prefix).append(mn).append(" = function");
173 for (int index = 1, i = 0; i < argsCnt.length(); i++) {
175 out.append("arg").append(String.valueOf(index));
176 if (argsCnt.charAt(i) == '1') {
182 out.append(") {").append("\n");
183 final byte[] code = m.getCode();
185 int len = m.getMaxLocals();
186 for (int index = argsCnt.length(), i = argsCnt.length(); i < len; i++) {
188 out.append("arg").append(String.valueOf(i + 1)).append(";\n");
190 out.append(";\n var stack = new Array();\n");
193 out.append(" /* no code found for ").append(m.getInternalSig()).append(" */\n");
198 private void produceCode(byte[] byteCodes) throws IOException {
199 out.append("\n var gt = 0;\n for(;;) switch(gt) {\n");
200 for (int i = 0; i < byteCodes.length; i++) {
202 out.append(" case " + i).append(": ");
203 final int c = readByte(byteCodes, i);
210 out.append("stack.push(arg0);");
217 out.append("stack.push(arg1);");
224 out.append("stack.push(arg2);");
231 out.append("stack.push(arg3);");
238 final int indx = readByte(byteCodes, ++i);
239 out.append("stack.push(arg").append(indx + ");");
247 final int indx = readByte(byteCodes, ++i);
248 out.append("arg" + indx).append(" = stack.pop();");
256 out.append("arg0 = stack.pop();");
263 out.append("arg1 = stack.pop();");
270 out.append("arg2 = stack.pop();");
277 out.append("arg3 = stack.pop();");
283 out.append("stack.push(stack.pop() + stack.pop());");
289 out.append("{ var tmp = stack.pop(); stack.push(stack.pop() - tmp); }");
295 out.append("stack.push(stack.pop() * stack.pop());");
299 out.append("{ var tmp = stack.pop(); stack.push(Math.floor(stack.pop() / tmp)); }");
303 out.append("{ var tmp = stack.pop(); stack.push(stack.pop() / tmp); }");
309 out.append("{ var d = stack.pop(); stack.push(stack.pop() % d); }");
313 out.append("stack.push(stack.pop() & stack.pop());");
317 out.append("stack.push(stack.pop() | stack.pop());");
321 out.append("stack.push(stack.pop() ^ stack.pop());");
327 out.append("stack.push(- stack.pop());");
331 out.append("{ var v = stack.pop(); stack.push(stack.pop() << v); }");
335 out.append("{ var v = stack.pop(); stack.push(stack.pop() >> v); }");
339 out.append("{ var v = stack.pop(); stack.push(stack.pop() >>> v); }");
342 final int varIndx = readByte(byteCodes, ++i);
343 final int incrBy = byteCodes[++i];
345 out.append("arg" + varIndx).append("++;");
347 out.append("arg" + varIndx).append(" += " + incrBy).append(";");
352 out.append("return;");
359 out.append("return stack.pop();");
370 out.append("/* number conversion */");
376 out.append("stack.push(Math.floor(stack.pop()));");
381 out.append("/* number conversion */");
383 case opc_aconst_null:
384 out.append("stack.push(null);");
387 out.append("stack.push(-1);");
393 out.append("stack.push(0);");
399 out.append("stack.push(1);");
403 out.append("stack.push(2);");
406 out.append("stack.push(3);");
409 out.append("stack.push(4);");
412 out.append("stack.push(5);");
415 int indx = readByte(byteCodes, ++i);
416 String v = encodeConstant(indx);
417 out.append("stack.push(").append(v).append(");");
422 int indx = readIntArg(byteCodes, i);
424 String v = encodeConstant(indx);
425 out.append("stack.push(").append(v).append(");");
433 out.append("{ var delta = stack.pop() - stack.pop(); stack.push(delta < 0 ?-1 : (delta == 0 ? 0 : 1)); }");
437 i = generateIf(byteCodes, i, "===");
440 i = generateIf(byteCodes, i, "!=");
442 case opc_if_icmpeq: {
443 i = generateIf(byteCodes, i, "==");
447 int indx = i + readIntArg(byteCodes, i);
448 out.append("if (stack.pop() == 0) { gt = " + indx);
449 out.append("; continue; }");
454 int indx = i + readIntArg(byteCodes, i);
455 out.append("if (stack.pop() != 0) { gt = " + indx);
456 out.append("; continue; }");
461 int indx = i + readIntArg(byteCodes, i);
462 out.append("if (stack.pop() < 0) { gt = " + indx);
463 out.append("; continue; }");
468 int indx = i + readIntArg(byteCodes, i);
469 out.append("if (stack.pop() <= 0) { gt = " + indx);
470 out.append("; continue; }");
475 int indx = i + readIntArg(byteCodes, i);
476 out.append("if (stack.pop() > 0) { gt = " + indx);
477 out.append("; continue; }");
482 int indx = i + readIntArg(byteCodes, i);
483 out.append("if (stack.pop() >= 0) { gt = " + indx);
484 out.append("; continue; }");
488 case opc_ifnonnull: {
489 int indx = i + readIntArg(byteCodes, i);
490 out.append("if (stack.pop() !== null) { gt = " + indx);
491 out.append("; continue; }");
496 int indx = i + readIntArg(byteCodes, i);
497 out.append("if (stack.pop() === null) { gt = " + indx);
498 out.append("; continue; }");
503 i = generateIf(byteCodes, i, "!=");
506 i = generateIf(byteCodes, i, ">");
509 i = generateIf(byteCodes, i, ">=");
512 i = generateIf(byteCodes, i, "<");
515 i = generateIf(byteCodes, i, "<=");
518 int indx = i + readIntArg(byteCodes, i);
519 out.append("gt = " + indx).append("; continue;");
523 case opc_lookupswitch: {
524 int table = i / 4 * 4 + 4;
525 int dflt = i + readInt4(byteCodes, table);
527 int n = readInt4(byteCodes, table);
529 out.append("switch (stack.pop()) {\n");
531 int cnstnt = readInt4(byteCodes, table);
533 int offset = i + readInt4(byteCodes, table);
535 out.append(" case " + cnstnt).append(": gt = " + offset).append("; continue;\n");
537 out.append(" default: gt = " + dflt).append("; continue;\n}");
541 case opc_tableswitch: {
542 int table = i / 4 * 4 + 4;
543 int dflt = i + readInt4(byteCodes, table);
545 int low = readInt4(byteCodes, table);
547 int high = readInt4(byteCodes, table);
549 out.append("switch (stack.pop()) {\n");
550 while (low <= high) {
551 int offset = i + readInt4(byteCodes, table);
553 out.append(" case " + low).append(": gt = " + offset).append("; continue;\n");
556 out.append(" default: gt = " + dflt).append("; continue;\n}");
560 case opc_invokeinterface: {
561 i = invokeVirtualMethod(byteCodes, i) + 2;
564 case opc_invokevirtual:
565 i = invokeVirtualMethod(byteCodes, i);
567 case opc_invokespecial:
568 i = invokeStaticMethod(byteCodes, i, false);
570 case opc_invokestatic:
571 i = invokeStaticMethod(byteCodes, i, true);
574 int indx = readIntArg(byteCodes, i);
575 String ci = jc.getClassName(indx);
576 out.append("stack.push(");
577 out.append("new ").append(ci.replace('/','_'));
584 int type = byteCodes[i++];
585 out.append("stack.push(new Array(stack.pop()).fillNulls());");
588 case opc_anewarray: {
589 i += 2; // skip type of array
590 out.append("stack.push(new Array(stack.pop()).fillNulls());");
593 case opc_multianewarray: {
595 int dim = readByte(byteCodes, ++i);
596 out.append("{ var a0 = new Array(stack.pop()).fillNulls();");
597 for (int d = 1; d < dim; d++) {
598 out.append("\n var l" + d).append(" = stack.pop();");
599 out.append("\n for (var i" + d).append (" = 0; i" + d).
600 append(" < a" + (d - 1)).
601 append(".length; i" + d).append("++) {");
602 out.append("\n var a" + d).
603 append (" = new Array(l" + d).append(").fillNulls();");
604 out.append("\n a" + (d - 1)).append("[i" + d).append("] = a" + d).
607 for (int d = 1; d < dim; d++) {
610 out.append("\nstack.push(a0); }");
613 case opc_arraylength:
614 out.append("stack.push(stack.pop().length);");
624 out.append("{ var value = stack.pop(); var indx = stack.pop(); stack.pop()[indx] = value; }");
635 out.append("{ var indx = stack.pop(); stack.push(stack.pop()[indx]); }");
639 out.append("stack.pop();");
641 out.append("stack.pop();");
644 out.append("stack.push(stack[stack.length - 1]);");
647 out.append("{ var v1 = stack.pop(); var v2 = stack.pop(); stack.push(v1); stack.push(v2); stack.push(v1); }");
650 out.append("{ var v1 = stack.pop(); var v2 = stack.pop(); var v3 = stack.pop(); stack.push(v1); stack.push(v3); stack.push(v2); stack.push(v1); }");
653 out.append("stack.push(" + byteCodes[++i] + ");");
656 out.append("stack.push(" + readIntArg(byteCodes, i) + ");");
660 int indx = readIntArg(byteCodes, i);
661 String[] fi = jc.getFieldInfoName(indx);
662 out.append("stack.push(stack.pop().fld_").
663 append(fi[1]).append(");");
667 case opc_getstatic: {
668 int indx = readIntArg(byteCodes, i);
669 String[] fi = jc.getFieldInfoName(indx);
670 out.append("stack.push(").append(fi[0].replace('/', '_'));
671 out.append('.').append(fi[1]).append(");");
676 case opc_putstatic: {
677 int indx = readIntArg(byteCodes, i);
678 String[] fi = jc.getFieldInfoName(indx);
679 out.append(fi[0].replace('/', '_'));
680 out.append('.').append(fi[1]).append(" = stack.pop();");
686 int indx = readIntArg(byteCodes, i);
687 String[] fi = jc.getFieldInfoName(indx);
688 out.append("{ var v = stack.pop(); stack.pop().fld_")
689 .append(fi[1]).append(" = v; }");
693 case opc_checkcast: {
694 int indx = readIntArg(byteCodes, i);
695 final String type = jc.getClassName(indx);
696 if (!type.startsWith("[")) {
697 // no way to check arrays right now
698 out.append("if(stack[stack.length - 1].$instOf_")
699 .append(type.replace('/', '_'))
700 .append(" != 1) throw {};"); // XXX proper exception
705 case opc_instanceof: {
706 int indx = readIntArg(byteCodes, i);
707 final String type = jc.getClassName(indx);
708 out.append("stack.push(stack.pop().$instOf_")
709 .append(type.replace('/', '_'))
710 .append(" ? 1 : 0);");
715 out.append("{ var t = stack.pop(); stack = new Array(1); stack[0] = t; throw t; }");
719 out.append("throw 'unknown bytecode " + c + "';");
724 for (int j = prev; j <= i; j++) {
726 final int cc = readByte(byteCodes, j);
727 out.append(Integer.toString(cc));
734 private int generateIf(byte[] byteCodes, int i, final String test) throws IOException {
735 int indx = i + readIntArg(byteCodes, i);
736 out.append("if (stack.pop() ").append(test).append(" stack.pop()) { gt = " + indx);
737 out.append("; continue; }");
741 private int readIntArg(byte[] byteCodes, int offsetInstruction) {
742 final int indxHi = byteCodes[offsetInstruction + 1] << 8;
743 final int indxLo = byteCodes[offsetInstruction + 2];
744 return (indxHi & 0xffffff00) | (indxLo & 0xff);
746 private int readInt4(byte[] byteCodes, int offsetInstruction) {
747 final int d = byteCodes[offsetInstruction + 0] << 24;
748 final int c = byteCodes[offsetInstruction + 1] << 16;
749 final int b = byteCodes[offsetInstruction + 2] << 8;
750 final int a = byteCodes[offsetInstruction + 3];
751 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
753 private int readByte(byte[] byteCodes, int offsetInstruction) {
754 return (byteCodes[offsetInstruction] + 256) % 256;
757 private static void countArgs(String descriptor, boolean[] hasReturnType, StringBuilder sig, StringBuilder cnt) {
759 Boolean count = null;
760 boolean array = false;
761 int firstPos = sig.length();
762 while (i < descriptor.length()) {
763 char ch = descriptor.charAt(i++);
787 if (ch == 'J' || ch == 'D') {
793 hasReturnType[0] = true;
794 sig.insert(firstPos, ch);
796 sig.insert(firstPos, 'A');
803 hasReturnType[0] = false;
804 sig.insert(firstPos, 'V');
807 int next = descriptor.indexOf(';', i);
813 sig.append(descriptor.substring(i, next).replace('/', '_'));
816 sig.insert(firstPos, descriptor.substring(i, next).replace('/', '_'));
817 sig.insert(firstPos, ch);
819 sig.insert(firstPos, 'A');
821 hasReturnType[0] = true;
829 break; // invalid character
834 private void generateStaticField(FieldData v) throws IOException {
836 .append(className(jc))
837 .append('.').append(v.getName()).append(initField(v));
840 private String findMethodName(MethodData m, StringBuilder cnt) {
841 StringBuilder name = new StringBuilder();
842 if ("<init>".equals(m.getName())) { // NOI18N
843 name.append("cons"); // NOI18N
844 } else if ("<clinit>".equals(m.getName())) { // NOI18N
845 name.append("class"); // NOI18N
847 name.append(m.getName());
850 boolean hasReturn[] = { false };
851 countArgs(findDescriptor(m.getInternalSig()), hasReturn, name, cnt);
852 return name.toString();
855 private String findMethodName(String[] mi, StringBuilder cnt, boolean[] hasReturn) {
856 StringBuilder name = new StringBuilder();
857 String descr = mi[2];//mi.getDescriptor();
859 if ("<init>".equals(nm)) { // NOI18N
860 name.append("cons"); // NOI18N
864 countArgs(findDescriptor(descr), hasReturn, name, cnt);
865 return name.toString();
868 private int invokeStaticMethod(byte[] byteCodes, int i, boolean isStatic)
870 int methodIndex = readIntArg(byteCodes, i);
871 String[] mi = jc.getFieldInfoName(methodIndex);
872 boolean[] hasReturn = { false };
873 StringBuilder cnt = new StringBuilder();
874 String mn = findMethodName(mi, cnt, hasReturn);
876 for (int j = cnt.length() - 1; j >= 0; j--) {
877 out.append("var v" + j).append(" = stack.pop(); ");
881 out.append("stack.push(");
883 final String in = mi[0];
884 out.append(in.replace('/', '_'));
885 out.append(".prototype.");
890 out.append("stack.pop()");
893 for (int j = 0; j < cnt.length(); j++) {
907 private int invokeVirtualMethod(byte[] byteCodes, int i)
909 int methodIndex = readIntArg(byteCodes, i);
910 String[] mi = jc.getFieldInfoName(methodIndex);
911 boolean[] hasReturn = { false };
912 StringBuilder cnt = new StringBuilder();
913 String mn = findMethodName(mi, cnt, hasReturn);
915 for (int j = cnt.length() - 1; j >= 0; j--) {
916 out.append("var v" + j).append(" = stack.pop(); ");
918 out.append("var self = stack.pop(); ");
920 out.append("stack.push(");
926 for (int j = 0; j < cnt.length(); j++) {
939 private void addReference(String cn) throws IOException {
940 if (requireReference(cn)) {
941 out.append(" /* needs ").append(cn).append(" */");
945 private void outType(String d, StringBuilder out) {
947 while (d.charAt(0) == '[') {
951 if (d.charAt(0) == 'L') {
952 assert d.charAt(d.length() - 1) == ';';
953 out.append(d.replace('/', '_').substring(0, d.length() - 1));
959 private String encodeConstant(int entryIndex) {
960 String s = jc.stringValue(entryIndex, true);
964 private String findDescriptor(String d) {
965 return d.replace('[', 'A');
968 private boolean javaScriptBody(String prefix, MethodData m, boolean isStatic) throws IOException {
969 byte[] arr = m.findAnnotationData(true);
973 final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
974 class P extends AnnotationParser {
976 String[] args = new String[30];
980 protected void visitAttr(String type, String attr, String value) {
981 if (type.equals(jvmType)) {
982 if ("body".equals(attr)) {
984 } else if ("args".equals(attr)) {
987 throw new IllegalArgumentException(attr);
994 if (p.body == null) {
997 StringBuilder cnt = new StringBuilder();
998 out.append(prefix).append(findMethodName(m, cnt));
999 out.append(" = function(");
1003 out.append(p.args[0]);
1010 for (int i = 0; i < cnt.length(); i++) {
1012 out.append(p.args[index]);
1016 out.append(") {").append("\n");
1018 out.append("\n}\n");
1021 private static String className(ClassData jc) {
1022 //return jc.getName().getInternalName().replace('/', '_');
1023 return jc.getClassName().replace('/', '_');
1026 private static String[] findAnnotation(
1027 byte[] arr, ClassData cd, final String className,
1028 final String... attrNames
1029 ) throws IOException {
1033 final String[] values = new String[attrNames.length];
1034 final boolean[] found = { false };
1035 final String jvmType = "L" + className.replace('.', '/') + ";";
1036 AnnotationParser ap = new AnnotationParser() {
1038 protected void visitAttr(String type, String attr, String value) {
1039 if (type.equals(jvmType)) {
1041 for (int i = 0; i < attrNames.length; i++) {
1042 if (attrNames[i].equals(attr)) {
1051 return found[0] ? values : null;
1054 private CharSequence initField(FieldData v) {
1055 final String is = v.getInternalSig();
1056 if (is.length() == 1) {
1057 switch (is.charAt(0)) {
1063 case 'I': return " = 0;";
1065 case 'D': return " = 0.0;";
1067 throw new IllegalStateException(is);