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." + v.getName() + " = 0;");
121 out.append("\n}\n\nfunction ").append(className).append("_proto() {");
122 out.append("\n if (").append(className).
123 append(".prototype.$instOf_").append(className).append(") {");
124 out.append("\n return new ").append(className).append(";");
126 ClassName sc = jc.getSuperClass();
128 out.append("\n var p = ").append(className)
129 .append(".prototype = ").
130 append(sc.getInternalName().replace('/', '_')).append("_proto();");
132 out.append("\n var p = ").append(className).append(".prototype;");
134 for (Method m : jc.getMethods()) {
135 if (!m.getName().contains("<init>") && !m.getName().contains("<cinit>")) {
136 compiler.generateMethodReference("\n p.", m);
139 out.append("\n p.$instOf_").append(className).append(" = true;");
140 for (ClassName superInterface : jc.getInterfaces()) {
141 out.append("\n p.$instOf_").append(superInterface.getInternalName().replace('/', '_')).append(" = true;");
143 out.append("\n return new ").append(className).append(";");
145 out.append("\n").append(className).append("_proto();");
146 StringBuilder sb = new StringBuilder();
147 for (String init : toInitilize) {
148 sb.append("\n").append(init).append("();");
150 return sb.toString();
152 private void generateStaticMethod(Method m, List<String> toInitilize) throws IOException {
153 if (javaScriptBody(m, true)) {
156 final String mn = findMethodName(m);
157 out.append("\nfunction ").append(
158 jc.getName().getInternalName().replace('/', '_')
159 ).append('_').append(mn);
160 if (mn.equals("classV")) {
161 toInitilize.add(jc.getName().getInternalName().replace('/', '_') + '_' + mn);
165 List<Parameter> args = m.getParameters();
166 for (int index = 0, i = 0; i < args.size(); i++) {
168 out.append("arg").append(String.valueOf(index));
170 final String desc = findDescriptor(args.get(i).getDescriptor());
171 if ("D".equals(desc) || "J".equals(desc)) {
177 out.append(") {").append("\n");
178 final Code code = m.getCode();
180 int len = code.getMaxLocals();
181 for (int index = args.size(), i = args.size(); i < len; i++) {
183 out.append("arg").append(String.valueOf(i)).append(";\n");
185 out.append(" var stack = new Array();\n");
186 produceCode(code.getByteCodes());
188 out.append(" /* no code found for ").append(m.getTypeSignature()).append(" */\n");
193 private void generateMethodReference(String prefix, Method m) throws IOException {
194 final String name = findMethodName(m);
195 out.append(prefix).append(name).append(" = ")
196 .append(jc.getName().getInternalName().replace('/', '_'))
197 .append('_').append(name).append(";");
200 private void generateInstanceMethod(Method m) throws IOException {
201 if (javaScriptBody(m, false)) {
204 out.append("\nfunction ").append(
205 jc.getName().getInternalName().replace('/', '_')
206 ).append('_').append(findMethodName(m));
209 List<Parameter> args = m.getParameters();
210 for (int index = 1, i = 0; i < args.size(); i++) {
212 out.append("arg").append(String.valueOf(index));
213 final String desc = findDescriptor(args.get(i).getDescriptor());
214 if ("D".equals(desc) || "J".equals(desc)) {
220 out.append(") {").append("\n");
221 final Code code = m.getCode();
223 int len = code.getMaxLocals();
224 for (int index = args.size(), i = args.size(); i < len; i++) {
226 out.append("arg").append(String.valueOf(i + 1)).append(";\n");
228 out.append(";\n var stack = new Array();\n");
229 produceCode(code.getByteCodes());
231 out.append(" /* no code found for ").append(m.getTypeSignature()).append(" */\n");
236 private void produceCode(byte[] byteCodes) throws IOException {
237 out.append("\n var gt = 0;\n for(;;) switch(gt) {\n");
238 for (int i = 0; i < byteCodes.length; i++) {
240 out.append(" case " + i).append(": ");
241 final int c = readByte(byteCodes, i);
248 out.append("stack.push(arg0);");
255 out.append("stack.push(arg1);");
262 out.append("stack.push(arg2);");
269 out.append("stack.push(arg3);");
276 final int indx = readByte(byteCodes, ++i);
277 out.append("stack.push(arg").append(indx + ");");
285 final int indx = readByte(byteCodes, ++i);
286 out.append("arg" + indx).append(" = stack.pop()");
294 out.append("arg0 = stack.pop();");
301 out.append("arg1 = stack.pop();");
308 out.append("arg2 = stack.pop();");
315 out.append("arg3 = stack.pop();");
321 out.append("stack.push(stack.pop() + stack.pop());");
327 out.append("{ var tmp = stack.pop(); stack.push(stack.pop() - tmp); }");
333 out.append("stack.push(stack.pop() * stack.pop());");
337 out.append("{ var tmp = stack.pop(); stack.push(Math.floor(stack.pop() / tmp)); }");
341 out.append("{ var tmp = stack.pop(); stack.push(stack.pop() / tmp); }");
345 out.append("stack.push(stack.pop() & stack.pop());");
349 out.append("stack.push(stack.pop() | stack.pop());");
353 out.append("stack.push(stack.pop() ^ stack.pop());");
359 out.append("stack.push(- stack.pop());");
363 out.append("{ var v = stack.pop(); stack.push(stack.pop() << v); }");
367 out.append("{ var v = stack.pop(); stack.push(stack.pop() >> v); }");
371 out.append("{ var v = stack.pop(); stack.push(stack.pop() >>> v); }");
374 final int varIndx = readByte(byteCodes, ++i);
375 final int incrBy = byteCodes[++i];
377 out.append("arg" + varIndx).append("++;");
379 out.append("arg" + varIndx).append(" += " + incrBy).append(";");
384 out.append("return;");
391 out.append("return stack.pop();");
402 out.append("/* number conversion */");
408 out.append("stack.push(Math.floor(stack.pop()));");
413 out.append("/* number conversion */");
416 out.append("stack.push(null);");
419 out.append("stack.push(-1);");
425 out.append("stack.push(0);");
431 out.append("stack.push(1);");
435 out.append("stack.push(2);");
438 out.append("stack.push(3);");
441 out.append("stack.push(4);");
444 out.append("stack.push(5);");
447 int indx = readByte(byteCodes, ++i);
448 CPEntry entry = jc.getConstantPool().get(indx);
449 String v = encodeConstant(entry);
450 out.append("stack.push(").append(v).append(");");
455 int indx = readIntArg(byteCodes, i);
456 CPEntry entry = jc.getConstantPool().get(indx);
458 String v = encodeConstant(entry);
459 out.append("stack.push(").append(v).append(");");
467 out.append("{ var delta = stack.pop() - stack.pop(); stack.push(delta < 0 ?-1 : (delta == 0 ? 0 : 1)); }");
471 i = generateIf(byteCodes, i, "===");
474 i = generateIf(byteCodes, i, "!=");
477 i = generateIf(byteCodes, i, "==");
481 int indx = i + readIntArg(byteCodes, i);
482 out.append("if (stack.pop() == 0) { gt = " + indx);
483 out.append("; continue; }");
488 int indx = i + readIntArg(byteCodes, i);
489 out.append("if (stack.pop() != 0) { gt = " + indx);
490 out.append("; continue; }");
495 int indx = i + readIntArg(byteCodes, i);
496 out.append("if (stack.pop() < 0) { gt = " + indx);
497 out.append("; continue; }");
502 int indx = i + readIntArg(byteCodes, i);
503 out.append("if (stack.pop() <= 0) { gt = " + indx);
504 out.append("; continue; }");
509 int indx = i + readIntArg(byteCodes, i);
510 out.append("if (stack.pop() > 0) { gt = " + indx);
511 out.append("; continue; }");
516 int indx = i + readIntArg(byteCodes, i);
517 out.append("if (stack.pop() >= 0) { gt = " + indx);
518 out.append("; continue; }");
523 int indx = i + readIntArg(byteCodes, i);
524 out.append("if (stack.pop()) { gt = " + indx);
525 out.append("; continue; }");
530 int indx = i + readIntArg(byteCodes, i);
531 out.append("if (!stack.pop()) { gt = " + indx);
532 out.append("; continue; }");
537 i = generateIf(byteCodes, i, "!=");
540 i = generateIf(byteCodes, i, ">");
543 i = generateIf(byteCodes, i, ">=");
546 i = generateIf(byteCodes, i, "<");
549 i = generateIf(byteCodes, i, "<=");
552 int indx = i + readIntArg(byteCodes, i);
553 out.append("gt = " + indx).append("; continue;");
557 case bc_lookupswitch: {
558 int table = i / 4 * 4 + 4;
559 int dflt = i + readInt4(byteCodes, table);
561 int n = readInt4(byteCodes, table);
563 out.append("switch (stack.pop()) {\n");
565 int cnstnt = readInt4(byteCodes, table);
567 int offset = i + readInt4(byteCodes, table);
569 out.append(" case " + cnstnt).append(": gt = " + offset).append("; continue;\n");
571 out.append(" default: gt = " + dflt).append("; continue;\n}");
575 case bc_tableswitch: {
576 int table = i / 4 * 4 + 4;
577 int dflt = i + readInt4(byteCodes, table);
579 int low = readInt4(byteCodes, table);
581 int high = readInt4(byteCodes, table);
583 out.append("switch (stack.pop()) {\n");
584 while (low <= high) {
585 int offset = i + readInt4(byteCodes, table);
587 out.append(" case " + low).append(": gt = " + offset).append("; continue;\n");
590 out.append(" default: gt = " + dflt).append("; continue;\n}");
594 case bc_invokeinterface: {
595 i = invokeVirtualMethod(byteCodes, i) + 2;
598 case bc_invokevirtual:
599 i = invokeVirtualMethod(byteCodes, i);
601 case bc_invokespecial:
602 i = invokeStaticMethod(byteCodes, i, false);
604 case bc_invokestatic:
605 i = invokeStaticMethod(byteCodes, i, true);
608 int indx = readIntArg(byteCodes, i);
609 CPClassInfo ci = jc.getConstantPool().getClass(indx);
610 out.append("stack.push(");
611 out.append("new ").append(ci.getClassName().getInternalName().replace('/','_'));
613 addReference(ci.getClassName().getInternalName());
618 int type = byteCodes[i++];
619 out.append("stack.push(new Array(stack.pop()));");
623 i += 2; // skip type of array
624 out.append("stack.push(new Array(stack.pop()));");
627 case bc_multianewarray: {
629 int dim = readByte(byteCodes, ++i);
630 out.append("{ var a0 = new Array(stack.pop());");
631 for (int d = 1; d < dim; d++) {
632 out.append("\n var l" + d).append(" = stack.pop();");
633 out.append("\n for (var i" + d).append (" = 0; i" + d).
634 append(" < a" + (d - 1)).
635 append(".length; i" + d).append("++) {");
636 out.append("\n var a" + d).
637 append (" = new Array(l" + d).append(");");
638 out.append("\n a" + (d - 1)).append("[i" + d).append("] = a" + d).
641 for (int d = 1; d < dim; d++) {
644 out.append("\nstack.push(a0); }");
648 out.append("stack.push(stack.pop().length);");
658 out.append("{ var value = stack.pop(); var indx = stack.pop(); stack.pop()[indx] = value; }");
669 out.append("{ var indx = stack.pop(); stack.push(stack.pop()[indx]); }");
673 out.append("stack.pop();");
675 out.append("stack.pop();");
678 out.append("stack.push(stack[stack.length - 1]);");
681 out.append("stack.push(" + byteCodes[++i] + ");");
684 out.append("stack.push(" + readIntArg(byteCodes, i) + ");");
688 int indx = readIntArg(byteCodes, i);
689 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
690 out.append("stack.push(stack.pop().").append(fi.getFieldName()).append(");");
695 int indx = readIntArg(byteCodes, i);
696 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
697 final String in = fi.getClassName().getInternalName();
698 out.append("stack.push(").append(in.replace('/', '_'));
699 out.append('_').append(fi.getFieldName()).append(");");
705 int indx = readIntArg(byteCodes, i);
706 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
707 final String in = fi.getClassName().getInternalName();
708 out.append(in.replace('/', '_'));
709 out.append('_').append(fi.getFieldName()).append(" = stack.pop();");
715 int indx = readIntArg(byteCodes, i);
716 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
717 out.append("{ var v = stack.pop(); stack.pop().")
718 .append(fi.getFieldName()).append(" = v; }");
723 int indx = readIntArg(byteCodes, i);
724 CPClassInfo ci = jc.getConstantPool().getClass(indx);
725 final String type = ci.getClassName().getType();
726 if (!type.startsWith("[")) {
727 // no way to check arrays right now
728 out.append("if(stack[stack.length - 1].$instOf_")
729 .append(type.replace('/', '_'))
730 .append(" != 1) throw {};"); // XXX proper exception
735 case bc_instanceof: {
736 int indx = readIntArg(byteCodes, i);
737 CPClassInfo ci = jc.getConstantPool().getClass(indx);
738 out.append("stack.push(stack.pop().$instOf_")
739 .append(ci.getClassName().getInternalName().replace('/', '_'))
740 .append(" ? 1 : 0);");
745 out.append("{ var t = stack.pop(); stack = new Array(1); stack[0] = t; throw t; }");
749 out.append("throw 'unknown bytecode " + c + "';");
754 for (int j = prev; j <= i; j++) {
756 final int cc = readByte(byteCodes, j);
757 out.append(Integer.toString(cc));
764 private int generateIf(byte[] byteCodes, int i, final String test) throws IOException {
765 int indx = i + readIntArg(byteCodes, i);
766 out.append("if (stack.pop() ").append(test).append(" stack.pop()) { gt = " + indx);
767 out.append("; continue; }");
771 private int readIntArg(byte[] byteCodes, int offsetInstruction) {
772 final int indxHi = byteCodes[offsetInstruction + 1] << 8;
773 final int indxLo = byteCodes[offsetInstruction + 2];
774 return (indxHi & 0xffffff00) | (indxLo & 0xff);
776 private int readInt4(byte[] byteCodes, int offsetInstruction) {
777 final int d = byteCodes[offsetInstruction + 0] << 24;
778 final int c = byteCodes[offsetInstruction + 1] << 16;
779 final int b = byteCodes[offsetInstruction + 2] << 8;
780 final int a = byteCodes[offsetInstruction + 3];
781 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
783 private int readByte(byte[] byteCodes, int offsetInstruction) {
784 return (byteCodes[offsetInstruction] + 256) % 256;
787 private static int countArgs(String descriptor, boolean[] hasReturnType, StringBuilder sig) {
790 Boolean count = null;
791 boolean array = false;
792 int firstPos = sig.length();
793 while (i < descriptor.length()) {
794 char ch = descriptor.charAt(i++);
820 hasReturnType[0] = true;
821 sig.insert(firstPos, ch);
823 sig.insert(firstPos, 'A');
830 hasReturnType[0] = false;
831 sig.insert(firstPos, 'V');
834 int next = descriptor.indexOf(';', i);
841 sig.append(descriptor.substring(i, next).replace('/', '_'));
843 sig.insert(firstPos, descriptor.substring(i, next).replace('/', '_'));
844 sig.insert(firstPos, ch);
846 sig.insert(firstPos, 'A');
848 hasReturnType[0] = true;
856 break; // invalid character
862 private void generateStaticField(Variable v) throws IOException {
864 .append(jc.getName().getInternalName().replace('/', '_'))
865 .append('_').append(v.getName()).append(" = 0;");
868 private String findMethodName(Method m) {
869 StringBuilder name = new StringBuilder();
870 String descr = m.getDescriptor();
871 if ("<init>".equals(m.getName())) { // NOI18N
872 name.append("cons"); // NOI18N
873 } else if ("<clinit>".equals(m.getName())) { // NOI18N
874 name.append("class"); // NOI18N
876 name.append(m.getName());
879 boolean hasReturn[] = { false };
880 countArgs(findDescriptor(m.getDescriptor()), hasReturn, name);
881 return name.toString();
884 private String findMethodName(CPMethodInfo mi, int[] cnt, boolean[] hasReturn) {
885 StringBuilder name = new StringBuilder();
886 String descr = mi.getDescriptor();
887 if ("<init>".equals(mi.getName())) { // NOI18N
888 name.append("cons"); // NOI18N
890 name.append(mi.getName());
892 cnt[0] = countArgs(findDescriptor(mi.getDescriptor()), hasReturn, name);
893 return name.toString();
896 private int invokeStaticMethod(byte[] byteCodes, int i, boolean isStatic)
898 int methodIndex = readIntArg(byteCodes, i);
899 CPMethodInfo mi = (CPMethodInfo) jc.getConstantPool().get(methodIndex);
900 boolean[] hasReturn = { false };
902 String mn = findMethodName(mi, cnt, hasReturn);
904 for (int j = cnt[0] - 1; j >= 0; j--) {
905 out.append("var v" + j).append(" = stack.pop(); ");
909 out.append("stack.push(");
911 final String in = mi.getClassName().getInternalName();
912 out.append(in.replace('/', '_'));
914 out.append(".prototype.");
922 out.append("stack.pop()");
925 for (int j = 0; j < cnt[0]; j++) {
939 private int invokeVirtualMethod(byte[] byteCodes, int i)
941 int methodIndex = readIntArg(byteCodes, i);
942 CPMethodInfo mi = (CPMethodInfo) jc.getConstantPool().get(methodIndex);
943 boolean[] hasReturn = { false };
945 String mn = findMethodName(mi, cnt, hasReturn);
947 for (int j = cnt[0] - 1; j >= 0; j--) {
948 out.append("var v" + j).append(" = stack.pop(); ");
950 out.append("var self = stack.pop(); ");
952 out.append("stack.push(");
958 for (int j = 0; j < cnt[0]; j++) {
971 private void addReference(String cn) throws IOException {
972 if (references != null) {
973 if (references.add(cn)) {
974 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(CPEntry entry) {
995 if (entry instanceof CPClassInfo) {
996 v = "new java_lang_Class";
997 } else if (entry instanceof CPStringInfo) {
998 v = "\"" + entry.getValue().toString().replace("\"", "\\\"") + "\"";
1000 v = entry.getValue().toString();
1005 private String findDescriptor(String d) {
1006 return d.replace('[', 'A');
1009 private boolean javaScriptBody(Method m, boolean isStatic) throws IOException {
1010 final ClassName extraAnn = ClassName.getClassName(JavaScriptBody.class.getName().replace('.', '/'));
1011 Annotation a = m.getAnnotation(extraAnn);
1013 final ElementValue annVal = a.getComponent("body").getValue();
1014 String body = ((PrimitiveElementValue) annVal).getValue().getValue().toString();
1016 final ArrayElementValue arrVal = (ArrayElementValue) a.getComponent("args").getValue();
1017 final int len = arrVal.getValues().length;
1018 String[] names = new String[len];
1019 for (int i = 0; i < len; i++) {
1020 names[i] = ((PrimitiveElementValue) arrVal.getValues()[i]).getValue().getValue().toString();
1022 out.append("\nfunction ").append(
1023 jc.getName().getInternalName().replace('/', '_')).append('_').append(findMethodName(m));
1028 out.append(names[0]);
1035 List<Parameter> args = m.getParameters();
1036 for (int i = 0; i < args.size(); i++) {
1038 out.append(names[index]);
1039 final String desc = findDescriptor(args.get(i).getDescriptor());
1043 out.append(") {").append("\n");
1045 out.append("\n}\n");