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 org.netbeans.modules.classfile.Annotation;
28 import org.netbeans.modules.classfile.AnnotationComponent;
29 import org.netbeans.modules.classfile.ArrayElementValue;
30 import static org.netbeans.modules.classfile.ByteCodes.*;
31 import org.netbeans.modules.classfile.CPClassInfo;
32 import org.netbeans.modules.classfile.CPEntry;
33 import org.netbeans.modules.classfile.CPFieldInfo;
34 import org.netbeans.modules.classfile.CPMethodInfo;
35 import org.netbeans.modules.classfile.CPStringInfo;
36 import org.netbeans.modules.classfile.ClassFile;
37 import org.netbeans.modules.classfile.ClassName;
38 import org.netbeans.modules.classfile.Code;
39 import org.netbeans.modules.classfile.ElementValue;
40 import org.netbeans.modules.classfile.Method;
41 import org.netbeans.modules.classfile.Parameter;
42 import org.netbeans.modules.classfile.PrimitiveElementValue;
43 import org.netbeans.modules.classfile.Variable;
45 /** Translator of the code inside class files to JavaScript.
47 * @author Jaroslav Tulach <jtulach@netbeans.org>
49 public final class ByteCodeToJavaScript {
50 private final ClassFile jc;
51 private final Appendable out;
52 private final Collection<? super String> references;
54 private ByteCodeToJavaScript(
55 ClassFile jc, Appendable out, Collection<? super String> references
59 this.references = references;
63 * Converts a given class file to a JavaScript version.
65 * @param classFile input stream with code of the .class file
66 * @param out a {@link StringBuilder} or similar to generate the output to
67 * @param references a write only collection where the system adds list of
68 * other classes that were referenced and should be loaded in order the
69 * generated JavaScript code works properly. The names are in internal
70 * JVM form so String is <code>java/lang/String</code>. Can be <code>null</code>
71 * if one is not interested in knowing references
72 * @param scripts write only collection with names of resources to read
73 * @return the initialization code for this class, if any. Otherwise <code>null</code>
75 * @throws IOException if something goes wrong during read or write or translating
78 public static String compile(
79 InputStream classFile, Appendable out,
80 Collection<? super String> references,
81 Collection<? super String> scripts
82 ) throws IOException {
83 ClassFile jc = new ClassFile(classFile, true);
84 final ClassName extraAnn = ClassName.getClassName(ExtraJavaScript.class.getName().replace('.', '/'));
85 Annotation a = jc.getAnnotation(extraAnn);
87 final ElementValue annVal = a.getComponent("resource").getValue();
88 String res = ((PrimitiveElementValue)annVal).getValue().getValue().toString();
90 final AnnotationComponent process = a.getComponent("processByteCode");
91 if (process != null && "const=0".equals(process.getValue().toString())) {
96 ByteCodeToJavaScript compiler = new ByteCodeToJavaScript(
99 List<String> toInitilize = new ArrayList<String>();
100 for (Method m : jc.getMethods()) {
102 compiler.generateStaticMethod(m, toInitilize);
104 compiler.generateInstanceMethod(m);
107 for (Variable v : jc.getVariables()) {
109 compiler.generateStaticField(v);
113 final String className = jc.getName().getInternalName().replace('/', '_');
114 out.append("\nfunction ").append(className);
116 for (Variable v : jc.getVariables()) {
118 out.append("\n this.fld_").
119 append(v.getName()).append(" = 0;");
122 out.append("\n}\n\nfunction ").append(className).append("_proto() {");
123 out.append("\n if (").append(className).
124 append(".prototype.$instOf_").append(className).append(") {");
125 out.append("\n return new ").append(className).append(";");
127 ClassName sc = jc.getSuperClass();
129 out.append("\n var p = ").append(className)
130 .append(".prototype = ").
131 append(sc.getInternalName().replace('/', '_')).append("_proto();");
133 out.append("\n var p = ").append(className).append(".prototype;");
135 for (Method m : jc.getMethods()) {
136 if (!m.getName().contains("<init>") && !m.getName().contains("<cinit>")) {
137 compiler.generateMethodReference("\n p.", m);
140 out.append("\n p.$instOf_").append(className).append(" = true;");
141 for (ClassName superInterface : jc.getInterfaces()) {
142 out.append("\n p.$instOf_").append(superInterface.getInternalName().replace('/', '_')).append(" = true;");
144 out.append("\n return new ").append(className).append(";");
146 out.append("\n").append(className).append("_proto();");
147 StringBuilder sb = new StringBuilder();
148 for (String init : toInitilize) {
149 sb.append("\n").append(init).append("();");
151 return sb.toString();
153 private void generateStaticMethod(Method m, List<String> toInitilize) throws IOException {
154 if (javaScriptBody(m, true)) {
157 final String mn = findMethodName(m);
158 out.append("\nfunction ").append(
159 jc.getName().getInternalName().replace('/', '_')
160 ).append('_').append(mn);
161 if (mn.equals("classV")) {
162 toInitilize.add(jc.getName().getInternalName().replace('/', '_') + '_' + mn);
166 List<Parameter> args = m.getParameters();
167 for (int index = 0, i = 0; i < args.size(); i++) {
169 out.append("arg").append(String.valueOf(index));
171 final String desc = findDescriptor(args.get(i).getDescriptor());
172 if ("D".equals(desc) || "J".equals(desc)) {
178 out.append(") {").append("\n");
179 final Code code = m.getCode();
181 int len = code.getMaxLocals();
182 for (int index = args.size(), i = args.size(); i < len; i++) {
184 out.append("arg").append(String.valueOf(i)).append(";\n");
186 out.append(" var stack = new Array();\n");
187 produceCode(code.getByteCodes());
189 out.append(" /* no code found for ").append(m.getTypeSignature()).append(" */\n");
194 private void generateMethodReference(String prefix, Method m) throws IOException {
195 final String name = findMethodName(m);
196 out.append(prefix).append(name).append(" = ")
197 .append(jc.getName().getInternalName().replace('/', '_'))
198 .append('_').append(name).append(";");
201 private void generateInstanceMethod(Method m) throws IOException {
202 if (javaScriptBody(m, false)) {
205 out.append("\nfunction ").append(
206 jc.getName().getInternalName().replace('/', '_')
207 ).append('_').append(findMethodName(m));
210 List<Parameter> args = m.getParameters();
211 for (int index = 1, i = 0; i < args.size(); i++) {
213 out.append("arg").append(String.valueOf(index));
214 final String desc = findDescriptor(args.get(i).getDescriptor());
215 if ("D".equals(desc) || "J".equals(desc)) {
221 out.append(") {").append("\n");
222 final Code code = m.getCode();
224 int len = code.getMaxLocals();
225 for (int index = args.size(), i = args.size(); i < len; i++) {
227 out.append("arg").append(String.valueOf(i + 1)).append(";\n");
229 out.append(";\n var stack = new Array();\n");
230 produceCode(code.getByteCodes());
232 out.append(" /* no code found for ").append(m.getTypeSignature()).append(" */\n");
237 private void produceCode(byte[] byteCodes) throws IOException {
238 out.append("\n var gt = 0;\n for(;;) switch(gt) {\n");
239 for (int i = 0; i < byteCodes.length; i++) {
241 out.append(" case " + i).append(": ");
242 final int c = readByte(byteCodes, i);
249 out.append("stack.push(arg0);");
256 out.append("stack.push(arg1);");
263 out.append("stack.push(arg2);");
270 out.append("stack.push(arg3);");
277 final int indx = readByte(byteCodes, ++i);
278 out.append("stack.push(arg").append(indx + ");");
286 final int indx = readByte(byteCodes, ++i);
287 out.append("arg" + indx).append(" = stack.pop()");
295 out.append("arg0 = stack.pop();");
302 out.append("arg1 = stack.pop();");
309 out.append("arg2 = stack.pop();");
316 out.append("arg3 = stack.pop();");
322 out.append("stack.push(stack.pop() + stack.pop());");
328 out.append("{ var tmp = stack.pop(); stack.push(stack.pop() - tmp); }");
334 out.append("stack.push(stack.pop() * stack.pop());");
338 out.append("{ var tmp = stack.pop(); stack.push(Math.floor(stack.pop() / tmp)); }");
342 out.append("{ var tmp = stack.pop(); stack.push(stack.pop() / tmp); }");
346 out.append("stack.push(stack.pop() & stack.pop());");
350 out.append("stack.push(stack.pop() | stack.pop());");
354 out.append("stack.push(stack.pop() ^ stack.pop());");
360 out.append("stack.push(- stack.pop());");
364 out.append("{ var v = stack.pop(); stack.push(stack.pop() << v); }");
368 out.append("{ var v = stack.pop(); stack.push(stack.pop() >> v); }");
372 out.append("{ var v = stack.pop(); stack.push(stack.pop() >>> v); }");
375 final int varIndx = readByte(byteCodes, ++i);
376 final int incrBy = byteCodes[++i];
378 out.append("arg" + varIndx).append("++;");
380 out.append("arg" + varIndx).append(" += " + incrBy).append(";");
385 out.append("return;");
392 out.append("return stack.pop();");
403 out.append("/* number conversion */");
409 out.append("stack.push(Math.floor(stack.pop()));");
414 out.append("/* number conversion */");
417 out.append("stack.push(null);");
420 out.append("stack.push(-1);");
426 out.append("stack.push(0);");
432 out.append("stack.push(1);");
436 out.append("stack.push(2);");
439 out.append("stack.push(3);");
442 out.append("stack.push(4);");
445 out.append("stack.push(5);");
448 int indx = readByte(byteCodes, ++i);
449 CPEntry entry = jc.getConstantPool().get(indx);
450 String v = encodeConstant(entry);
451 out.append("stack.push(").append(v).append(");");
456 int indx = readIntArg(byteCodes, i);
457 CPEntry entry = jc.getConstantPool().get(indx);
459 String v = encodeConstant(entry);
460 out.append("stack.push(").append(v).append(");");
468 out.append("{ var delta = stack.pop() - stack.pop(); stack.push(delta < 0 ?-1 : (delta == 0 ? 0 : 1)); }");
472 i = generateIf(byteCodes, i, "===");
475 i = generateIf(byteCodes, i, "!=");
478 i = generateIf(byteCodes, i, "==");
482 int indx = i + readIntArg(byteCodes, i);
483 out.append("if (stack.pop() == 0) { gt = " + indx);
484 out.append("; continue; }");
489 int indx = i + readIntArg(byteCodes, i);
490 out.append("if (stack.pop() != 0) { gt = " + indx);
491 out.append("; continue; }");
496 int indx = i + readIntArg(byteCodes, i);
497 out.append("if (stack.pop() < 0) { gt = " + indx);
498 out.append("; continue; }");
503 int indx = i + readIntArg(byteCodes, i);
504 out.append("if (stack.pop() <= 0) { gt = " + indx);
505 out.append("; continue; }");
510 int indx = i + readIntArg(byteCodes, i);
511 out.append("if (stack.pop() > 0) { gt = " + indx);
512 out.append("; continue; }");
517 int indx = i + readIntArg(byteCodes, i);
518 out.append("if (stack.pop() >= 0) { gt = " + indx);
519 out.append("; continue; }");
524 int indx = i + readIntArg(byteCodes, i);
525 out.append("if (stack.pop()) { gt = " + indx);
526 out.append("; continue; }");
531 int indx = i + readIntArg(byteCodes, i);
532 out.append("if (!stack.pop()) { gt = " + indx);
533 out.append("; continue; }");
538 i = generateIf(byteCodes, i, "!=");
541 i = generateIf(byteCodes, i, ">");
544 i = generateIf(byteCodes, i, ">=");
547 i = generateIf(byteCodes, i, "<");
550 i = generateIf(byteCodes, i, "<=");
553 int indx = i + readIntArg(byteCodes, i);
554 out.append("gt = " + indx).append("; continue;");
558 case bc_lookupswitch: {
559 int table = i / 4 * 4 + 4;
560 int dflt = i + readInt4(byteCodes, table);
562 int n = readInt4(byteCodes, table);
564 out.append("switch (stack.pop()) {\n");
566 int cnstnt = readInt4(byteCodes, table);
568 int offset = i + readInt4(byteCodes, table);
570 out.append(" case " + cnstnt).append(": gt = " + offset).append("; continue;\n");
572 out.append(" default: gt = " + dflt).append("; continue;\n}");
576 case bc_tableswitch: {
577 int table = i / 4 * 4 + 4;
578 int dflt = i + readInt4(byteCodes, table);
580 int low = readInt4(byteCodes, table);
582 int high = readInt4(byteCodes, table);
584 out.append("switch (stack.pop()) {\n");
585 while (low <= high) {
586 int offset = i + readInt4(byteCodes, table);
588 out.append(" case " + low).append(": gt = " + offset).append("; continue;\n");
591 out.append(" default: gt = " + dflt).append("; continue;\n}");
595 case bc_invokeinterface: {
596 i = invokeVirtualMethod(byteCodes, i) + 2;
599 case bc_invokevirtual:
600 i = invokeVirtualMethod(byteCodes, i);
602 case bc_invokespecial:
603 i = invokeStaticMethod(byteCodes, i, false);
605 case bc_invokestatic:
606 i = invokeStaticMethod(byteCodes, i, true);
609 int indx = readIntArg(byteCodes, i);
610 CPClassInfo ci = jc.getConstantPool().getClass(indx);
611 out.append("stack.push(");
612 out.append("new ").append(ci.getClassName().getInternalName().replace('/','_'));
614 addReference(ci.getClassName().getInternalName());
619 int type = byteCodes[i++];
620 out.append("stack.push(new Array(stack.pop()));");
624 i += 2; // skip type of array
625 out.append("stack.push(new Array(stack.pop()));");
628 case bc_multianewarray: {
630 int dim = readByte(byteCodes, ++i);
631 out.append("{ var a0 = new Array(stack.pop());");
632 for (int d = 1; d < dim; d++) {
633 out.append("\n var l" + d).append(" = stack.pop();");
634 out.append("\n for (var i" + d).append (" = 0; i" + d).
635 append(" < a" + (d - 1)).
636 append(".length; i" + d).append("++) {");
637 out.append("\n var a" + d).
638 append (" = new Array(l" + d).append(");");
639 out.append("\n a" + (d - 1)).append("[i" + d).append("] = a" + d).
642 for (int d = 1; d < dim; d++) {
645 out.append("\nstack.push(a0); }");
649 out.append("stack.push(stack.pop().length);");
659 out.append("{ var value = stack.pop(); var indx = stack.pop(); stack.pop()[indx] = value; }");
670 out.append("{ var indx = stack.pop(); stack.push(stack.pop()[indx]); }");
674 out.append("stack.pop();");
676 out.append("stack.pop();");
679 out.append("stack.push(stack[stack.length - 1]);");
682 out.append("stack.push(" + byteCodes[++i] + ");");
685 out.append("stack.push(" + readIntArg(byteCodes, i) + ");");
689 int indx = readIntArg(byteCodes, i);
690 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
691 out.append("stack.push(stack.pop().fld_").
692 append(fi.getFieldName()).append(");");
697 int indx = readIntArg(byteCodes, i);
698 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
699 final String in = fi.getClassName().getInternalName();
700 out.append("stack.push(").append(in.replace('/', '_'));
701 out.append('_').append(fi.getFieldName()).append(");");
707 int indx = readIntArg(byteCodes, i);
708 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
709 final String in = fi.getClassName().getInternalName();
710 out.append(in.replace('/', '_'));
711 out.append('_').append(fi.getFieldName()).append(" = stack.pop();");
717 int indx = readIntArg(byteCodes, i);
718 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
719 out.append("{ var v = stack.pop(); stack.pop().fld_")
720 .append(fi.getFieldName()).append(" = v; }");
725 int indx = readIntArg(byteCodes, i);
726 CPClassInfo ci = jc.getConstantPool().getClass(indx);
727 final String type = ci.getClassName().getType();
728 if (!type.startsWith("[")) {
729 // no way to check arrays right now
730 out.append("if(stack[stack.length - 1].$instOf_")
731 .append(type.replace('/', '_'))
732 .append(" != 1) throw {};"); // XXX proper exception
737 case bc_instanceof: {
738 int indx = readIntArg(byteCodes, i);
739 CPClassInfo ci = jc.getConstantPool().getClass(indx);
740 out.append("stack.push(stack.pop().$instOf_")
741 .append(ci.getClassName().getInternalName().replace('/', '_'))
742 .append(" ? 1 : 0);");
747 out.append("{ var t = stack.pop(); stack = new Array(1); stack[0] = t; throw t; }");
751 out.append("throw 'unknown bytecode " + c + "';");
756 for (int j = prev; j <= i; j++) {
758 final int cc = readByte(byteCodes, j);
759 out.append(Integer.toString(cc));
766 private int generateIf(byte[] byteCodes, int i, final String test) throws IOException {
767 int indx = i + readIntArg(byteCodes, i);
768 out.append("if (stack.pop() ").append(test).append(" stack.pop()) { gt = " + indx);
769 out.append("; continue; }");
773 private int readIntArg(byte[] byteCodes, int offsetInstruction) {
774 final int indxHi = byteCodes[offsetInstruction + 1] << 8;
775 final int indxLo = byteCodes[offsetInstruction + 2];
776 return (indxHi & 0xffffff00) | (indxLo & 0xff);
778 private int readInt4(byte[] byteCodes, int offsetInstruction) {
779 final int d = byteCodes[offsetInstruction + 0] << 24;
780 final int c = byteCodes[offsetInstruction + 1] << 16;
781 final int b = byteCodes[offsetInstruction + 2] << 8;
782 final int a = byteCodes[offsetInstruction + 3];
783 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
785 private int readByte(byte[] byteCodes, int offsetInstruction) {
786 return (byteCodes[offsetInstruction] + 256) % 256;
789 private static int countArgs(String descriptor, boolean[] hasReturnType, StringBuilder sig) {
792 Boolean count = null;
793 boolean array = false;
794 int firstPos = sig.length();
795 while (i < descriptor.length()) {
796 char ch = descriptor.charAt(i++);
822 hasReturnType[0] = true;
823 sig.insert(firstPos, ch);
825 sig.insert(firstPos, 'A');
832 hasReturnType[0] = false;
833 sig.insert(firstPos, 'V');
836 int next = descriptor.indexOf(';', i);
843 sig.append(descriptor.substring(i, next).replace('/', '_'));
845 sig.insert(firstPos, descriptor.substring(i, next).replace('/', '_'));
846 sig.insert(firstPos, ch);
848 sig.insert(firstPos, 'A');
850 hasReturnType[0] = true;
858 break; // invalid character
864 private void generateStaticField(Variable v) throws IOException {
866 .append(jc.getName().getInternalName().replace('/', '_'))
867 .append('_').append(v.getName()).append(" = 0;");
870 private String findMethodName(Method m) {
871 StringBuilder name = new StringBuilder();
872 String descr = m.getDescriptor();
873 if ("<init>".equals(m.getName())) { // NOI18N
874 name.append("cons"); // NOI18N
875 } else if ("<clinit>".equals(m.getName())) { // NOI18N
876 name.append("class"); // NOI18N
878 name.append(m.getName());
881 boolean hasReturn[] = { false };
882 countArgs(findDescriptor(m.getDescriptor()), hasReturn, name);
883 return name.toString();
886 private String findMethodName(CPMethodInfo mi, int[] cnt, boolean[] hasReturn) {
887 StringBuilder name = new StringBuilder();
888 String descr = mi.getDescriptor();
889 if ("<init>".equals(mi.getName())) { // NOI18N
890 name.append("cons"); // NOI18N
892 name.append(mi.getName());
894 cnt[0] = countArgs(findDescriptor(mi.getDescriptor()), hasReturn, name);
895 return name.toString();
898 private int invokeStaticMethod(byte[] byteCodes, int i, boolean isStatic)
900 int methodIndex = readIntArg(byteCodes, i);
901 CPMethodInfo mi = (CPMethodInfo) jc.getConstantPool().get(methodIndex);
902 boolean[] hasReturn = { false };
904 String mn = findMethodName(mi, cnt, hasReturn);
906 for (int j = cnt[0] - 1; j >= 0; j--) {
907 out.append("var v" + j).append(" = stack.pop(); ");
911 out.append("stack.push(");
913 final String in = mi.getClassName().getInternalName();
914 out.append(in.replace('/', '_'));
916 out.append(".prototype.");
924 out.append("stack.pop()");
927 for (int j = 0; j < cnt[0]; j++) {
941 private int invokeVirtualMethod(byte[] byteCodes, int i)
943 int methodIndex = readIntArg(byteCodes, i);
944 CPMethodInfo mi = (CPMethodInfo) jc.getConstantPool().get(methodIndex);
945 boolean[] hasReturn = { false };
947 String mn = findMethodName(mi, cnt, hasReturn);
949 for (int j = cnt[0] - 1; j >= 0; j--) {
950 out.append("var v" + j).append(" = stack.pop(); ");
952 out.append("var self = stack.pop(); ");
954 out.append("stack.push(");
960 for (int j = 0; j < cnt[0]; j++) {
973 private void addReference(String cn) throws IOException {
974 if (references != null) {
975 if (references.add(cn)) {
976 out.append(" /* needs ").append(cn).append(" */");
981 private void outType(String d, StringBuilder out) {
983 while (d.charAt(0) == '[') {
987 if (d.charAt(0) == 'L') {
988 assert d.charAt(d.length() - 1) == ';';
989 out.append(d.replace('/', '_').substring(0, d.length() - 1));
995 private String encodeConstant(CPEntry entry) {
997 if (entry instanceof CPClassInfo) {
998 v = "new java_lang_Class";
999 } else if (entry instanceof CPStringInfo) {
1000 v = "\"" + entry.getValue().toString().
1001 replace("\\", "\\\\").
1002 replace("\n", "\\n").
1003 replace("\r", "\\r").
1004 replace("\t", "\\t").
1005 replace("\"", "\\\"")
1008 v = entry.getValue().toString();
1013 private String findDescriptor(String d) {
1014 return d.replace('[', 'A');
1017 private boolean javaScriptBody(Method m, boolean isStatic) throws IOException {
1018 final ClassName extraAnn = ClassName.getClassName(JavaScriptBody.class.getName().replace('.', '/'));
1019 Annotation a = m.getAnnotation(extraAnn);
1021 final ElementValue annVal = a.getComponent("body").getValue();
1022 String body = ((PrimitiveElementValue) annVal).getValue().getValue().toString();
1024 final ArrayElementValue arrVal = (ArrayElementValue) a.getComponent("args").getValue();
1025 final int len = arrVal.getValues().length;
1026 String[] names = new String[len];
1027 for (int i = 0; i < len; i++) {
1028 names[i] = ((PrimitiveElementValue) arrVal.getValues()[i]).getValue().getValue().toString();
1030 out.append("\nfunction ").append(
1031 jc.getName().getInternalName().replace('/', '_')).append('_').append(findMethodName(m));
1036 out.append(names[0]);
1043 List<Parameter> args = m.getParameters();
1044 for (int i = 0; i < args.size(); i++) {
1046 out.append(names[index]);
1047 final String desc = findDescriptor(args.get(i).getDescriptor());
1051 out.append(") {").append("\n");
1053 out.append("\n}\n");