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 ").append(className).append(".prototype;");
126 ClassName sc = jc.getSuperClass();
128 out.append("\n ").append(sc.getInternalName().replace('/', '_')).append("_proto();");
129 out.append("\n ").append(className)
130 .append(".prototype = new ").append(sc.getInternalName().replace('/', '_')).append(';');
132 for (Method m : jc.getMethods()) {
133 if (!m.getName().contains("<init>") && !m.getName().contains("<cinit>")) {
134 compiler.generateMethodReference("\n " + className + ".prototype.", m);
137 out.append("\n " + className + ".prototype.$instOf_").append(className).append(" = true;");
138 for (ClassName superInterface : jc.getInterfaces()) {
139 out.append("\n " + className + ".prototype.$instOf_").append(superInterface.getInternalName().replace('/', '_')).append(" = true;");
141 out.append("\n return ").append(className).append(".prototype;");
143 out.append("\n").append(className).append("_proto();");
144 StringBuilder sb = new StringBuilder();
145 for (String init : toInitilize) {
146 sb.append("\n").append(init).append("();");
148 return sb.toString();
150 private void generateStaticMethod(Method m, List<String> toInitilize) throws IOException {
151 if (javaScriptBody(m, true)) {
154 final String mn = findMethodName(m);
155 out.append("\nfunction ").append(
156 jc.getName().getInternalName().replace('/', '_')
157 ).append('_').append(mn);
158 if (mn.equals("classV")) {
159 toInitilize.add(jc.getName().getInternalName().replace('/', '_') + '_' + mn);
163 List<Parameter> args = m.getParameters();
164 for (int index = 0, i = 0; i < args.size(); i++) {
166 out.append("arg").append(String.valueOf(index));
168 final String desc = findDescriptor(args.get(i).getDescriptor());
169 if ("D".equals(desc) || "J".equals(desc)) {
175 out.append(") {").append("\n");
176 final Code code = m.getCode();
178 int len = code.getMaxLocals();
179 for (int index = args.size(), i = args.size(); i < len; i++) {
181 out.append("arg").append(String.valueOf(i)).append(";\n");
183 out.append(" var stack = new Array();\n");
184 produceCode(code.getByteCodes());
186 out.append(" /* no code found for ").append(m.getTypeSignature()).append(" */\n");
191 private void generateMethodReference(String prefix, Method m) throws IOException {
192 final String name = findMethodName(m);
193 out.append(prefix).append(name).append(" = ")
194 .append(jc.getName().getInternalName().replace('/', '_'))
195 .append('_').append(name).append(";");
198 private void generateInstanceMethod(Method m) throws IOException {
199 if (javaScriptBody(m, false)) {
202 out.append("\nfunction ").append(
203 jc.getName().getInternalName().replace('/', '_')
204 ).append('_').append(findMethodName(m));
207 List<Parameter> args = m.getParameters();
208 for (int index = 1, i = 0; i < args.size(); i++) {
210 out.append("arg").append(String.valueOf(index));
211 final String desc = findDescriptor(args.get(i).getDescriptor());
212 if ("D".equals(desc) || "J".equals(desc)) {
218 out.append(") {").append("\n");
219 final Code code = m.getCode();
221 int len = code.getMaxLocals();
222 for (int index = args.size(), i = args.size(); i < len; i++) {
224 out.append("arg").append(String.valueOf(i + 1)).append(";\n");
226 out.append(";\n var stack = new Array();\n");
227 produceCode(code.getByteCodes());
229 out.append(" /* no code found for ").append(m.getTypeSignature()).append(" */\n");
234 private void produceCode(byte[] byteCodes) throws IOException {
235 out.append("\n var gt = 0;\n for(;;) switch(gt) {\n");
236 for (int i = 0; i < byteCodes.length; i++) {
238 out.append(" case " + i).append(": ");
239 final int c = (byteCodes[i] + 256) % 256;
246 out.append("stack.push(arg0);");
253 out.append("stack.push(arg1);");
260 out.append("stack.push(arg2);");
267 out.append("stack.push(arg3);");
274 final int indx = (byteCodes[++i] + 256) % 256;
275 out.append("stack.push(arg").append(indx + ");");
283 final int indx = (byteCodes[++i] + 256) % 256;
284 out.append("arg" + indx).append(" = stack.pop()");
292 out.append("arg0 = stack.pop();");
299 out.append("arg1 = stack.pop();");
306 out.append("arg2 = stack.pop();");
313 out.append("arg3 = stack.pop();");
319 out.append("stack.push(stack.pop() + stack.pop());");
325 out.append("{ var tmp = stack.pop(); stack.push(stack.pop() - tmp); }");
331 out.append("stack.push(stack.pop() * stack.pop());");
335 out.append("{ var tmp = stack.pop(); stack.push(Math.floor(stack.pop() / tmp)); }");
339 out.append("{ var tmp = stack.pop(); stack.push(stack.pop() / tmp); }");
343 out.append("stack.push(stack.pop() & stack.pop());");
347 out.append("stack.push(stack.pop() | stack.pop());");
351 out.append("stack.push(stack.pop() ^ stack.pop());");
357 out.append("stack.push(- stack.pop());");
361 out.append("{ var v = stack.pop(); stack.push(stack.pop() << v); }");
365 out.append("{ var v = stack.pop(); stack.push(stack.pop() >> v); }");
369 out.append("{ var v = stack.pop(); stack.push(stack.pop() >>> v); }");
372 final int varIndx = (byteCodes[++i] + 256) % 256;
373 final int incrBy = byteCodes[++i];
375 out.append("arg" + varIndx).append("++;");
377 out.append("arg" + varIndx).append(" += " + incrBy).append(";");
382 out.append("return;");
389 out.append("return stack.pop();");
400 out.append("/* number conversion */");
406 out.append("stack.push(Math.floor(stack.pop()));");
411 out.append("/* number conversion */");
414 out.append("stack.push(null);");
417 out.append("stack.push(-1);");
423 out.append("stack.push(0);");
429 out.append("stack.push(1);");
433 out.append("stack.push(2);");
436 out.append("stack.push(3);");
439 out.append("stack.push(4);");
442 out.append("stack.push(5);");
445 int indx = byteCodes[++i];
446 CPEntry entry = jc.getConstantPool().get(indx);
447 String v = encodeConstant(entry);
448 out.append("stack.push(").append(v).append(");");
453 int indx = readIntArg(byteCodes, i);
454 CPEntry entry = jc.getConstantPool().get(indx);
456 String v = encodeConstant(entry);
457 out.append("stack.push(").append(v).append(");");
465 out.append("{ var delta = stack.pop() - stack.pop(); stack.push(delta < 0 ?-1 : (delta == 0 ? 0 : 1)); }");
469 i = generateIf(byteCodes, i, "===");
472 i = generateIf(byteCodes, i, "!=");
475 i = generateIf(byteCodes, i, "==");
479 int indx = i + readIntArg(byteCodes, i);
480 out.append("if (stack.pop() == 0) { gt = " + indx);
481 out.append("; continue; }");
486 int indx = i + readIntArg(byteCodes, i);
487 out.append("if (stack.pop() != 0) { gt = " + indx);
488 out.append("; continue; }");
493 int indx = i + readIntArg(byteCodes, i);
494 out.append("if (stack.pop() < 0) { gt = " + indx);
495 out.append("; continue; }");
500 int indx = i + readIntArg(byteCodes, i);
501 out.append("if (stack.pop() <= 0) { gt = " + indx);
502 out.append("; continue; }");
507 int indx = i + readIntArg(byteCodes, i);
508 out.append("if (stack.pop() > 0) { gt = " + indx);
509 out.append("; continue; }");
514 int indx = i + readIntArg(byteCodes, i);
515 out.append("if (stack.pop() >= 0) { gt = " + indx);
516 out.append("; continue; }");
521 int indx = i + readIntArg(byteCodes, i);
522 out.append("if (stack.pop()) { gt = " + indx);
523 out.append("; continue; }");
528 int indx = i + readIntArg(byteCodes, i);
529 out.append("if (!stack.pop()) { gt = " + indx);
530 out.append("; continue; }");
535 i = generateIf(byteCodes, i, "!=");
538 i = generateIf(byteCodes, i, ">");
541 i = generateIf(byteCodes, i, ">=");
544 i = generateIf(byteCodes, i, "<");
547 i = generateIf(byteCodes, i, "<=");
550 int indx = i + readIntArg(byteCodes, i);
551 out.append("gt = " + indx).append("; continue;");
555 case bc_lookupswitch: {
556 int table = (i - 1) / 4 * 4 + 4;
557 int dflt = i + readInt4(byteCodes, table);
559 int n = readInt4(byteCodes, table);
561 out.append("switch (stack.pop()) {\n");
563 int cnstnt = readInt4(byteCodes, table);
565 int offset = i + readInt4(byteCodes, table);
567 out.append(" case " + cnstnt).append(": gt = " + offset).append("; continue;\n");
569 out.append(" default: gt = " + dflt).append("; continue;\n}");
573 case bc_tableswitch: {
574 int table = (i - 1) / 4 * 4 + 4;
575 int dflt = i + readInt4(byteCodes, table);
577 int low = readInt4(byteCodes, table);
579 int high = readInt4(byteCodes, table);
581 out.append("switch (stack.pop()) {\n");
582 while (low <= high) {
583 int offset = i + readInt4(byteCodes, table);
585 out.append(" case " + low).append(": gt = " + offset).append("; continue;\n");
588 out.append(" default: gt = " + dflt).append("; continue;\n}");
592 case bc_invokeinterface: {
593 i = invokeVirtualMethod(byteCodes, i) + 2;
596 case bc_invokevirtual:
597 i = invokeVirtualMethod(byteCodes, i);
599 case bc_invokespecial:
600 i = invokeStaticMethod(byteCodes, i, false);
602 case bc_invokestatic:
603 i = invokeStaticMethod(byteCodes, i, true);
606 int indx = readIntArg(byteCodes, i);
607 CPClassInfo ci = jc.getConstantPool().getClass(indx);
608 out.append("stack.push(");
609 out.append("new ").append(ci.getClassName().getInternalName().replace('/','_'));
611 addReference(ci.getClassName().getInternalName());
616 int type = byteCodes[i++];
617 out.append("stack.push(new Array(stack.pop()));");
621 i += 2; // skip type of array
622 out.append("stack.push(new Array(stack.pop()));");
626 out.append("stack.push(stack.pop().length);");
636 out.append("{ var value = stack.pop(); var indx = stack.pop(); stack.pop()[indx] = value; }");
647 out.append("{ var indx = stack.pop(); stack.push(stack.pop()[indx]); }");
651 out.append("stack.pop();");
653 out.append("stack.pop();");
656 out.append("stack.push(stack[stack.length - 1]);");
659 out.append("stack.push(" + byteCodes[++i] + ");");
662 out.append("stack.push(" + readIntArg(byteCodes, i) + ");");
666 int indx = readIntArg(byteCodes, i);
667 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
668 out.append("stack.push(stack.pop().").append(fi.getFieldName()).append(");");
673 int indx = readIntArg(byteCodes, i);
674 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
675 final String in = fi.getClassName().getInternalName();
676 out.append("stack.push(").append(in.replace('/', '_'));
677 out.append('_').append(fi.getFieldName()).append(");");
683 int indx = readIntArg(byteCodes, i);
684 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
685 final String in = fi.getClassName().getInternalName();
686 out.append(in.replace('/', '_'));
687 out.append('_').append(fi.getFieldName()).append(" = stack.pop();");
693 int indx = readIntArg(byteCodes, i);
694 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
695 out.append("{ var v = stack.pop(); stack.pop().")
696 .append(fi.getFieldName()).append(" = v; }");
701 int indx = readIntArg(byteCodes, i);
702 CPClassInfo ci = jc.getConstantPool().getClass(indx);
703 final String type = ci.getClassName().getType();
704 if (!type.startsWith("[")) {
705 // no way to check arrays right now
706 out.append("if(stack[stack.length - 1].$instOf_")
707 .append(type.replace('/', '_'))
708 .append(" != 1) throw {};"); // XXX proper exception
713 case bc_instanceof: {
714 int indx = readIntArg(byteCodes, i);
715 CPClassInfo ci = jc.getConstantPool().getClass(indx);
716 out.append("stack.push(stack.pop().$instOf_")
717 .append(ci.getClassName().getInternalName().replace('/', '_'))
718 .append(" ? 1 : 0);");
723 out.append("{ var t = stack.pop(); stack = new Array(1); stack[0] = t; throw t; }");
727 out.append("throw 'unknown bytecode " + c + "';");
732 for (int j = prev; j <= i; j++) {
734 final int cc = (byteCodes[j] + 256) % 256;
735 out.append(Integer.toString(cc));
742 private int generateIf(byte[] byteCodes, int i, final String test) throws IOException {
743 int indx = i + readIntArg(byteCodes, i);
744 out.append("if (stack.pop() ").append(test).append(" stack.pop()) { gt = " + indx);
745 out.append("; continue; }");
749 private int readIntArg(byte[] byteCodes, int offsetInstruction) {
750 final int indxHi = byteCodes[offsetInstruction + 1] << 8;
751 final int indxLo = byteCodes[offsetInstruction + 2];
752 return (indxHi & 0xffffff00) | (indxLo & 0xff);
754 private int readInt4(byte[] byteCodes, int offsetInstruction) {
755 final int d = byteCodes[offsetInstruction + 0] << 24;
756 final int c = byteCodes[offsetInstruction + 1] << 16;
757 final int b = byteCodes[offsetInstruction + 2] << 8;
758 final int a = byteCodes[offsetInstruction + 3];
759 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
762 private static int countArgs(String descriptor, boolean[] hasReturnType, StringBuilder sig) {
765 Boolean count = null;
766 boolean array = false;
767 int firstPos = sig.length();
768 while (i < descriptor.length()) {
769 char ch = descriptor.charAt(i++);
795 hasReturnType[0] = true;
796 sig.insert(firstPos, ch);
798 sig.insert(firstPos, 'A');
805 hasReturnType[0] = false;
806 sig.insert(firstPos, 'V');
809 int next = descriptor.indexOf(';', i);
816 sig.append(descriptor.substring(i, next).replace('/', '_'));
818 sig.insert(firstPos, descriptor.substring(i, next).replace('/', '_'));
819 sig.insert(firstPos, ch);
821 sig.insert(firstPos, 'A');
823 hasReturnType[0] = true;
831 break; // invalid character
837 private void generateStaticField(Variable v) throws IOException {
839 .append(jc.getName().getInternalName().replace('/', '_'))
840 .append('_').append(v.getName()).append(" = 0;");
843 private String findMethodName(Method m) {
844 StringBuilder name = new StringBuilder();
845 String descr = m.getDescriptor();
846 if ("<init>".equals(m.getName())) { // NOI18N
847 name.append("cons"); // NOI18N
848 } else if ("<clinit>".equals(m.getName())) { // NOI18N
849 name.append("class"); // NOI18N
851 name.append(m.getName());
854 boolean hasReturn[] = { false };
855 countArgs(findDescriptor(m.getDescriptor()), hasReturn, name);
856 return name.toString();
859 private String findMethodName(CPMethodInfo mi, int[] cnt, boolean[] hasReturn) {
860 StringBuilder name = new StringBuilder();
861 String descr = mi.getDescriptor();
862 if ("<init>".equals(mi.getName())) { // NOI18N
863 name.append("cons"); // NOI18N
865 name.append(mi.getName());
867 cnt[0] = countArgs(findDescriptor(mi.getDescriptor()), hasReturn, name);
868 return name.toString();
871 private int invokeStaticMethod(byte[] byteCodes, int i, boolean isStatic)
873 int methodIndex = readIntArg(byteCodes, i);
874 CPMethodInfo mi = (CPMethodInfo) jc.getConstantPool().get(methodIndex);
875 boolean[] hasReturn = { false };
877 String mn = findMethodName(mi, cnt, hasReturn);
879 for (int j = cnt[0] - 1; j >= 0; j--) {
880 out.append("var v" + j).append(" = stack.pop(); ");
884 out.append("stack.push(");
886 final String in = mi.getClassName().getInternalName();
887 out.append(in.replace('/', '_'));
889 out.append(".prototype.");
897 out.append("stack.pop()");
900 for (int j = 0; j < cnt[0]; j++) {
914 private int invokeVirtualMethod(byte[] byteCodes, int i)
916 int methodIndex = readIntArg(byteCodes, i);
917 CPMethodInfo mi = (CPMethodInfo) jc.getConstantPool().get(methodIndex);
918 boolean[] hasReturn = { false };
920 String mn = findMethodName(mi, cnt, hasReturn);
922 for (int j = cnt[0] - 1; j >= 0; j--) {
923 out.append("var v" + j).append(" = stack.pop(); ");
925 out.append("var self = stack.pop(); ");
927 out.append("stack.push(");
933 for (int j = 0; j < cnt[0]; j++) {
946 private void addReference(String cn) throws IOException {
947 out.append(" /* needs ").append(cn).append(" */");
948 if (references != null) {
953 private void outType(String d, StringBuilder out) {
955 while (d.charAt(0) == '[') {
959 if (d.charAt(0) == 'L') {
960 assert d.charAt(d.length() - 1) == ';';
961 out.append(d.replace('/', '_').substring(0, d.length() - 1));
967 private String encodeConstant(CPEntry entry) {
969 if (entry instanceof CPClassInfo) {
970 v = "new java_lang_Class";
971 } else if (entry instanceof CPStringInfo) {
972 v = "\"" + entry.getValue().toString().replace("\"", "\\\"") + "\"";
974 v = entry.getValue().toString();
979 private String findDescriptor(String d) {
980 return d.replace('[', 'A');
983 private boolean javaScriptBody(Method m, boolean isStatic) throws IOException {
984 final ClassName extraAnn = ClassName.getClassName(JavaScriptBody.class.getName().replace('.', '/'));
985 Annotation a = m.getAnnotation(extraAnn);
987 final ElementValue annVal = a.getComponent("body").getValue();
988 String body = ((PrimitiveElementValue) annVal).getValue().getValue().toString();
990 final ArrayElementValue arrVal = (ArrayElementValue) a.getComponent("args").getValue();
991 final int len = arrVal.getValues().length;
992 String[] names = new String[len];
993 for (int i = 0; i < len; i++) {
994 names[i] = ((PrimitiveElementValue) arrVal.getValues()[i]).getValue().getValue().toString();
996 out.append("\nfunction ").append(
997 jc.getName().getInternalName().replace('/', '_')).append('_').append(findMethodName(m));
1002 out.append(names[0]);
1009 List<Parameter> args = m.getParameters();
1010 for (int i = 0; i < args.size(); i++) {
1012 out.append(names[index]);
1013 final String desc = findDescriptor(args.get(i).getDescriptor());
1017 out.append(") {").append("\n");
1019 out.append("\n}\n");