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
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;");
122 ClassName sc = jc.getSuperClass();
124 out.append("\n").append(className)
125 .append(".prototype = new ").append(sc.getInternalName().replace('/', '_')).append(';');
127 for (Method m : jc.getMethods()) {
128 if (!m.isStatic() && !m.isPrivate() && !m.getName().contains("<init>")) {
129 compiler.generateMethodReference("\n" + className + ".prototype.", m);
132 out.append("\n" + className + ".prototype.$instOf_").append(className).append(" = true;");
133 for (ClassName superInterface : jc.getInterfaces()) {
134 out.append("\n" + className + ".prototype.$instOf_").append(superInterface.getInternalName().replace('/', '_')).append(" = true;");
137 StringBuilder sb = new StringBuilder();
138 for (String init : toInitilize) {
139 sb.append("\n").append(init).append("();");
141 return sb.toString();
143 private void generateStaticMethod(Method m, List<String> toInitilize) throws IOException {
144 if (javaScriptBody(m, true)) {
147 final String mn = findMethodName(m);
148 out.append("\nfunction ").append(
149 jc.getName().getInternalName().replace('/', '_')
150 ).append('_').append(mn);
151 if (mn.equals("classV")) {
152 toInitilize.add(jc.getName().getInternalName().replace('/', '_') + '_' + mn);
156 List<Parameter> args = m.getParameters();
157 for (int index = 0, i = 0; i < args.size(); i++) {
159 out.append("arg").append(String.valueOf(index));
161 final String desc = findDescriptor(args.get(i).getDescriptor());
162 if ("D".equals(desc) || "J".equals(desc)) {
168 out.append(") {").append("\n");
169 final Code code = m.getCode();
171 int len = code.getMaxLocals();
172 for (int index = args.size(), i = args.size(); i < len; i++) {
174 out.append("arg").append(String.valueOf(i)).append(";\n");
176 out.append(" var stack = new Array();\n");
177 produceCode(code.getByteCodes());
179 out.append(" /* no code found for ").append(m.getTypeSignature()).append(" */\n");
184 private void generateMethodReference(String prefix, Method m) throws IOException {
185 final String name = findMethodName(m);
186 out.append(prefix).append(name).append(" = ")
187 .append(jc.getName().getInternalName().replace('/', '_'))
188 .append('_').append(name).append(";");
191 private void generateInstanceMethod(Method m) throws IOException {
192 if (javaScriptBody(m, false)) {
195 out.append("\nfunction ").append(
196 jc.getName().getInternalName().replace('/', '_')
197 ).append('_').append(findMethodName(m));
200 List<Parameter> args = m.getParameters();
201 for (int index = 1, i = 0; i < args.size(); i++) {
203 out.append("arg").append(String.valueOf(index));
204 final String desc = findDescriptor(args.get(i).getDescriptor());
205 if ("D".equals(desc) || "J".equals(desc)) {
211 out.append(") {").append("\n");
212 final Code code = m.getCode();
214 int len = code.getMaxLocals();
215 for (int index = args.size(), i = args.size(); i < len; i++) {
217 out.append("arg").append(String.valueOf(i + 1)).append(";\n");
219 out.append(";\n var stack = new Array();\n");
220 produceCode(code.getByteCodes());
222 out.append(" /* no code found for ").append(m.getTypeSignature()).append(" */\n");
227 private void produceCode(byte[] byteCodes) throws IOException {
228 out.append("\n var gt = 0;\n for(;;) switch(gt) {\n");
229 for (int i = 0; i < byteCodes.length; i++) {
231 out.append(" case " + i).append(": ");
232 final int c = (byteCodes[i] + 256) % 256;
239 out.append("stack.push(arg0);");
246 out.append("stack.push(arg1);");
253 out.append("stack.push(arg2);");
260 out.append("stack.push(arg3);");
267 final int indx = (byteCodes[++i] + 256) % 256;
268 out.append("stack.push(arg").append(indx + ");");
276 final int indx = (byteCodes[++i] + 256) % 256;
277 out.append("arg" + indx).append(" = stack.pop()");
285 out.append("arg0 = stack.pop();");
292 out.append("arg1 = stack.pop();");
299 out.append("arg2 = stack.pop();");
306 out.append("arg3 = stack.pop();");
312 out.append("stack.push(stack.pop() + stack.pop());");
318 out.append("{ var tmp = stack.pop(); stack.push(stack.pop() - tmp); }");
324 out.append("stack.push(stack.pop() * stack.pop());");
328 out.append("{ var tmp = stack.pop(); stack.push(Math.floor(stack.pop() / tmp)); }");
332 out.append("{ var tmp = stack.pop(); stack.push(stack.pop() / tmp); }");
336 out.append("stack.push(stack.pop() & stack.pop());");
340 out.append("stack.push(stack.pop() | stack.pop());");
344 out.append("stack.push(stack.pop() ^ stack.pop());");
350 out.append("stack.push(- stack.pop());");
354 out.append("{ var v = stack.pop(); stack.push(stack.pop() << v); }");
358 out.append("{ var v = stack.pop(); stack.push(stack.pop() >> v); }");
362 out.append("{ var v = stack.pop(); stack.push(stack.pop() >>> v); }");
365 final int varIndx = (byteCodes[++i] + 256) % 256;
366 final int incrBy = (byteCodes[++i] + 256) % 256;
368 out.append("arg" + varIndx).append("++;");
370 out.append("arg" + varIndx).append(" += " + incrBy).append(";");
375 out.append("return;");
382 out.append("return stack.pop();");
393 out.append("/* number conversion */");
399 out.append("stack.push(Math.floor(stack.pop()));");
404 out.append("/* number conversion */");
407 out.append("stack.push(null);");
410 out.append("stack.push(-1);");
416 out.append("stack.push(0);");
422 out.append("stack.push(1);");
426 out.append("stack.push(2);");
429 out.append("stack.push(3);");
432 out.append("stack.push(4);");
435 out.append("stack.push(5);");
438 int indx = byteCodes[++i];
439 CPEntry entry = jc.getConstantPool().get(indx);
440 String v = encodeConstant(entry);
441 out.append("stack.push(").append(v).append(");");
446 int indx = readIntArg(byteCodes, i);
447 CPEntry entry = jc.getConstantPool().get(indx);
449 String v = encodeConstant(entry);
450 out.append("stack.push(").append(v).append(");");
458 out.append("{ var delta = stack.pop() - stack.pop(); stack.push(delta < 0 ?-1 : (delta == 0 ? 0 : 1)); }");
462 i = generateIf(byteCodes, i, "==");
466 int indx = i + readIntArg(byteCodes, i);
467 out.append("if (stack.pop() == 0) { gt = " + indx);
468 out.append("; continue; }");
473 int indx = i + readIntArg(byteCodes, i);
474 out.append("if (stack.pop() != 0) { gt = " + indx);
475 out.append("; continue; }");
480 int indx = i + readIntArg(byteCodes, i);
481 out.append("if (stack.pop() < 0) { gt = " + indx);
482 out.append("; continue; }");
487 int indx = i + readIntArg(byteCodes, i);
488 out.append("if (stack.pop() <= 0) { gt = " + indx);
489 out.append("; continue; }");
494 int indx = i + readIntArg(byteCodes, i);
495 out.append("if (stack.pop() > 0) { gt = " + indx);
496 out.append("; continue; }");
501 int indx = i + readIntArg(byteCodes, i);
502 out.append("if (stack.pop() >= 0) { gt = " + indx);
503 out.append("; continue; }");
508 int indx = i + readIntArg(byteCodes, i);
509 out.append("if (stack.pop()) { gt = " + indx);
510 out.append("; continue; }");
515 int indx = i + readIntArg(byteCodes, i);
516 out.append("if (!stack.pop()) { gt = " + indx);
517 out.append("; continue; }");
522 i = generateIf(byteCodes, i, "!=");
525 i = generateIf(byteCodes, i, ">");
528 i = generateIf(byteCodes, i, ">=");
531 i = generateIf(byteCodes, i, "<");
534 i = generateIf(byteCodes, i, "<=");
537 int indx = i + readIntArg(byteCodes, i);
538 out.append("gt = " + indx).append("; continue;");
542 case bc_invokeinterface: {
543 i = invokeVirtualMethod(byteCodes, i) + 2;
546 case bc_invokevirtual:
547 i = invokeVirtualMethod(byteCodes, i);
549 case bc_invokespecial:
550 i = invokeStaticMethod(byteCodes, i, false);
552 case bc_invokestatic:
553 i = invokeStaticMethod(byteCodes, i, true);
556 int indx = readIntArg(byteCodes, i);
557 CPClassInfo ci = jc.getConstantPool().getClass(indx);
558 out.append("stack.push(");
559 out.append("new ").append(ci.getClassName().getInternalName().replace('/','_'));
561 addReference(ci.getClassName().getInternalName());
566 int type = byteCodes[i++];
567 out.append("stack.push(new Array(stack.pop()));");
571 i += 2; // skip type of array
572 out.append("stack.push(new Array(stack.pop()));");
576 out.append("stack.push(stack.pop().length);");
586 out.append("{ var value = stack.pop(); var indx = stack.pop(); stack.pop()[indx] = value; }");
597 out.append("{ var indx = stack.pop(); stack.push(stack.pop()[indx]); }");
601 out.append("stack.pop();");
603 out.append("stack.pop();");
606 out.append("stack.push(stack[stack.length - 1]);");
609 out.append("stack.push(" + byteCodes[++i] + ");");
612 out.append("stack.push(" + readIntArg(byteCodes, i) + ");");
616 int indx = readIntArg(byteCodes, i);
617 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
618 out.append("stack.push(stack.pop().").append(fi.getFieldName()).append(");");
623 int indx = readIntArg(byteCodes, i);
624 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
625 final String in = fi.getClassName().getInternalName();
626 out.append("stack.push(").append(in.replace('/', '_'));
627 out.append('_').append(fi.getFieldName()).append(");");
633 int indx = readIntArg(byteCodes, i);
634 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
635 final String in = fi.getClassName().getInternalName();
636 out.append(in.replace('/', '_'));
637 out.append('_').append(fi.getFieldName()).append(" = stack.pop();");
643 int indx = readIntArg(byteCodes, i);
644 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
645 out.append("{ var v = stack.pop(); stack.pop().")
646 .append(fi.getFieldName()).append(" = v; }");
651 int indx = readIntArg(byteCodes, i);
652 CPClassInfo ci = jc.getConstantPool().getClass(indx);
653 final String type = ci.getClassName().getType();
654 if (!type.startsWith("[")) {
655 // no way to check arrays right now
656 out.append("if(stack[stack.length - 1].$instOf_")
657 .append(type.replace('/', '_'))
658 .append(" != 1) throw {};"); // XXX proper exception
663 case bc_instanceof: {
664 int indx = readIntArg(byteCodes, i);
665 CPClassInfo ci = jc.getConstantPool().getClass(indx);
666 out.append("stack.push(stack.pop().$instOf_")
667 .append(ci.getClassName().getInternalName().replace('/', '_'))
668 .append(" ? 1 : 0);");
675 for (int j = prev; j <= i; j++) {
677 final int cc = (byteCodes[j] + 256) % 256;
678 out.append(Integer.toString(cc));
685 private int generateIf(byte[] byteCodes, int i, final String test) throws IOException {
686 int indx = i + readIntArg(byteCodes, i);
687 out.append("if (stack.pop() ").append(test).append(" stack.pop()) { gt = " + indx);
688 out.append("; continue; }");
692 private int readIntArg(byte[] byteCodes, int offsetInstruction) {
693 final int indxHi = byteCodes[offsetInstruction + 1] << 8;
694 final int indxLo = byteCodes[offsetInstruction + 2];
695 return (indxHi & 0xffffff00) | (indxLo & 0xff);
698 private static int countArgs(String descriptor, boolean[] hasReturnType, StringBuilder sig) {
701 Boolean count = null;
702 boolean array = false;
703 int firstPos = sig.length();
704 while (i < descriptor.length()) {
705 char ch = descriptor.charAt(i++);
731 hasReturnType[0] = true;
732 sig.insert(firstPos, ch);
734 sig.insert(firstPos, 'A');
741 hasReturnType[0] = false;
742 sig.insert(firstPos, 'V');
745 int next = descriptor.indexOf(';', i);
752 sig.append(descriptor.substring(i, next).replace('/', '_'));
754 sig.insert(firstPos, descriptor.substring(i, next).replace('/', '_'));
755 sig.insert(firstPos, ch);
757 sig.insert(firstPos, 'A');
759 hasReturnType[0] = true;
767 break; // invalid character
773 private void generateStaticField(Variable v) throws IOException {
775 .append(jc.getName().getInternalName().replace('/', '_'))
776 .append('_').append(v.getName()).append(" = 0;");
779 private String findMethodName(Method m) {
780 StringBuilder name = new StringBuilder();
781 String descr = m.getDescriptor();
782 if ("<init>".equals(m.getName())) { // NOI18N
783 name.append("cons"); // NOI18N
784 } else if ("<clinit>".equals(m.getName())) { // NOI18N
785 name.append("class"); // NOI18N
787 name.append(m.getName());
790 boolean hasReturn[] = { false };
791 countArgs(findDescriptor(m.getDescriptor()), hasReturn, name);
792 return name.toString();
795 private String findMethodName(CPMethodInfo mi, int[] cnt, boolean[] hasReturn) {
796 StringBuilder name = new StringBuilder();
797 String descr = mi.getDescriptor();
798 if ("<init>".equals(mi.getName())) { // NOI18N
799 name.append("cons"); // NOI18N
801 name.append(mi.getName());
803 cnt[0] = countArgs(findDescriptor(mi.getDescriptor()), hasReturn, name);
804 return name.toString();
807 private int invokeStaticMethod(byte[] byteCodes, int i, boolean isStatic)
809 int methodIndex = readIntArg(byteCodes, i);
810 CPMethodInfo mi = (CPMethodInfo) jc.getConstantPool().get(methodIndex);
811 boolean[] hasReturn = { false };
813 String mn = findMethodName(mi, cnt, hasReturn);
815 for (int j = cnt[0] - 1; j >= 0; j--) {
816 out.append("var v" + j).append(" = stack.pop(); ");
820 out.append("stack.push(");
822 final String in = mi.getClassName().getInternalName();
823 out.append(in.replace('/', '_'));
829 out.append("stack.pop()");
832 for (int j = 0; j < cnt[0]; j++) {
846 private int invokeVirtualMethod(byte[] byteCodes, int i)
848 int methodIndex = readIntArg(byteCodes, i);
849 CPMethodInfo mi = (CPMethodInfo) jc.getConstantPool().get(methodIndex);
850 boolean[] hasReturn = { false };
852 String mn = findMethodName(mi, cnt, hasReturn);
854 for (int j = cnt[0] - 1; j >= 0; j--) {
855 out.append("var v" + j).append(" = stack.pop(); ");
857 out.append("var self = stack.pop(); ");
859 out.append("stack.push(");
865 for (int j = 0; j < cnt[0]; j++) {
878 private void addReference(String cn) {
879 if (references != null) {
884 private void outType(String d, StringBuilder out) {
886 while (d.charAt(0) == '[') {
890 if (d.charAt(0) == 'L') {
891 assert d.charAt(d.length() - 1) == ';';
892 out.append(d.replace('/', '_').substring(0, d.length() - 1));
898 private String encodeConstant(CPEntry entry) {
900 if (entry instanceof CPClassInfo) {
901 v = "new java_lang_Class";
902 } else if (entry instanceof CPStringInfo) {
903 v = "\"" + entry.getValue().toString().replace("\"", "\\\"") + "\"";
905 v = entry.getValue().toString();
910 private String findDescriptor(String d) {
911 return d.replace('[', 'A');
914 private boolean javaScriptBody(Method m, boolean isStatic) throws IOException {
915 final ClassName extraAnn = ClassName.getClassName(JavaScriptBody.class.getName().replace('.', '/'));
916 Annotation a = m.getAnnotation(extraAnn);
918 final ElementValue annVal = a.getComponent("body").getValue();
919 String body = ((PrimitiveElementValue) annVal).getValue().getValue().toString();
921 final ArrayElementValue arrVal = (ArrayElementValue) a.getComponent("args").getValue();
922 final int len = arrVal.getValues().length;
923 String[] names = new String[len];
924 for (int i = 0; i < len; i++) {
925 names[i] = ((PrimitiveElementValue) arrVal.getValues()[i]).getValue().getValue().toString();
927 out.append("\nfunction ").append(
928 jc.getName().getInternalName().replace('/', '_')).append('_').append(findMethodName(m));
933 out.append(names[0]);
940 List<Parameter> args = m.getParameters();
941 for (int i = 0; i < args.size(); i++) {
943 out.append(names[index]);
944 final String desc = findDescriptor(args.get(i).getDescriptor());
947 out.append(") {").append("\n");