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(");
216 out.append(Integer.toString(code.getMaxStack()));
218 produceCode(code.getByteCodes());
220 out.append(" /* no code found for ").append(m.getTypeSignature()).append(" */\n");
225 private void produceCode(byte[] byteCodes) throws IOException {
226 out.append("\n var gt = 0;\n for(;;) switch(gt) {\n");
227 for (int i = 0; i < byteCodes.length; i++) {
229 out.append(" case " + i).append(": ");
230 final int c = (byteCodes[i] + 256) % 256;
237 out.append("stack.push(arg0);");
244 out.append("stack.push(arg1);");
251 out.append("stack.push(arg2);");
258 out.append("stack.push(arg3);");
265 final int indx = (byteCodes[++i] + 256) % 256;
266 out.append("stack.push(arg").append(indx + ");");
274 final int indx = (byteCodes[++i] + 256) % 256;
275 out.append("arg" + indx).append(" = stack.pop()");
283 out.append("arg0 = stack.pop();");
290 out.append("arg1 = stack.pop();");
297 out.append("arg2 = stack.pop();");
304 out.append("arg3 = stack.pop();");
310 out.append("stack.push(stack.pop() + stack.pop());");
316 out.append("{ var tmp = stack.pop(); stack.push(stack.pop() - tmp); }");
322 out.append("stack.push(stack.pop() * stack.pop());");
326 out.append("{ var tmp = stack.pop(); stack.push(Math.floor(stack.pop() / tmp)); }");
330 out.append("{ var tmp = stack.pop(); stack.push(stack.pop() / tmp); }");
334 out.append("stack.push(stack.pop() & stack.pop());");
338 out.append("stack.push(stack.pop() | stack.pop());");
342 out.append("stack.push(stack.pop() ^ stack.pop());");
348 out.append("stack.push(- stack.pop());");
352 out.append("{ var v = stack.pop(); stack.push(stack.pop() << v); }");
356 out.append("{ var v = stack.pop(); stack.push(stack.pop() >> v); }");
360 out.append("{ var v = stack.pop(); stack.push(stack.pop() >>> v); }");
363 final int varIndx = (byteCodes[++i] + 256) % 256;
364 final int incrBy = (byteCodes[++i] + 256) % 256;
366 out.append("arg" + varIndx).append("++;");
368 out.append("arg" + varIndx).append(" += " + incrBy).append(";");
373 out.append("return;");
380 out.append("return stack.pop();");
391 out.append("/* number conversion */");
397 out.append("stack.push(Math.floor(stack.pop()));");
402 out.append("/* number conversion */");
405 out.append("stack.push(null);");
408 out.append("stack.push(-1);");
414 out.append("stack.push(0);");
420 out.append("stack.push(1);");
424 out.append("stack.push(2);");
427 out.append("stack.push(3);");
430 out.append("stack.push(4);");
433 out.append("stack.push(5);");
436 int indx = byteCodes[++i];
437 CPEntry entry = jc.getConstantPool().get(indx);
438 String v = encodeConstant(entry);
439 out.append("stack.push(").append(v).append(");");
444 int indx = readIntArg(byteCodes, i);
445 CPEntry entry = jc.getConstantPool().get(indx);
447 String v = encodeConstant(entry);
448 out.append("stack.push(").append(v).append(");");
456 out.append("{ var delta = stack.pop() - stack.pop(); stack.push(delta < 0 ?-1 : (delta == 0 ? 0 : 1)); }");
460 i = generateIf(byteCodes, i, "==");
464 int indx = i + readIntArg(byteCodes, i);
465 out.append("if (stack.pop() == 0) { gt = " + indx);
466 out.append("; continue; }");
471 int indx = i + readIntArg(byteCodes, i);
472 out.append("if (stack.pop() != 0) { gt = " + indx);
473 out.append("; continue; }");
478 int indx = i + readIntArg(byteCodes, i);
479 out.append("if (stack.pop() < 0) { gt = " + indx);
480 out.append("; continue; }");
485 int indx = i + readIntArg(byteCodes, i);
486 out.append("if (stack.pop() <= 0) { gt = " + indx);
487 out.append("; continue; }");
492 int indx = i + readIntArg(byteCodes, i);
493 out.append("if (stack.pop() > 0) { gt = " + indx);
494 out.append("; continue; }");
499 int indx = i + readIntArg(byteCodes, i);
500 out.append("if (stack.pop() >= 0) { gt = " + indx);
501 out.append("; continue; }");
506 int indx = i + readIntArg(byteCodes, i);
507 out.append("if (stack.pop()) { gt = " + indx);
508 out.append("; continue; }");
513 int indx = i + readIntArg(byteCodes, i);
514 out.append("if (!stack.pop()) { gt = " + indx);
515 out.append("; continue; }");
520 i = generateIf(byteCodes, i, "!=");
523 i = generateIf(byteCodes, i, ">");
526 i = generateIf(byteCodes, i, ">=");
529 i = generateIf(byteCodes, i, "<");
532 i = generateIf(byteCodes, i, "<=");
535 int indx = i + readIntArg(byteCodes, i);
536 out.append("gt = " + indx).append("; continue;");
540 case bc_invokeinterface: {
541 i = invokeVirtualMethod(byteCodes, i) + 2;
544 case bc_invokevirtual:
545 i = invokeVirtualMethod(byteCodes, i);
547 case bc_invokespecial:
548 i = invokeStaticMethod(byteCodes, i, false);
550 case bc_invokestatic:
551 i = invokeStaticMethod(byteCodes, i, true);
554 int indx = readIntArg(byteCodes, i);
555 CPClassInfo ci = jc.getConstantPool().getClass(indx);
556 out.append("stack.push(");
557 out.append("new ").append(ci.getClassName().getInternalName().replace('/','_'));
559 addReference(ci.getClassName().getInternalName());
564 int type = byteCodes[i++];
565 out.append("stack.push(new Array(stack.pop()));");
569 i += 2; // skip type of array
570 out.append("stack.push(new Array(stack.pop()));");
574 out.append("stack.push(stack.pop().length);");
584 out.append("{ var value = stack.pop(); var indx = stack.pop(); stack.pop()[indx] = value; }");
595 out.append("{ var indx = stack.pop(); stack.push(stack.pop()[indx]); }");
599 out.append("stack.pop();");
601 out.append("stack.pop();");
604 out.append("stack.push(stack[stack.length - 1]);");
607 out.append("stack.push(" + byteCodes[++i] + ");");
610 out.append("stack.push(" + readIntArg(byteCodes, i) + ");");
614 int indx = readIntArg(byteCodes, i);
615 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
616 out.append("stack.push(stack.pop().").append(fi.getFieldName()).append(");");
621 int indx = readIntArg(byteCodes, i);
622 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
623 final String in = fi.getClassName().getInternalName();
624 out.append("stack.push(").append(in.replace('/', '_'));
625 out.append('_').append(fi.getFieldName()).append(");");
631 int indx = readIntArg(byteCodes, i);
632 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
633 final String in = fi.getClassName().getInternalName();
634 out.append(in.replace('/', '_'));
635 out.append('_').append(fi.getFieldName()).append(" = stack.pop();");
641 int indx = readIntArg(byteCodes, i);
642 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
643 out.append("{ var v = stack.pop(); stack.pop().")
644 .append(fi.getFieldName()).append(" = v; }");
649 int indx = readIntArg(byteCodes, i);
650 CPClassInfo ci = jc.getConstantPool().getClass(indx);
651 final String type = ci.getClassName().getType();
652 if (!type.startsWith("[")) {
653 // no way to check arrays right now
654 out.append("if(stack[stack.length - 1].$instOf_")
655 .append(type.replace('/', '_'))
656 .append(" != 1) throw {};"); // XXX proper exception
661 case bc_instanceof: {
662 int indx = readIntArg(byteCodes, i);
663 CPClassInfo ci = jc.getConstantPool().getClass(indx);
664 out.append("stack.push(stack.pop().$instOf_")
665 .append(ci.getClassName().getInternalName().replace('/', '_'))
666 .append(" ? 1 : 0);");
673 for (int j = prev; j <= i; j++) {
675 final int cc = (byteCodes[j] + 256) % 256;
676 out.append(Integer.toString(cc));
683 private int generateIf(byte[] byteCodes, int i, final String test) throws IOException {
684 int indx = i + readIntArg(byteCodes, i);
685 out.append("if (stack.pop() ").append(test).append(" stack.pop()) { gt = " + indx);
686 out.append("; continue; }");
690 private int readIntArg(byte[] byteCodes, int offsetInstruction) {
691 final int indxHi = byteCodes[offsetInstruction + 1] << 8;
692 final int indxLo = byteCodes[offsetInstruction + 2];
693 return (indxHi & 0xffffff00) | (indxLo & 0xff);
696 private static int countArgs(String descriptor, boolean[] hasReturnType, StringBuilder sig) {
699 Boolean count = null;
700 boolean array = false;
701 int firstPos = sig.length();
702 while (i < descriptor.length()) {
703 char ch = descriptor.charAt(i++);
729 hasReturnType[0] = true;
730 sig.insert(firstPos, ch);
732 sig.insert(firstPos, 'A');
739 hasReturnType[0] = false;
740 sig.insert(firstPos, 'V');
743 int next = descriptor.indexOf(';', i);
750 sig.append(descriptor.substring(i, next).replace('/', '_'));
752 sig.insert(firstPos, descriptor.substring(i, next).replace('/', '_'));
753 sig.insert(firstPos, ch);
755 sig.insert(firstPos, 'A');
757 hasReturnType[0] = true;
765 break; // invalid character
771 private void generateStaticField(Variable v) throws IOException {
773 .append(jc.getName().getInternalName().replace('/', '_'))
774 .append('_').append(v.getName()).append(" = 0;");
777 private String findMethodName(Method m) {
778 StringBuilder name = new StringBuilder();
779 String descr = m.getDescriptor();
780 if ("<init>".equals(m.getName())) { // NOI18N
781 name.append("cons"); // NOI18N
782 } else if ("<clinit>".equals(m.getName())) { // NOI18N
783 name.append("class"); // NOI18N
785 name.append(m.getName());
788 boolean hasReturn[] = { false };
789 countArgs(findDescriptor(m.getDescriptor()), hasReturn, name);
790 return name.toString();
793 private String findMethodName(CPMethodInfo mi, int[] cnt, boolean[] hasReturn) {
794 StringBuilder name = new StringBuilder();
795 String descr = mi.getDescriptor();
796 if ("<init>".equals(mi.getName())) { // NOI18N
797 name.append("cons"); // NOI18N
799 name.append(mi.getName());
801 cnt[0] = countArgs(findDescriptor(mi.getDescriptor()), hasReturn, name);
802 return name.toString();
805 private int invokeStaticMethod(byte[] byteCodes, int i, boolean isStatic)
807 int methodIndex = readIntArg(byteCodes, i);
808 CPMethodInfo mi = (CPMethodInfo) jc.getConstantPool().get(methodIndex);
809 boolean[] hasReturn = { false };
811 String mn = findMethodName(mi, cnt, hasReturn);
813 for (int j = cnt[0] - 1; j >= 0; j--) {
814 out.append("var v" + j).append(" = stack.pop(); ");
818 out.append("stack.push(");
820 final String in = mi.getClassName().getInternalName();
821 out.append(in.replace('/', '_'));
827 out.append("stack.pop()");
830 for (int j = 0; j < cnt[0]; j++) {
844 private int invokeVirtualMethod(byte[] byteCodes, int i)
846 int methodIndex = readIntArg(byteCodes, i);
847 CPMethodInfo mi = (CPMethodInfo) jc.getConstantPool().get(methodIndex);
848 boolean[] hasReturn = { false };
850 String mn = findMethodName(mi, cnt, hasReturn);
852 for (int j = cnt[0] - 1; j >= 0; j--) {
853 out.append("var v" + j).append(" = stack.pop(); ");
855 out.append("var self = stack.pop(); ");
857 out.append("stack.push(");
863 for (int j = 0; j < cnt[0]; j++) {
876 private void addReference(String cn) {
877 if (references != null) {
882 private void outType(String d, StringBuilder out) {
884 while (d.charAt(0) == '[') {
888 if (d.charAt(0) == 'L') {
889 assert d.charAt(d.length() - 1) == ';';
890 out.append(d.replace('/', '_').substring(0, d.length() - 1));
896 private String encodeConstant(CPEntry entry) {
898 if (entry instanceof CPClassInfo) {
899 v = "new java_lang_Class";
900 } else if (entry instanceof CPStringInfo) {
901 v = "\"" + entry.getValue().toString().replace("\"", "\\\"") + "\"";
903 v = entry.getValue().toString();
908 private String findDescriptor(String d) {
909 return d.replace('[', 'A');
912 private boolean javaScriptBody(Method m, boolean isStatic) throws IOException {
913 final ClassName extraAnn = ClassName.getClassName(JavaScriptBody.class.getName().replace('.', '/'));
914 Annotation a = m.getAnnotation(extraAnn);
916 final ElementValue annVal = a.getComponent("body").getValue();
917 String body = ((PrimitiveElementValue) annVal).getValue().getValue().toString();
919 final ArrayElementValue arrVal = (ArrayElementValue) a.getComponent("args").getValue();
920 final int len = arrVal.getValues().length;
921 String[] names = new String[len];
922 for (int i = 0; i < len; i++) {
923 names[i] = ((PrimitiveElementValue) arrVal.getValues()[i]).getValue().getValue().toString();
925 out.append("\nfunction ").append(
926 jc.getName().getInternalName().replace('/', '_')).append('_').append(findMethodName(m));
931 out.append(names[0]);
938 List<Parameter> args = m.getParameters();
939 for (int i = 0; i < args.size(); i++) {
941 out.append(names[index]);
942 final String desc = findDescriptor(args.get(i).getDescriptor());
945 out.append(") {").append("\n");