Almost rewritten to javap: @JavaScriptBody and double/long may not yet be supported
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 java.util.ArrayList;
23 import java.util.Collection;
24 import java.util.List;
25 import org.apidesign.bck2brwsr.core.ExtraJavaScript;
26 import org.apidesign.bck2brwsr.core.JavaScriptBody;
27 import sun.tools.javap.ClassData;
28 import sun.tools.javap.FieldData;
29 import sun.tools.javap.MethodData;
30 import static sun.tools.javap.RuntimeConstants.*;
32 /** Translator of the code inside class files to JavaScript.
34 * @author Jaroslav Tulach <jtulach@netbeans.org>
36 public final class ByteCodeToJavaScript {
37 private final ClassData jc;
38 private final Appendable out;
39 private final Collection<? super String> references;
41 private ByteCodeToJavaScript(
42 ClassData jc, Appendable out, Collection<? super String> references
46 this.references = references;
50 * Converts a given class file to a JavaScript version.
52 * @param classFile input stream with code of the .class file
53 * @param out a {@link StringBuilder} or similar to generate the output to
54 * @param references a write only collection where the system adds list of
55 * other classes that were referenced and should be loaded in order the
56 * generated JavaScript code works properly. The names are in internal
57 * JVM form so String is <code>java/lang/String</code>. Can be <code>null</code>
58 * if one is not interested in knowing references
59 * @param scripts write only collection with names of resources to read
60 * @return the initialization code for this class, if any. Otherwise <code>null</code>
62 * @throws IOException if something goes wrong during read or write or translating
65 public static String compile(
66 InputStream classFile, Appendable out,
67 Collection<? super String> references,
68 Collection<? super String> scripts
69 ) throws IOException {
70 ClassData jc = new ClassData(classFile);
72 final ClassName extraAnn = ClassName.getClassName(ExtraJavaScript.class.getName().replace('.', '/'));
73 Annotation a = jc.getAnnotation(extraAnn);
75 final ElementValue annVal = a.getComponent("resource").getValue();
76 String res = ((PrimitiveElementValue)annVal).getValue().getValue().toString();
78 final AnnotationComponent process = a.getComponent("processByteCode");
79 if (process != null && "const=0".equals(process.getValue().toString())) {
84 ByteCodeToJavaScript compiler = new ByteCodeToJavaScript(
87 List<String> toInitilize = new ArrayList<String>();
88 for (MethodData m : jc.getMethods()) {
90 compiler.generateStaticMethod(m, toInitilize);
92 compiler.generateInstanceMethod(m);
95 for (FieldData v : jc.getFields()) {
97 compiler.generateStaticField(v);
101 final String className = className(jc);
102 out.append("\nfunction ").append(className);
104 for (FieldData v : jc.getFields()) {
106 out.append("\n this.fld_").
107 append(v.getName()).append(" = 0;");
110 out.append("\n}\n\nfunction ").append(className).append("_proto() {");
111 out.append("\n if (").append(className).
112 append(".prototype.$instOf_").append(className).append(") {");
113 out.append("\n return new ").append(className).append(";");
115 // ClassName sc = jc.getSuperClass();
116 String sc = jc.getSuperClassName(); // with _
118 out.append("\n var p = ").append(className)
119 .append(".prototype = ").
120 append(sc.replace('/', '_')).append("_proto();");
122 out.append("\n var p = ").append(className).append(".prototype;");
124 for (MethodData m : jc.getMethods()) {
125 if (!m.getName().contains("<init>") && !m.getName().contains("<cinit>")) {
126 compiler.generateMethodReference("\n p.", m);
129 out.append("\n p.$instOf_").append(className).append(" = true;");
130 for (String superInterface : jc.getSuperInterfaces()) {
131 out.append("\n p.$instOf_").append(superInterface.replace('/', '_')).append(" = true;");
133 out.append("\n return new ").append(className).append(";");
135 out.append("\n").append(className).append("_proto();");
136 StringBuilder sb = new StringBuilder();
137 for (String init : toInitilize) {
138 sb.append("\n").append(init).append("();");
140 return sb.toString();
142 private void generateStaticMethod(MethodData m, List<String> toInitilize) throws IOException {
143 if (javaScriptBody(m, true)) {
146 int[] argsCnt = { -1 };
147 final String mn = findMethodName(m, argsCnt);
148 out.append("\nfunction ").append(
150 ).append('_').append(mn);
151 if (mn.equals("classV")) {
152 toInitilize.add(className(jc) + '_' + mn);
156 for (int index = 0, i = 0; i < argsCnt[0]; i++) {
158 out.append("arg").append(String.valueOf(index));
160 final String desc = null;// XXX findDescriptor(args.get(i).getDescriptor());
161 if ("D".equals(desc) || "J".equals(desc)) {
167 out.append(") {").append("\n");
168 final byte[] code = m.getCode();
170 int len = m.getMaxLocals();
171 for (int index = argsCnt[0], i = argsCnt[0]; i < len; i++) {
173 out.append("arg").append(String.valueOf(i)).append(";\n");
175 out.append(" var stack = new Array();\n");
178 out.append(" /* no code found for ").append(m.getInternalSig()).append(" */\n");
183 private void generateMethodReference(String prefix, MethodData m) throws IOException {
184 final String name = findMethodName(m, null);
185 out.append(prefix).append(name).append(" = ")
186 .append(className(jc))
187 .append('_').append(name).append(";");
190 private void generateInstanceMethod(MethodData m) throws IOException {
191 if (javaScriptBody(m, false)) {
194 int[] argsCnt = { -1 };
195 out.append("\nfunction ").append(
197 ).append('_').append(findMethodName(m, argsCnt));
200 for (int index = 1, i = 0; i < argsCnt[0]; i++) {
202 out.append("arg").append(String.valueOf(index));
203 final String desc = null;// XXX findDescriptor(args.get(i).getDescriptor());
204 if ("D".equals(desc) || "J".equals(desc)) {
210 out.append(") {").append("\n");
211 final byte[] code = m.getCode();
213 int len = m.getMaxLocals();
214 for (int index = argsCnt[0], i = argsCnt[0]; i < len; i++) {
216 out.append("arg").append(String.valueOf(i + 1)).append(";\n");
218 out.append(";\n var stack = new Array();\n");
221 out.append(" /* no code found for ").append(m.getInternalSig()).append(" */\n");
226 private void produceCode(byte[] byteCodes) throws IOException {
227 out.append("\n var gt = 0;\n for(;;) switch(gt) {\n");
228 for (int i = 0; i < byteCodes.length; i++) {
230 out.append(" case " + i).append(": ");
231 final int c = readByte(byteCodes, i);
238 out.append("stack.push(arg0);");
245 out.append("stack.push(arg1);");
252 out.append("stack.push(arg2);");
259 out.append("stack.push(arg3);");
266 final int indx = readByte(byteCodes, ++i);
267 out.append("stack.push(arg").append(indx + ");");
275 final int indx = readByte(byteCodes, ++i);
276 out.append("arg" + indx).append(" = stack.pop();");
284 out.append("arg0 = stack.pop();");
291 out.append("arg1 = stack.pop();");
298 out.append("arg2 = stack.pop();");
305 out.append("arg3 = stack.pop();");
311 out.append("stack.push(stack.pop() + stack.pop());");
317 out.append("{ var tmp = stack.pop(); stack.push(stack.pop() - tmp); }");
323 out.append("stack.push(stack.pop() * stack.pop());");
327 out.append("{ var tmp = stack.pop(); stack.push(Math.floor(stack.pop() / tmp)); }");
331 out.append("{ var tmp = stack.pop(); stack.push(stack.pop() / tmp); }");
335 out.append("stack.push(stack.pop() & stack.pop());");
339 out.append("stack.push(stack.pop() | stack.pop());");
343 out.append("stack.push(stack.pop() ^ stack.pop());");
349 out.append("stack.push(- stack.pop());");
353 out.append("{ var v = stack.pop(); stack.push(stack.pop() << v); }");
357 out.append("{ var v = stack.pop(); stack.push(stack.pop() >> v); }");
361 out.append("{ var v = stack.pop(); stack.push(stack.pop() >>> v); }");
364 final int varIndx = readByte(byteCodes, ++i);
365 final int incrBy = byteCodes[++i];
367 out.append("arg" + varIndx).append("++;");
369 out.append("arg" + varIndx).append(" += " + incrBy).append(";");
374 out.append("return;");
381 out.append("return stack.pop();");
392 out.append("/* number conversion */");
398 out.append("stack.push(Math.floor(stack.pop()));");
403 out.append("/* number conversion */");
405 case opc_aconst_null:
406 out.append("stack.push(null);");
409 out.append("stack.push(-1);");
415 out.append("stack.push(0);");
421 out.append("stack.push(1);");
425 out.append("stack.push(2);");
428 out.append("stack.push(3);");
431 out.append("stack.push(4);");
434 out.append("stack.push(5);");
437 int indx = readByte(byteCodes, ++i);
438 String v = encodeConstant(indx);
439 out.append("stack.push(").append(v).append(");");
444 int indx = readIntArg(byteCodes, i);
446 String v = encodeConstant(indx);
447 out.append("stack.push(").append(v).append(");");
455 out.append("{ var delta = stack.pop() - stack.pop(); stack.push(delta < 0 ?-1 : (delta == 0 ? 0 : 1)); }");
459 i = generateIf(byteCodes, i, "===");
462 i = generateIf(byteCodes, i, "!=");
464 case opc_if_icmpeq: {
465 i = generateIf(byteCodes, i, "==");
469 int indx = i + readIntArg(byteCodes, i);
470 out.append("if (stack.pop() == 0) { gt = " + indx);
471 out.append("; continue; }");
476 int indx = i + readIntArg(byteCodes, i);
477 out.append("if (stack.pop() != 0) { gt = " + indx);
478 out.append("; continue; }");
483 int indx = i + readIntArg(byteCodes, i);
484 out.append("if (stack.pop() < 0) { gt = " + indx);
485 out.append("; continue; }");
490 int indx = i + readIntArg(byteCodes, i);
491 out.append("if (stack.pop() <= 0) { gt = " + indx);
492 out.append("; continue; }");
497 int indx = i + readIntArg(byteCodes, i);
498 out.append("if (stack.pop() > 0) { gt = " + indx);
499 out.append("; continue; }");
504 int indx = i + readIntArg(byteCodes, i);
505 out.append("if (stack.pop() >= 0) { gt = " + indx);
506 out.append("; continue; }");
510 case opc_ifnonnull: {
511 int indx = i + readIntArg(byteCodes, i);
512 out.append("if (stack.pop()) { gt = " + indx);
513 out.append("; continue; }");
518 int indx = i + readIntArg(byteCodes, i);
519 out.append("if (!stack.pop()) { gt = " + indx);
520 out.append("; continue; }");
525 i = generateIf(byteCodes, i, "!=");
528 i = generateIf(byteCodes, i, ">");
531 i = generateIf(byteCodes, i, ">=");
534 i = generateIf(byteCodes, i, "<");
537 i = generateIf(byteCodes, i, "<=");
540 int indx = i + readIntArg(byteCodes, i);
541 out.append("gt = " + indx).append("; continue;");
545 case opc_lookupswitch: {
546 int table = i / 4 * 4 + 4;
547 int dflt = i + readInt4(byteCodes, table);
549 int n = readInt4(byteCodes, table);
551 out.append("switch (stack.pop()) {\n");
553 int cnstnt = readInt4(byteCodes, table);
555 int offset = i + readInt4(byteCodes, table);
557 out.append(" case " + cnstnt).append(": gt = " + offset).append("; continue;\n");
559 out.append(" default: gt = " + dflt).append("; continue;\n}");
563 case opc_tableswitch: {
564 int table = i / 4 * 4 + 4;
565 int dflt = i + readInt4(byteCodes, table);
567 int low = readInt4(byteCodes, table);
569 int high = readInt4(byteCodes, table);
571 out.append("switch (stack.pop()) {\n");
572 while (low <= high) {
573 int offset = i + readInt4(byteCodes, table);
575 out.append(" case " + low).append(": gt = " + offset).append("; continue;\n");
578 out.append(" default: gt = " + dflt).append("; continue;\n}");
582 case opc_invokeinterface: {
583 i = invokeVirtualMethod(byteCodes, i) + 2;
586 case opc_invokevirtual:
587 i = invokeVirtualMethod(byteCodes, i);
589 case opc_invokespecial:
590 i = invokeStaticMethod(byteCodes, i, false);
592 case opc_invokestatic:
593 i = invokeStaticMethod(byteCodes, i, true);
596 int indx = readIntArg(byteCodes, i);
597 String ci = jc.getClassName(indx);
598 out.append("stack.push(");
599 out.append("new ").append(ci.replace('/','_'));
606 int type = byteCodes[i++];
607 out.append("stack.push(new Array(stack.pop()));");
610 case opc_anewarray: {
611 i += 2; // skip type of array
612 out.append("stack.push(new Array(stack.pop()));");
615 case opc_multianewarray: {
617 int dim = readByte(byteCodes, ++i);
618 out.append("{ var a0 = new Array(stack.pop());");
619 for (int d = 1; d < dim; d++) {
620 out.append("\n var l" + d).append(" = stack.pop();");
621 out.append("\n for (var i" + d).append (" = 0; i" + d).
622 append(" < a" + (d - 1)).
623 append(".length; i" + d).append("++) {");
624 out.append("\n var a" + d).
625 append (" = new Array(l" + d).append(");");
626 out.append("\n a" + (d - 1)).append("[i" + d).append("] = a" + d).
629 for (int d = 1; d < dim; d++) {
632 out.append("\nstack.push(a0); }");
635 case opc_arraylength:
636 out.append("stack.push(stack.pop().length);");
646 out.append("{ var value = stack.pop(); var indx = stack.pop(); stack.pop()[indx] = value; }");
657 out.append("{ var indx = stack.pop(); stack.push(stack.pop()[indx]); }");
661 out.append("stack.pop();");
663 out.append("stack.pop();");
666 out.append("stack.push(stack[stack.length - 1]);");
669 out.append("stack.push(" + byteCodes[++i] + ");");
672 out.append("stack.push(" + readIntArg(byteCodes, i) + ");");
676 int indx = readIntArg(byteCodes, i);
677 String[] fi = jc.getFieldInfoName(indx);
678 out.append("stack.push(stack.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("stack.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(" = stack.pop();");
702 int indx = readIntArg(byteCodes, i);
703 String[] fi = jc.getFieldInfoName(indx);
704 out.append("{ var v = stack.pop(); stack.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(stack[stack.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("stack.push(stack.pop().$instOf_")
725 .append(type.replace('/', '_'))
726 .append(" ? 1 : 0);");
731 out.append("{ var t = stack.pop(); stack = new Array(1); stack[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 (stack.pop() ").append(test).append(" stack.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 int countArgs(String descriptor, boolean[] hasReturnType, StringBuilder sig) {
776 Boolean count = null;
777 boolean array = false;
778 int firstPos = sig.length();
779 while (i < descriptor.length()) {
780 char ch = descriptor.charAt(i++);
806 hasReturnType[0] = true;
807 sig.insert(firstPos, ch);
809 sig.insert(firstPos, 'A');
816 hasReturnType[0] = false;
817 sig.insert(firstPos, 'V');
820 int next = descriptor.indexOf(';', i);
827 sig.append(descriptor.substring(i, next).replace('/', '_'));
829 sig.insert(firstPos, descriptor.substring(i, next).replace('/', '_'));
830 sig.insert(firstPos, ch);
832 sig.insert(firstPos, 'A');
834 hasReturnType[0] = true;
842 break; // invalid character
848 private void generateStaticField(FieldData v) throws IOException {
850 .append(className(jc))
851 .append('_').append(v.getName()).append(" = 0;");
854 private String findMethodName(MethodData m, int[] cnt) {
855 StringBuilder name = new StringBuilder();
856 if ("<init>".equals(m.getName())) { // NOI18N
857 name.append("cons"); // NOI18N
858 } else if ("<clinit>".equals(m.getName())) { // NOI18N
859 name.append("class"); // NOI18N
861 name.append(m.getName());
864 boolean hasReturn[] = { false };
865 int argsCnt = countArgs(findDescriptor(m.getInternalSig()), hasReturn, name);
869 return name.toString();
872 private String findMethodName(String[] mi, int[] cnt, boolean[] hasReturn) {
873 StringBuilder name = new StringBuilder();
874 String descr = mi[2];//mi.getDescriptor();
876 if ("<init>".equals(nm)) { // NOI18N
877 name.append("cons"); // NOI18N
881 cnt[0] = countArgs(findDescriptor(descr), hasReturn, name);
882 return name.toString();
885 private int invokeStaticMethod(byte[] byteCodes, int i, boolean isStatic)
887 int methodIndex = readIntArg(byteCodes, i);
888 String[] mi = jc.getFieldInfoName(methodIndex);
889 boolean[] hasReturn = { false };
891 String mn = findMethodName(mi, cnt, hasReturn);
893 for (int j = cnt[0] - 1; j >= 0; j--) {
894 out.append("var v" + j).append(" = stack.pop(); ");
898 out.append("stack.push(");
900 final String in = mi[0];
901 out.append(in.replace('/', '_'));
903 out.append(".prototype.");
911 out.append("stack.pop()");
914 for (int j = 0; j < cnt[0]; j++) {
928 private int invokeVirtualMethod(byte[] byteCodes, int i)
930 int methodIndex = readIntArg(byteCodes, i);
931 String[] mi = jc.getFieldInfoName(methodIndex);
932 boolean[] hasReturn = { false };
934 String mn = findMethodName(mi, cnt, hasReturn);
936 for (int j = cnt[0] - 1; j >= 0; j--) {
937 out.append("var v" + j).append(" = stack.pop(); ");
939 out.append("var self = stack.pop(); ");
941 out.append("stack.push(");
947 for (int j = 0; j < cnt[0]; j++) {
960 private void addReference(String cn) throws IOException {
961 if (references != null) {
962 if (references.add(cn)) {
963 out.append(" /* needs ").append(cn).append(" */");
968 private void outType(String d, StringBuilder out) {
970 while (d.charAt(0) == '[') {
974 if (d.charAt(0) == 'L') {
975 assert d.charAt(d.length() - 1) == ';';
976 out.append(d.replace('/', '_').substring(0, d.length() - 1));
982 private String encodeConstant(int entryIndex) {
983 String s = jc.stringValue(entryIndex, true);
987 private String findDescriptor(String d) {
988 return d.replace('[', 'A');
991 private boolean javaScriptBody(MethodData m, boolean isStatic) throws IOException {
994 final ClassName extraAnn = ClassName.getClassName(JavaScriptBody.class.getName().replace('.', '/'));
995 Annotation a = m.getAnnotation(extraAnn);
997 final ElementValue annVal = a.getComponent("body").getValue();
998 String body = ((PrimitiveElementValue) annVal).getValue().getValue().toString();
1000 final ArrayElementValue arrVal = (ArrayElementValue) a.getComponent("args").getValue();
1001 final int len = arrVal.getValues().length;
1002 String[] names = new String[len];
1003 for (int i = 0; i < len; i++) {
1004 names[i] = ((PrimitiveElementValue) arrVal.getValues()[i]).getValue().getValue().toString();
1006 out.append("\nfunction ").append(
1007 jc.getName().getInternalName().replace('/', '_')).append('_').append(findMethodName(m));
1012 out.append(names[0]);
1019 List<Parameter> args = m.getParameters();
1020 for (int i = 0; i < args.size(); i++) {
1022 out.append(names[index]);
1023 final String desc = findDescriptor(args.get(i).getDescriptor());
1027 out.append(") {").append("\n");
1029 out.append("\n}\n");
1035 private static String className(ClassData jc) {
1036 //return jc.getName().getInternalName().replace('/', '_');
1037 return jc.getClassName().replace('/', '_');