2 Java 4 Browser Bytecode Translator
3 Copyright (C) 2012-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
74 * @throws IOException if something goes wrong during read or write or translating
77 public static void compile(
78 InputStream classFile, Appendable out,
79 Collection<? super String> references,
80 Collection<? super String> scripts
81 ) throws IOException {
82 ClassFile jc = new ClassFile(classFile, true);
83 final ClassName extraAnn = ClassName.getClassName(ExtraJavaScript.class.getName().replace('.', '/'));
84 Annotation a = jc.getAnnotation(extraAnn);
86 final ElementValue annVal = a.getComponent("resource").getValue();
87 String res = ((PrimitiveElementValue)annVal).getValue().getValue().toString();
89 final AnnotationComponent process = a.getComponent("processByteCode");
90 if (process != null && "const=0".equals(process.getValue().toString())) {
95 ByteCodeToJavaScript compiler = new ByteCodeToJavaScript(
98 List<String> toInitilize = new ArrayList<String>();
99 for (Method m : jc.getMethods()) {
101 compiler.generateStaticMethod(m, toInitilize);
103 compiler.generateInstanceMethod(m);
106 for (Variable v : jc.getVariables()) {
108 compiler.generateStaticField(v);
112 final String className = jc.getName().getInternalName().replace('/', '_');
113 out.append("\nfunction ").append(className);
115 for (Variable v : jc.getVariables()) {
117 out.append("\n this." + v.getName() + " = 0;");
121 ClassName sc = jc.getSuperClass();
123 out.append("\n").append(className)
124 .append(".prototype = new ").append(sc.getInternalName().replace('/', '_')).append(';');
126 for (Method m : jc.getMethods()) {
127 if (!m.isStatic() && !m.isPrivate() && !m.getName().contains("<init>")) {
128 compiler.generateMethodReference("\n" + className + ".prototype.", m);
131 out.append("\n" + className + ".prototype.$instOf_").append(className).append(" = true;");
132 for (ClassName superInterface : jc.getInterfaces()) {
133 out.append("\n" + className + ".prototype.$instOf_").append(superInterface.getInternalName().replace('/', '_')).append(" = true;");
135 for (String init : toInitilize) {
136 out.append("\n").append(init).append("();");
139 private void generateStaticMethod(Method m, List<String> toInitilize) throws IOException {
140 if (javaScriptBody(m, true)) {
143 final String mn = findMethodName(m);
144 out.append("\nfunction ").append(
145 jc.getName().getInternalName().replace('/', '_')
146 ).append('_').append(mn);
147 if (mn.equals("classV")) {
148 toInitilize.add(jc.getName().getInternalName().replace('/', '_') + '_' + mn);
152 List<Parameter> args = m.getParameters();
153 for (int index = 0, i = 0; i < args.size(); i++) {
155 out.append("arg").append(String.valueOf(index));
157 final String desc = findDescriptor(args.get(i).getDescriptor());
158 if ("D".equals(desc) || "J".equals(desc)) {
164 out.append(") {").append("\n");
165 final Code code = m.getCode();
167 int len = code.getMaxLocals();
168 for (int index = args.size(), i = args.size(); i < len; i++) {
170 out.append("arg").append(String.valueOf(i)).append(";\n");
172 out.append(" var stack = new Array();\n");
173 produceCode(code.getByteCodes());
175 out.append(" /* no code found for ").append(m.getTypeSignature()).append(" */\n");
180 private void generateMethodReference(String prefix, Method m) throws IOException {
181 final String name = findMethodName(m);
182 out.append(prefix).append(name).append(" = ")
183 .append(jc.getName().getInternalName().replace('/', '_'))
184 .append('_').append(name).append(";");
187 private void generateInstanceMethod(Method m) throws IOException {
188 if (javaScriptBody(m, false)) {
191 out.append("\nfunction ").append(
192 jc.getName().getInternalName().replace('/', '_')
193 ).append('_').append(findMethodName(m));
196 List<Parameter> args = m.getParameters();
197 for (int index = 1, i = 0; i < args.size(); i++) {
199 out.append("arg").append(String.valueOf(index));
200 final String desc = findDescriptor(args.get(i).getDescriptor());
201 if ("D".equals(desc) || "J".equals(desc)) {
207 out.append(") {").append("\n");
208 final Code code = m.getCode();
210 int len = code.getMaxLocals();
211 for (int index = args.size(), i = args.size(); i < len; i++) {
213 out.append("arg").append(String.valueOf(i + 1)).append(";\n");
215 out.append(";\n var stack = new Array();\n");
216 produceCode(code.getByteCodes());
218 out.append(" /* no code found for ").append(m.getTypeSignature()).append(" */\n");
223 private void produceCode(byte[] byteCodes) throws IOException {
224 out.append("\n var gt = 0;\n for(;;) switch(gt) {\n");
225 for (int i = 0; i < byteCodes.length; i++) {
227 out.append(" case " + i).append(": ");
228 final int c = (byteCodes[i] + 256) % 256;
235 out.append("stack.push(arg0);");
242 out.append("stack.push(arg1);");
249 out.append("stack.push(arg2);");
256 out.append("stack.push(arg3);");
263 final int indx = (byteCodes[++i] + 256) % 256;
264 out.append("stack.push(arg").append(indx + ");");
272 final int indx = (byteCodes[++i] + 256) % 256;
273 out.append("arg" + indx).append(" = stack.pop()");
281 out.append("arg0 = stack.pop();");
288 out.append("arg1 = stack.pop();");
295 out.append("arg2 = stack.pop();");
302 out.append("arg3 = stack.pop();");
308 out.append("stack.push(stack.pop() + stack.pop());");
314 out.append("{ var tmp = stack.pop(); stack.push(stack.pop() - tmp); }");
320 out.append("stack.push(stack.pop() * stack.pop());");
324 out.append("{ var tmp = stack.pop(); stack.push(Math.floor(stack.pop() / tmp)); }");
328 out.append("{ var tmp = stack.pop(); stack.push(stack.pop() / tmp); }");
332 out.append("stack.push(stack.pop() & stack.pop());");
336 out.append("stack.push(stack.pop() | stack.pop());");
340 out.append("stack.push(stack.pop() ^ stack.pop());");
346 out.append("stack.push(- stack.pop());");
350 out.append("{ var v = stack.pop(); stack.push(stack.pop() << v); }");
354 out.append("{ var v = stack.pop(); stack.push(stack.pop() >> v); }");
358 out.append("{ var v = stack.pop(); stack.push(stack.pop() >>> v); }");
361 final int varIndx = (byteCodes[++i] + 256) % 256;
362 final int incrBy = (byteCodes[++i] + 256) % 256;
364 out.append("arg" + varIndx).append("++;");
366 out.append("arg" + varIndx).append(" += " + incrBy).append(";");
371 out.append("return;");
378 out.append("return stack.pop();");
389 out.append("/* number conversion */");
395 out.append("stack.push(Math.floor(stack.pop()));");
400 out.append("/* number conversion */");
403 out.append("stack.push(null);");
406 out.append("stack.push(-1);");
412 out.append("stack.push(0);");
418 out.append("stack.push(1);");
422 out.append("stack.push(2);");
425 out.append("stack.push(3);");
428 out.append("stack.push(4);");
431 out.append("stack.push(5);");
434 int indx = byteCodes[++i];
435 CPEntry entry = jc.getConstantPool().get(indx);
436 String v = encodeConstant(entry);
437 out.append("stack.push(").append(v).append(");");
442 int indx = readIntArg(byteCodes, i);
443 CPEntry entry = jc.getConstantPool().get(indx);
445 String v = encodeConstant(entry);
446 out.append("stack.push(").append(v).append(");");
454 out.append("{ var delta = stack.pop() - stack.pop(); stack.push(delta < 0 ?-1 : (delta == 0 ? 0 : 1)); }");
458 i = generateIf(byteCodes, i, "==");
462 int indx = i + readIntArg(byteCodes, i);
463 out.append("if (stack.pop() == 0) { gt = " + indx);
464 out.append("; continue; }");
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()) { gt = " + indx);
506 out.append("; continue; }");
511 int indx = i + readIntArg(byteCodes, i);
512 out.append("if (!stack.pop()) { gt = " + indx);
513 out.append("; continue; }");
518 i = generateIf(byteCodes, i, "!=");
521 i = generateIf(byteCodes, i, ">");
524 i = generateIf(byteCodes, i, ">=");
527 i = generateIf(byteCodes, i, "<");
530 i = generateIf(byteCodes, i, "<=");
533 int indx = i + readIntArg(byteCodes, i);
534 out.append("gt = " + indx).append("; continue;");
538 case bc_invokeinterface: {
539 i = invokeVirtualMethod(byteCodes, i) + 2;
542 case bc_invokevirtual:
543 i = invokeVirtualMethod(byteCodes, i);
545 case bc_invokespecial:
546 i = invokeStaticMethod(byteCodes, i, false);
548 case bc_invokestatic:
549 i = invokeStaticMethod(byteCodes, i, true);
552 int indx = readIntArg(byteCodes, i);
553 CPClassInfo ci = jc.getConstantPool().getClass(indx);
554 out.append("stack.push(");
555 out.append("new ").append(ci.getClassName().getInternalName().replace('/','_'));
557 addReference(ci.getClassName().getInternalName());
562 int type = byteCodes[i++];
563 out.append("stack.push(new Array(stack.pop()));");
567 i += 2; // skip type of array
568 out.append("stack.push(new Array(stack.pop()));");
572 out.append("stack.push(stack.pop().length);");
582 out.append("{ var value = stack.pop(); var indx = stack.pop(); stack.pop()[indx] = value; }");
593 out.append("{ var indx = stack.pop(); stack.push(stack.pop()[indx]); }");
597 out.append("stack.pop();");
599 out.append("stack.pop();");
602 out.append("stack.push(stack[stack.length - 1]);");
605 out.append("stack.push(" + byteCodes[++i] + ");");
608 out.append("stack.push(" + readIntArg(byteCodes, i) + ");");
612 int indx = readIntArg(byteCodes, i);
613 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
614 out.append("stack.push(stack.pop().").append(fi.getFieldName()).append(");");
619 int indx = readIntArg(byteCodes, i);
620 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
621 final String in = fi.getClassName().getInternalName();
622 out.append("stack.push(").append(in.replace('/', '_'));
623 out.append('_').append(fi.getFieldName()).append(");");
629 int indx = readIntArg(byteCodes, i);
630 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
631 final String in = fi.getClassName().getInternalName();
632 out.append(in.replace('/', '_'));
633 out.append('_').append(fi.getFieldName()).append(" = stack.pop();");
639 int indx = readIntArg(byteCodes, i);
640 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
641 out.append("{ var v = stack.pop(); stack.pop().")
642 .append(fi.getFieldName()).append(" = v; }");
647 int indx = readIntArg(byteCodes, i);
648 CPClassInfo ci = jc.getConstantPool().getClass(indx);
649 final String type = ci.getClassName().getType();
650 if (!type.startsWith("[")) {
651 // no way to check arrays right now
652 out.append("if(stack[stack.length - 1].$instOf_")
653 .append(type.replace('/', '_'))
654 .append(" != 1) throw {};"); // XXX proper exception
659 case bc_instanceof: {
660 int indx = readIntArg(byteCodes, i);
661 CPClassInfo ci = jc.getConstantPool().getClass(indx);
662 out.append("stack.push(stack.pop().$instOf_")
663 .append(ci.getClassName().getInternalName().replace('/', '_'))
664 .append(" ? 1 : 0);");
671 for (int j = prev; j <= i; j++) {
673 final int cc = (byteCodes[j] + 256) % 256;
674 out.append(Integer.toString(cc));
681 private int generateIf(byte[] byteCodes, int i, final String test) throws IOException {
682 int indx = i + readIntArg(byteCodes, i);
683 out.append("if (stack.pop() ").append(test).append(" stack.pop()) { gt = " + indx);
684 out.append("; continue; }");
688 private int readIntArg(byte[] byteCodes, int offsetInstruction) {
689 final int indxHi = byteCodes[offsetInstruction + 1] << 8;
690 final int indxLo = byteCodes[offsetInstruction + 2];
691 return (indxHi & 0xffffff00) | (indxLo & 0xff);
694 private static int countArgs(String descriptor, boolean[] hasReturnType, StringBuilder sig) {
697 Boolean count = null;
698 boolean array = false;
699 int firstPos = sig.length();
700 while (i < descriptor.length()) {
701 char ch = descriptor.charAt(i++);
727 hasReturnType[0] = true;
728 sig.insert(firstPos, ch);
730 sig.insert(firstPos, 'A');
737 hasReturnType[0] = false;
738 sig.insert(firstPos, 'V');
741 int next = descriptor.indexOf(';', i);
748 sig.append(descriptor.substring(i, next).replace('/', '_'));
750 sig.insert(firstPos, descriptor.substring(i, next).replace('/', '_'));
751 sig.insert(firstPos, ch);
753 sig.insert(firstPos, 'A');
755 hasReturnType[0] = true;
763 break; // invalid character
769 private void generateStaticField(Variable v) throws IOException {
771 .append(jc.getName().getInternalName().replace('/', '_'))
772 .append('_').append(v.getName()).append(" = 0;");
775 private String findMethodName(Method m) {
776 StringBuilder name = new StringBuilder();
777 String descr = m.getDescriptor();
778 if ("<init>".equals(m.getName())) { // NOI18N
779 name.append("cons"); // NOI18N
780 } else if ("<clinit>".equals(m.getName())) { // NOI18N
781 name.append("class"); // NOI18N
783 name.append(m.getName());
786 boolean hasReturn[] = { false };
787 countArgs(findDescriptor(m.getDescriptor()), hasReturn, name);
788 return name.toString();
791 private String findMethodName(CPMethodInfo mi, int[] cnt, boolean[] hasReturn) {
792 StringBuilder name = new StringBuilder();
793 String descr = mi.getDescriptor();
794 if ("<init>".equals(mi.getName())) { // NOI18N
795 name.append("cons"); // NOI18N
797 name.append(mi.getName());
799 cnt[0] = countArgs(findDescriptor(mi.getDescriptor()), hasReturn, name);
800 return name.toString();
803 private int invokeStaticMethod(byte[] byteCodes, int i, boolean isStatic)
805 int methodIndex = readIntArg(byteCodes, i);
806 CPMethodInfo mi = (CPMethodInfo) jc.getConstantPool().get(methodIndex);
807 boolean[] hasReturn = { false };
809 String mn = findMethodName(mi, cnt, hasReturn);
811 for (int j = cnt[0] - 1; j >= 0; j--) {
812 out.append("var v" + j).append(" = stack.pop(); ");
816 out.append("stack.push(");
818 final String in = mi.getClassName().getInternalName();
819 out.append(in.replace('/', '_'));
825 out.append("stack.pop()");
828 for (int j = 0; j < cnt[0]; j++) {
842 private int invokeVirtualMethod(byte[] byteCodes, int i)
844 int methodIndex = readIntArg(byteCodes, i);
845 CPMethodInfo mi = (CPMethodInfo) jc.getConstantPool().get(methodIndex);
846 boolean[] hasReturn = { false };
848 String mn = findMethodName(mi, cnt, hasReturn);
850 for (int j = cnt[0] - 1; j >= 0; j--) {
851 out.append("var v" + j).append(" = stack.pop(); ");
853 out.append("var self = stack.pop(); ");
855 out.append("stack.push(");
861 for (int j = 0; j < cnt[0]; j++) {
874 private void addReference(String cn) {
875 if (references != null) {
880 private void outType(String d, StringBuilder out) {
882 while (d.charAt(0) == '[') {
886 if (d.charAt(0) == 'L') {
887 assert d.charAt(d.length() - 1) == ';';
888 out.append(d.replace('/', '_').substring(0, d.length() - 1));
894 private String encodeConstant(CPEntry entry) {
896 if (entry instanceof CPClassInfo) {
897 v = "new java_lang_Class";
898 } else if (entry instanceof CPStringInfo) {
899 v = "\"" + entry.getValue().toString().replace("\"", "\\\"") + "\"";
901 v = entry.getValue().toString();
906 private String findDescriptor(String d) {
907 return d.replace('[', 'A');
910 private boolean javaScriptBody(Method m, boolean isStatic) throws IOException {
911 final ClassName extraAnn = ClassName.getClassName(JavaScriptBody.class.getName().replace('.', '/'));
912 Annotation a = m.getAnnotation(extraAnn);
914 final ElementValue annVal = a.getComponent("body").getValue();
915 String body = ((PrimitiveElementValue) annVal).getValue().getValue().toString();
917 final ArrayElementValue arrVal = (ArrayElementValue) a.getComponent("args").getValue();
918 final int len = arrVal.getValues().length;
919 String[] names = new String[len];
920 for (int i = 0; i < len; i++) {
921 names[i] = ((PrimitiveElementValue) arrVal.getValues()[i]).getValue().getValue().toString();
923 out.append("\nfunction ").append(
924 jc.getName().getInternalName().replace('/', '_')).append('_').append(findMethodName(m));
929 out.append(names[0]);
936 List<Parameter> args = m.getParameters();
937 for (int i = 0; i < args.size(); i++) {
939 out.append(names[index]);
940 final String desc = findDescriptor(args.get(i).getDescriptor());
943 out.append(") {").append("\n");