Merging new class and prototype methods. When asking for prototype one can add (true) argument
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("\n\nfunction ").append(className).append("() {");
78 out.append("\n if (!").append(className).
79 append(".prototype.$instOf_").append(className).append(") {");
80 for (FieldData v : jc.getFields()) {
82 generateStaticField(v);
85 // ClassName sc = jc.getSuperClass();
86 String sc = jc.getSuperClassName(); // with _
88 out.append("\n var p = ").append(className)
89 .append(".prototype = ").
90 append(sc.replace('/', '_')).append("(true);");
92 out.append("\n var p = ").append(className).append(".prototype;");
94 for (MethodData m : jc.getMethods()) {
96 generateStaticMethod("\n p.", m, toInitilize);
98 generateInstanceMethod("\n p.", m);
101 out.append("\n p.$instOf_").append(className).append(" = true;");
102 for (String superInterface : jc.getSuperInterfaces()) {
103 out.append("\n p.$instOf_").append(superInterface.replace('/', '_')).append(" = true;");
106 out.append("\n if (arguments.length === 0) {");
107 for (FieldData v : jc.getFields()) {
109 out.append("\n this.fld_").
110 append(v.getName()).append(initField(v));
113 out.append("\n return this;");
115 out.append("\n return new ").append(className).append(";");
117 out.append("\n").append(className).append("(true);");
118 StringBuilder sb = new StringBuilder();
119 for (String init : toInitilize.toArray()) {
120 sb.append("\n").append(init).append("();");
122 return sb.toString();
124 private void generateStaticMethod(String prefix, MethodData m, StringArray toInitilize) throws IOException {
125 if (javaScriptBody(prefix, m, true)) {
128 StringBuilder argsCnt = new StringBuilder();
129 final String mn = findMethodName(m, argsCnt);
130 out.append(prefix).append(mn).append(" = function");
131 if (mn.equals("classV")) {
132 toInitilize.add(className(jc) + "(true)." + mn);
136 for (int index = 0, i = 0; i < argsCnt.length(); i++) {
138 out.append("arg").append(String.valueOf(index));
140 final String desc = null;// XXX findDescriptor(args.get(i).getDescriptor());
141 if (argsCnt.charAt(i) == '1') {
147 out.append(") {").append("\n");
148 final byte[] code = m.getCode();
150 int len = m.getMaxLocals();
151 for (int index = argsCnt.length(), i = argsCnt.length(); i < len; i++) {
153 out.append("arg").append(String.valueOf(i)).append(";\n");
155 out.append(" var stack = new Array();\n");
158 out.append(" /* no code found for ").append(m.getInternalSig()).append(" */\n");
163 private void generateInstanceMethod(String prefix, MethodData m) throws IOException {
164 if (javaScriptBody(prefix, m, false)) {
167 StringBuilder argsCnt = new StringBuilder();
168 final String mn = findMethodName(m, argsCnt);
169 out.append(prefix).append(mn).append(" = function");
172 for (int index = 1, i = 0; i < argsCnt.length(); i++) {
174 out.append("arg").append(String.valueOf(index));
175 if (argsCnt.charAt(i) == '1') {
181 out.append(") {").append("\n");
182 final byte[] code = m.getCode();
184 int len = m.getMaxLocals();
185 for (int index = argsCnt.length(), i = argsCnt.length(); i < len; i++) {
187 out.append("arg").append(String.valueOf(i + 1)).append(";\n");
189 out.append(";\n var stack = new Array();\n");
192 out.append(" /* no code found for ").append(m.getInternalSig()).append(" */\n");
197 private void produceCode(byte[] byteCodes) throws IOException {
198 out.append("\n var gt = 0;\n for(;;) switch(gt) {\n");
199 for (int i = 0; i < byteCodes.length; i++) {
201 out.append(" case " + i).append(": ");
202 final int c = readByte(byteCodes, i);
209 out.append("stack.push(arg0);");
216 out.append("stack.push(arg1);");
223 out.append("stack.push(arg2);");
230 out.append("stack.push(arg3);");
237 final int indx = readByte(byteCodes, ++i);
238 out.append("stack.push(arg").append(indx + ");");
246 final int indx = readByte(byteCodes, ++i);
247 out.append("arg" + indx).append(" = stack.pop();");
255 out.append("arg0 = stack.pop();");
262 out.append("arg1 = stack.pop();");
269 out.append("arg2 = stack.pop();");
276 out.append("arg3 = stack.pop();");
282 out.append("stack.push(stack.pop() + stack.pop());");
288 out.append("{ var tmp = stack.pop(); stack.push(stack.pop() - tmp); }");
294 out.append("stack.push(stack.pop() * stack.pop());");
298 out.append("{ var tmp = stack.pop(); stack.push(Math.floor(stack.pop() / tmp)); }");
302 out.append("{ var tmp = stack.pop(); stack.push(stack.pop() / tmp); }");
308 out.append("{ var d = stack.pop(); stack.push(stack.pop() % d); }");
312 out.append("stack.push(stack.pop() & stack.pop());");
316 out.append("stack.push(stack.pop() | stack.pop());");
320 out.append("stack.push(stack.pop() ^ stack.pop());");
326 out.append("stack.push(- stack.pop());");
330 out.append("{ var v = stack.pop(); stack.push(stack.pop() << v); }");
334 out.append("{ var v = stack.pop(); stack.push(stack.pop() >> v); }");
338 out.append("{ var v = stack.pop(); stack.push(stack.pop() >>> v); }");
341 final int varIndx = readByte(byteCodes, ++i);
342 final int incrBy = byteCodes[++i];
344 out.append("arg" + varIndx).append("++;");
346 out.append("arg" + varIndx).append(" += " + incrBy).append(";");
351 out.append("return;");
358 out.append("return stack.pop();");
369 out.append("/* number conversion */");
375 out.append("stack.push(Math.floor(stack.pop()));");
380 out.append("/* number conversion */");
382 case opc_aconst_null:
383 out.append("stack.push(null);");
386 out.append("stack.push(-1);");
392 out.append("stack.push(0);");
398 out.append("stack.push(1);");
402 out.append("stack.push(2);");
405 out.append("stack.push(3);");
408 out.append("stack.push(4);");
411 out.append("stack.push(5);");
414 int indx = readByte(byteCodes, ++i);
415 String v = encodeConstant(indx);
416 out.append("stack.push(").append(v).append(");");
421 int indx = readIntArg(byteCodes, i);
423 String v = encodeConstant(indx);
424 out.append("stack.push(").append(v).append(");");
432 out.append("{ var delta = stack.pop() - stack.pop(); stack.push(delta < 0 ?-1 : (delta == 0 ? 0 : 1)); }");
436 i = generateIf(byteCodes, i, "===");
439 i = generateIf(byteCodes, i, "!=");
441 case opc_if_icmpeq: {
442 i = generateIf(byteCodes, i, "==");
446 int indx = i + readIntArg(byteCodes, i);
447 out.append("if (stack.pop() == 0) { gt = " + indx);
448 out.append("; continue; }");
453 int indx = i + readIntArg(byteCodes, i);
454 out.append("if (stack.pop() != 0) { gt = " + indx);
455 out.append("; continue; }");
460 int indx = i + readIntArg(byteCodes, i);
461 out.append("if (stack.pop() < 0) { gt = " + indx);
462 out.append("; continue; }");
467 int indx = i + readIntArg(byteCodes, i);
468 out.append("if (stack.pop() <= 0) { gt = " + indx);
469 out.append("; continue; }");
474 int indx = i + readIntArg(byteCodes, i);
475 out.append("if (stack.pop() > 0) { gt = " + indx);
476 out.append("; continue; }");
481 int indx = i + readIntArg(byteCodes, i);
482 out.append("if (stack.pop() >= 0) { gt = " + indx);
483 out.append("; continue; }");
487 case opc_ifnonnull: {
488 int indx = i + readIntArg(byteCodes, i);
489 out.append("if (stack.pop() !== null) { gt = " + indx);
490 out.append("; continue; }");
495 int indx = i + readIntArg(byteCodes, i);
496 out.append("if (stack.pop() === null) { gt = " + indx);
497 out.append("; continue; }");
502 i = generateIf(byteCodes, i, "!=");
505 i = generateIf(byteCodes, i, ">");
508 i = generateIf(byteCodes, i, ">=");
511 i = generateIf(byteCodes, i, "<");
514 i = generateIf(byteCodes, i, "<=");
517 int indx = i + readIntArg(byteCodes, i);
518 out.append("gt = " + indx).append("; continue;");
522 case opc_lookupswitch: {
523 int table = i / 4 * 4 + 4;
524 int dflt = i + readInt4(byteCodes, table);
526 int n = readInt4(byteCodes, table);
528 out.append("switch (stack.pop()) {\n");
530 int cnstnt = readInt4(byteCodes, table);
532 int offset = i + readInt4(byteCodes, table);
534 out.append(" case " + cnstnt).append(": gt = " + offset).append("; continue;\n");
536 out.append(" default: gt = " + dflt).append("; continue;\n}");
540 case opc_tableswitch: {
541 int table = i / 4 * 4 + 4;
542 int dflt = i + readInt4(byteCodes, table);
544 int low = readInt4(byteCodes, table);
546 int high = readInt4(byteCodes, table);
548 out.append("switch (stack.pop()) {\n");
549 while (low <= high) {
550 int offset = i + readInt4(byteCodes, table);
552 out.append(" case " + low).append(": gt = " + offset).append("; continue;\n");
555 out.append(" default: gt = " + dflt).append("; continue;\n}");
559 case opc_invokeinterface: {
560 i = invokeVirtualMethod(byteCodes, i) + 2;
563 case opc_invokevirtual:
564 i = invokeVirtualMethod(byteCodes, i);
566 case opc_invokespecial:
567 i = invokeStaticMethod(byteCodes, i, false);
569 case opc_invokestatic:
570 i = invokeStaticMethod(byteCodes, i, true);
573 int indx = readIntArg(byteCodes, i);
574 String ci = jc.getClassName(indx);
575 out.append("stack.push(");
576 out.append("new ").append(ci.replace('/','_'));
583 int type = byteCodes[i++];
584 out.append("stack.push(new Array(stack.pop()).fillNulls());");
587 case opc_anewarray: {
588 i += 2; // skip type of array
589 out.append("stack.push(new Array(stack.pop()).fillNulls());");
592 case opc_multianewarray: {
594 int dim = readByte(byteCodes, ++i);
595 out.append("{ var a0 = new Array(stack.pop()).fillNulls();");
596 for (int d = 1; d < dim; d++) {
597 out.append("\n var l" + d).append(" = stack.pop();");
598 out.append("\n for (var i" + d).append (" = 0; i" + d).
599 append(" < a" + (d - 1)).
600 append(".length; i" + d).append("++) {");
601 out.append("\n var a" + d).
602 append (" = new Array(l" + d).append(").fillNulls();");
603 out.append("\n a" + (d - 1)).append("[i" + d).append("] = a" + d).
606 for (int d = 1; d < dim; d++) {
609 out.append("\nstack.push(a0); }");
612 case opc_arraylength:
613 out.append("stack.push(stack.pop().length);");
623 out.append("{ var value = stack.pop(); var indx = stack.pop(); stack.pop()[indx] = value; }");
634 out.append("{ var indx = stack.pop(); stack.push(stack.pop()[indx]); }");
638 out.append("stack.pop();");
640 out.append("stack.pop();");
643 out.append("stack.push(stack[stack.length - 1]);");
646 out.append("{ var v1 = stack.pop(); var v2 = stack.pop(); stack.push(v1); stack.push(v2); stack.push(v1); }");
649 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); }");
652 out.append("stack.push(" + byteCodes[++i] + ");");
655 out.append("stack.push(" + readIntArg(byteCodes, i) + ");");
659 int indx = readIntArg(byteCodes, i);
660 String[] fi = jc.getFieldInfoName(indx);
661 out.append("stack.push(stack.pop().fld_").
662 append(fi[1]).append(");");
666 case opc_getstatic: {
667 int indx = readIntArg(byteCodes, i);
668 String[] fi = jc.getFieldInfoName(indx);
669 out.append("stack.push(").append(fi[0].replace('/', '_'));
670 out.append('.').append(fi[1]).append(");");
675 case opc_putstatic: {
676 int indx = readIntArg(byteCodes, i);
677 String[] fi = jc.getFieldInfoName(indx);
678 out.append(fi[0].replace('/', '_'));
679 out.append('.').append(fi[1]).append(" = stack.pop();");
685 int indx = readIntArg(byteCodes, i);
686 String[] fi = jc.getFieldInfoName(indx);
687 out.append("{ var v = stack.pop(); stack.pop().fld_")
688 .append(fi[1]).append(" = v; }");
692 case opc_checkcast: {
693 int indx = readIntArg(byteCodes, i);
694 final String type = jc.getClassName(indx);
695 if (!type.startsWith("[")) {
696 // no way to check arrays right now
697 out.append("if(stack[stack.length - 1].$instOf_")
698 .append(type.replace('/', '_'))
699 .append(" != 1) throw {};"); // XXX proper exception
704 case opc_instanceof: {
705 int indx = readIntArg(byteCodes, i);
706 final String type = jc.getClassName(indx);
707 out.append("stack.push(stack.pop().$instOf_")
708 .append(type.replace('/', '_'))
709 .append(" ? 1 : 0);");
714 out.append("{ var t = stack.pop(); stack = new Array(1); stack[0] = t; throw t; }");
718 out.append("throw 'unknown bytecode " + c + "';");
723 for (int j = prev; j <= i; j++) {
725 final int cc = readByte(byteCodes, j);
726 out.append(Integer.toString(cc));
733 private int generateIf(byte[] byteCodes, int i, final String test) throws IOException {
734 int indx = i + readIntArg(byteCodes, i);
735 out.append("if (stack.pop() ").append(test).append(" stack.pop()) { gt = " + indx);
736 out.append("; continue; }");
740 private int readIntArg(byte[] byteCodes, int offsetInstruction) {
741 final int indxHi = byteCodes[offsetInstruction + 1] << 8;
742 final int indxLo = byteCodes[offsetInstruction + 2];
743 return (indxHi & 0xffffff00) | (indxLo & 0xff);
745 private int readInt4(byte[] byteCodes, int offsetInstruction) {
746 final int d = byteCodes[offsetInstruction + 0] << 24;
747 final int c = byteCodes[offsetInstruction + 1] << 16;
748 final int b = byteCodes[offsetInstruction + 2] << 8;
749 final int a = byteCodes[offsetInstruction + 3];
750 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
752 private int readByte(byte[] byteCodes, int offsetInstruction) {
753 return (byteCodes[offsetInstruction] + 256) % 256;
756 private static void countArgs(String descriptor, boolean[] hasReturnType, StringBuilder sig, StringBuilder cnt) {
758 Boolean count = null;
759 boolean array = false;
760 int firstPos = sig.length();
761 while (i < descriptor.length()) {
762 char ch = descriptor.charAt(i++);
786 if (ch == 'J' || ch == 'D') {
792 hasReturnType[0] = true;
793 sig.insert(firstPos, ch);
795 sig.insert(firstPos, 'A');
802 hasReturnType[0] = false;
803 sig.insert(firstPos, 'V');
806 int next = descriptor.indexOf(';', i);
812 sig.append(descriptor.substring(i, next).replace('/', '_'));
815 sig.insert(firstPos, descriptor.substring(i, next).replace('/', '_'));
816 sig.insert(firstPos, ch);
818 sig.insert(firstPos, 'A');
820 hasReturnType[0] = true;
828 break; // invalid character
833 private void generateStaticField(FieldData v) throws IOException {
835 .append(className(jc))
836 .append('.').append(v.getName()).append(initField(v));
839 private String findMethodName(MethodData m, StringBuilder cnt) {
840 StringBuilder name = new StringBuilder();
841 if ("<init>".equals(m.getName())) { // NOI18N
842 name.append("cons"); // NOI18N
843 } else if ("<clinit>".equals(m.getName())) { // NOI18N
844 name.append("class"); // NOI18N
846 name.append(m.getName());
849 boolean hasReturn[] = { false };
850 countArgs(findDescriptor(m.getInternalSig()), hasReturn, name, cnt);
851 return name.toString();
854 private String findMethodName(String[] mi, StringBuilder cnt, boolean[] hasReturn) {
855 StringBuilder name = new StringBuilder();
856 String descr = mi[2];//mi.getDescriptor();
858 if ("<init>".equals(nm)) { // NOI18N
859 name.append("cons"); // NOI18N
863 countArgs(findDescriptor(descr), hasReturn, name, cnt);
864 return name.toString();
867 private int invokeStaticMethod(byte[] byteCodes, int i, boolean isStatic)
869 int methodIndex = readIntArg(byteCodes, i);
870 String[] mi = jc.getFieldInfoName(methodIndex);
871 boolean[] hasReturn = { false };
872 StringBuilder cnt = new StringBuilder();
873 String mn = findMethodName(mi, cnt, hasReturn);
875 for (int j = cnt.length() - 1; j >= 0; j--) {
876 out.append("var v" + j).append(" = stack.pop(); ");
880 out.append("stack.push(");
882 final String in = mi[0];
883 out.append(in.replace('/', '_'));
884 out.append(".prototype.");
889 out.append("stack.pop()");
892 for (int j = 0; j < cnt.length(); j++) {
906 private int invokeVirtualMethod(byte[] byteCodes, int i)
908 int methodIndex = readIntArg(byteCodes, i);
909 String[] mi = jc.getFieldInfoName(methodIndex);
910 boolean[] hasReturn = { false };
911 StringBuilder cnt = new StringBuilder();
912 String mn = findMethodName(mi, cnt, hasReturn);
914 for (int j = cnt.length() - 1; j >= 0; j--) {
915 out.append("var v" + j).append(" = stack.pop(); ");
917 out.append("var self = stack.pop(); ");
919 out.append("stack.push(");
925 for (int j = 0; j < cnt.length(); j++) {
938 private void addReference(String cn) throws IOException {
939 if (requireReference(cn)) {
940 out.append(" /* needs ").append(cn).append(" */");
944 private void outType(String d, StringBuilder out) {
946 while (d.charAt(0) == '[') {
950 if (d.charAt(0) == 'L') {
951 assert d.charAt(d.length() - 1) == ';';
952 out.append(d.replace('/', '_').substring(0, d.length() - 1));
958 private String encodeConstant(int entryIndex) {
959 String s = jc.stringValue(entryIndex, true);
963 private String findDescriptor(String d) {
964 return d.replace('[', 'A');
967 private boolean javaScriptBody(String prefix, MethodData m, boolean isStatic) throws IOException {
968 byte[] arr = m.findAnnotationData(true);
972 final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
973 class P extends AnnotationParser {
975 String[] args = new String[30];
979 protected void visitAttr(String type, String attr, String value) {
980 if (type.equals(jvmType)) {
981 if ("body".equals(attr)) {
983 } else if ("args".equals(attr)) {
986 throw new IllegalArgumentException(attr);
993 if (p.body == null) {
996 StringBuilder cnt = new StringBuilder();
997 out.append(prefix).append(findMethodName(m, cnt));
998 out.append(" = function(");
1002 out.append(p.args[0]);
1009 for (int i = 0; i < cnt.length(); i++) {
1011 out.append(p.args[index]);
1015 out.append(") {").append("\n");
1017 out.append("\n}\n");
1020 private static String className(ClassData jc) {
1021 //return jc.getName().getInternalName().replace('/', '_');
1022 return jc.getClassName().replace('/', '_');
1025 private static String[] findAnnotation(
1026 byte[] arr, ClassData cd, final String className,
1027 final String... attrNames
1028 ) throws IOException {
1032 final String[] values = new String[attrNames.length];
1033 final boolean[] found = { false };
1034 final String jvmType = "L" + className.replace('.', '/') + ";";
1035 AnnotationParser ap = new AnnotationParser() {
1037 protected void visitAttr(String type, String attr, String value) {
1038 if (type.equals(jvmType)) {
1040 for (int i = 0; i < attrNames.length; i++) {
1041 if (attrNames[i].equals(attr)) {
1050 return found[0] ? values : null;
1053 private CharSequence initField(FieldData v) {
1054 final String is = v.getInternalSig();
1055 if (is.length() == 1) {
1056 switch (is.charAt(0)) {
1062 case 'I': return " = 0;";
1064 case 'D': return " = 0.0;";
1066 throw new IllegalStateException(is);