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.
19 Java 4 Browser Bytecode Translator
20 Copyright (C) 2012-2012 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
22 This program is free software: you can redistribute it and/or modify
23 it under the terms of the GNU General Public License as published by
24 the Free Software Foundation, version 2 of the License.
26 This program is distributed in the hope that it will be useful,
27 but WITHOUT ANY WARRANTY; without even the implied warranty of
28 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
29 GNU General Public License for more details.
31 You should have received a copy of the GNU General Public License
32 along with this program. Look for COPYING file in the top folder.
33 If not, see http://opensource.org/licenses/GPL-2.0.
35 package org.apidesign.vm4brwsr;
37 import java.io.IOException;
38 import java.io.InputStream;
39 import java.util.ArrayList;
40 import java.util.Collection;
41 import java.util.List;
42 import org.apidesign.bck2brwsr.core.ExtraJavaScript;
43 import org.apidesign.bck2brwsr.core.JavaScriptBody;
44 import org.netbeans.modules.classfile.Annotation;
45 import org.netbeans.modules.classfile.AnnotationComponent;
46 import org.netbeans.modules.classfile.ArrayElementValue;
47 import static org.netbeans.modules.classfile.ByteCodes.*;
48 import org.netbeans.modules.classfile.CPClassInfo;
49 import org.netbeans.modules.classfile.CPEntry;
50 import org.netbeans.modules.classfile.CPFieldInfo;
51 import org.netbeans.modules.classfile.CPMethodInfo;
52 import org.netbeans.modules.classfile.CPStringInfo;
53 import org.netbeans.modules.classfile.ClassFile;
54 import org.netbeans.modules.classfile.ClassName;
55 import org.netbeans.modules.classfile.Code;
56 import org.netbeans.modules.classfile.ElementValue;
57 import org.netbeans.modules.classfile.Method;
58 import org.netbeans.modules.classfile.Parameter;
59 import org.netbeans.modules.classfile.PrimitiveElementValue;
60 import org.netbeans.modules.classfile.Variable;
62 /** Translator of the code inside class files to JavaScript.
64 * @author Jaroslav Tulach <jtulach@netbeans.org>
66 public final class ByteCodeToJavaScript {
67 private final ClassFile jc;
68 private final Appendable out;
69 private final Collection<? super String> references;
71 private ByteCodeToJavaScript(
72 ClassFile jc, Appendable out, Collection<? super String> references
76 this.references = references;
80 * Converts a given class file to a JavaScript version.
82 * @param classFile input stream with code of the .class file
83 * @param out a {@link StringBuilder} or similar to generate the output to
84 * @param references a write only collection where the system adds list of
85 * other classes that were referenced and should be loaded in order the
86 * generated JavaScript code works properly. The names are in internal
87 * JVM form so String is <code>java/lang/String</code>. Can be <code>null</code>
88 * if one is not interested in knowing references
89 * @param scripts write only collection with names of resources to read
90 * @return the initialization code for this class, if any. Otherwise <code>null</code>
92 * @throws IOException if something goes wrong during read or write or translating
95 public static String compile(
96 InputStream classFile, Appendable out,
97 Collection<? super String> references,
98 Collection<? super String> scripts
99 ) throws IOException {
100 ClassFile jc = new ClassFile(classFile, true);
101 final ClassName extraAnn = ClassName.getClassName(ExtraJavaScript.class.getName().replace('.', '/'));
102 Annotation a = jc.getAnnotation(extraAnn);
104 final ElementValue annVal = a.getComponent("resource").getValue();
105 String res = ((PrimitiveElementValue)annVal).getValue().getValue().toString();
107 final AnnotationComponent process = a.getComponent("processByteCode");
108 if (process != null && "const=0".equals(process.getValue().toString())) {
113 ByteCodeToJavaScript compiler = new ByteCodeToJavaScript(
116 List<String> toInitilize = new ArrayList<String>();
117 for (Method m : jc.getMethods()) {
119 compiler.generateStaticMethod(m, toInitilize);
121 compiler.generateInstanceMethod(m);
124 for (Variable v : jc.getVariables()) {
126 compiler.generateStaticField(v);
130 final String className = jc.getName().getInternalName().replace('/', '_');
131 out.append("\nfunction ").append(className);
133 for (Variable v : jc.getVariables()) {
135 out.append("\n this." + v.getName() + " = 0;");
138 out.append("\n}\n\nfunction ").append(className).append("_proto() {");
139 out.append("\n if (").append(className).
140 append(".prototype.$instOf_").append(className).append(") {");
141 out.append("\n return ").append(className).append(".prototype;");
143 ClassName sc = jc.getSuperClass();
145 out.append("\n ").append(sc.getInternalName().replace('/', '_')).append("_proto();");
146 out.append("\n ").append(className)
147 .append(".prototype = new ").append(sc.getInternalName().replace('/', '_')).append(';');
149 for (Method m : jc.getMethods()) {
150 if (!m.getName().contains("<init>") && !m.getName().contains("<cinit>")) {
151 compiler.generateMethodReference("\n " + className + ".prototype.", m);
154 out.append("\n " + className + ".prototype.$instOf_").append(className).append(" = true;");
155 for (ClassName superInterface : jc.getInterfaces()) {
156 out.append("\n " + className + ".prototype.$instOf_").append(superInterface.getInternalName().replace('/', '_')).append(" = true;");
158 out.append("\n return ").append(className).append(".prototype;");
160 out.append("\n").append(className).append("_proto();");
161 StringBuilder sb = new StringBuilder();
162 for (String init : toInitilize) {
163 sb.append("\n").append(init).append("();");
165 return sb.toString();
167 private void generateStaticMethod(Method m, List<String> toInitilize) throws IOException {
168 if (javaScriptBody(m, true)) {
171 final String mn = findMethodName(m);
172 out.append("\nfunction ").append(
173 jc.getName().getInternalName().replace('/', '_')
174 ).append('_').append(mn);
175 if (mn.equals("classV")) {
176 toInitilize.add(jc.getName().getInternalName().replace('/', '_') + '_' + mn);
180 List<Parameter> args = m.getParameters();
181 for (int index = 0, i = 0; i < args.size(); i++) {
183 out.append("arg").append(String.valueOf(index));
185 final String desc = findDescriptor(args.get(i).getDescriptor());
186 if ("D".equals(desc) || "J".equals(desc)) {
192 out.append(") {").append("\n");
193 final Code code = m.getCode();
195 int len = code.getMaxLocals();
196 for (int index = args.size(), i = args.size(); i < len; i++) {
198 out.append("arg").append(String.valueOf(i)).append(";\n");
200 out.append(" var stack = new Array();\n");
201 produceCode(code.getByteCodes());
203 out.append(" /* no code found for ").append(m.getTypeSignature()).append(" */\n");
208 private void generateMethodReference(String prefix, Method m) throws IOException {
209 final String name = findMethodName(m);
210 out.append(prefix).append(name).append(" = ")
211 .append(jc.getName().getInternalName().replace('/', '_'))
212 .append('_').append(name).append(";");
215 private void generateInstanceMethod(Method m) throws IOException {
216 if (javaScriptBody(m, false)) {
219 out.append("\nfunction ").append(
220 jc.getName().getInternalName().replace('/', '_')
221 ).append('_').append(findMethodName(m));
224 List<Parameter> args = m.getParameters();
225 for (int index = 1, i = 0; i < args.size(); i++) {
227 out.append("arg").append(String.valueOf(index));
228 final String desc = findDescriptor(args.get(i).getDescriptor());
229 if ("D".equals(desc) || "J".equals(desc)) {
235 out.append(") {").append("\n");
236 final Code code = m.getCode();
238 int len = code.getMaxLocals();
239 for (int index = args.size(), i = args.size(); i < len; i++) {
241 out.append("arg").append(String.valueOf(i + 1)).append(";\n");
243 out.append(";\n var stack = new Array();\n");
244 produceCode(code.getByteCodes());
246 out.append(" /* no code found for ").append(m.getTypeSignature()).append(" */\n");
251 private void produceCode(byte[] byteCodes) throws IOException {
252 out.append("\n var gt = 0;\n for(;;) switch(gt) {\n");
253 for (int i = 0; i < byteCodes.length; i++) {
255 out.append(" case " + i).append(": ");
256 final int c = (byteCodes[i] + 256) % 256;
263 out.append("stack.push(arg0);");
270 out.append("stack.push(arg1);");
277 out.append("stack.push(arg2);");
284 out.append("stack.push(arg3);");
291 final int indx = (byteCodes[++i] + 256) % 256;
292 out.append("stack.push(arg").append(indx + ");");
300 final int indx = (byteCodes[++i] + 256) % 256;
301 out.append("arg" + indx).append(" = stack.pop()");
309 out.append("arg0 = stack.pop();");
316 out.append("arg1 = stack.pop();");
323 out.append("arg2 = stack.pop();");
330 out.append("arg3 = stack.pop();");
336 out.append("stack.push(stack.pop() + stack.pop());");
342 out.append("{ var tmp = stack.pop(); stack.push(stack.pop() - tmp); }");
348 out.append("stack.push(stack.pop() * stack.pop());");
352 out.append("{ var tmp = stack.pop(); stack.push(Math.floor(stack.pop() / tmp)); }");
356 out.append("{ var tmp = stack.pop(); stack.push(stack.pop() / tmp); }");
360 out.append("stack.push(stack.pop() & stack.pop());");
364 out.append("stack.push(stack.pop() | stack.pop());");
368 out.append("stack.push(stack.pop() ^ stack.pop());");
374 out.append("stack.push(- stack.pop());");
378 out.append("{ var v = stack.pop(); stack.push(stack.pop() << v); }");
382 out.append("{ var v = stack.pop(); stack.push(stack.pop() >> v); }");
386 out.append("{ var v = stack.pop(); stack.push(stack.pop() >>> v); }");
389 final int varIndx = (byteCodes[++i] + 256) % 256;
390 final int incrBy = byteCodes[++i];
392 out.append("arg" + varIndx).append("++;");
394 out.append("arg" + varIndx).append(" += " + incrBy).append(";");
399 out.append("return;");
406 out.append("return stack.pop();");
417 out.append("/* number conversion */");
423 out.append("stack.push(Math.floor(stack.pop()));");
428 out.append("/* number conversion */");
431 out.append("stack.push(null);");
434 out.append("stack.push(-1);");
440 out.append("stack.push(0);");
446 out.append("stack.push(1);");
450 out.append("stack.push(2);");
453 out.append("stack.push(3);");
456 out.append("stack.push(4);");
459 out.append("stack.push(5);");
462 int indx = byteCodes[++i];
463 CPEntry entry = jc.getConstantPool().get(indx);
464 String v = encodeConstant(entry);
465 out.append("stack.push(").append(v).append(");");
470 int indx = readIntArg(byteCodes, i);
471 CPEntry entry = jc.getConstantPool().get(indx);
473 String v = encodeConstant(entry);
474 out.append("stack.push(").append(v).append(");");
482 out.append("{ var delta = stack.pop() - stack.pop(); stack.push(delta < 0 ?-1 : (delta == 0 ? 0 : 1)); }");
486 i = generateIf(byteCodes, i, "===");
489 i = generateIf(byteCodes, i, "!=");
492 i = generateIf(byteCodes, i, "==");
496 int indx = i + readIntArg(byteCodes, i);
497 out.append("if (stack.pop() == 0) { gt = " + indx);
498 out.append("; continue; }");
503 int indx = i + readIntArg(byteCodes, i);
504 out.append("if (stack.pop() != 0) { gt = " + indx);
505 out.append("; continue; }");
510 int indx = i + readIntArg(byteCodes, i);
511 out.append("if (stack.pop() < 0) { gt = " + indx);
512 out.append("; continue; }");
517 int indx = i + readIntArg(byteCodes, i);
518 out.append("if (stack.pop() <= 0) { gt = " + indx);
519 out.append("; continue; }");
524 int indx = i + readIntArg(byteCodes, i);
525 out.append("if (stack.pop() > 0) { gt = " + indx);
526 out.append("; continue; }");
531 int indx = i + readIntArg(byteCodes, i);
532 out.append("if (stack.pop() >= 0) { gt = " + indx);
533 out.append("; continue; }");
538 int indx = i + readIntArg(byteCodes, i);
539 out.append("if (stack.pop()) { gt = " + indx);
540 out.append("; continue; }");
545 int indx = i + readIntArg(byteCodes, i);
546 out.append("if (!stack.pop()) { gt = " + indx);
547 out.append("; continue; }");
552 i = generateIf(byteCodes, i, "!=");
555 i = generateIf(byteCodes, i, ">");
558 i = generateIf(byteCodes, i, ">=");
561 i = generateIf(byteCodes, i, "<");
564 i = generateIf(byteCodes, i, "<=");
567 int indx = i + readIntArg(byteCodes, i);
568 out.append("gt = " + indx).append("; continue;");
572 case bc_lookupswitch: {
573 int table = (i - 1) / 4 * 4 + 4;
574 int dflt = i + readInt4(byteCodes, table);
576 int n = readInt4(byteCodes, table);
578 out.append("switch (stack.pop()) {\n");
580 int cnstnt = readInt4(byteCodes, table);
582 int offset = i + readInt4(byteCodes, table);
584 out.append(" case " + cnstnt).append(": gt = " + offset).append("; continue;\n");
586 out.append(" default: gt = " + dflt).append("; continue;\n}");
590 case bc_tableswitch: {
591 int table = (i - 1) / 4 * 4 + 4;
592 int dflt = i + readInt4(byteCodes, table);
594 int low = readInt4(byteCodes, table);
596 int high = readInt4(byteCodes, table);
598 out.append("switch (stack.pop()) {\n");
599 while (low <= high) {
600 int offset = i + readInt4(byteCodes, table);
602 out.append(" case " + low).append(": gt = " + offset).append("; continue;\n");
605 out.append(" default: gt = " + dflt).append("; continue;\n}");
609 case bc_invokeinterface: {
610 i = invokeVirtualMethod(byteCodes, i) + 2;
613 case bc_invokevirtual:
614 i = invokeVirtualMethod(byteCodes, i);
616 case bc_invokespecial:
617 i = invokeStaticMethod(byteCodes, i, false);
619 case bc_invokestatic:
620 i = invokeStaticMethod(byteCodes, i, true);
623 int indx = readIntArg(byteCodes, i);
624 CPClassInfo ci = jc.getConstantPool().getClass(indx);
625 out.append("stack.push(");
626 out.append("new ").append(ci.getClassName().getInternalName().replace('/','_'));
628 addReference(ci.getClassName().getInternalName());
633 int type = byteCodes[i++];
634 out.append("stack.push(new Array(stack.pop()));");
638 i += 2; // skip type of array
639 out.append("stack.push(new Array(stack.pop()));");
643 out.append("stack.push(stack.pop().length);");
653 out.append("{ var value = stack.pop(); var indx = stack.pop(); stack.pop()[indx] = value; }");
664 out.append("{ var indx = stack.pop(); stack.push(stack.pop()[indx]); }");
668 out.append("stack.pop();");
670 out.append("stack.pop();");
673 out.append("stack.push(stack[stack.length - 1]);");
676 out.append("stack.push(" + byteCodes[++i] + ");");
679 out.append("stack.push(" + readIntArg(byteCodes, i) + ");");
683 int indx = readIntArg(byteCodes, i);
684 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
685 out.append("stack.push(stack.pop().").append(fi.getFieldName()).append(");");
690 int indx = readIntArg(byteCodes, i);
691 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
692 final String in = fi.getClassName().getInternalName();
693 out.append("stack.push(").append(in.replace('/', '_'));
694 out.append('_').append(fi.getFieldName()).append(");");
700 int indx = readIntArg(byteCodes, i);
701 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
702 final String in = fi.getClassName().getInternalName();
703 out.append(in.replace('/', '_'));
704 out.append('_').append(fi.getFieldName()).append(" = stack.pop();");
710 int indx = readIntArg(byteCodes, i);
711 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
712 out.append("{ var v = stack.pop(); stack.pop().")
713 .append(fi.getFieldName()).append(" = v; }");
718 int indx = readIntArg(byteCodes, i);
719 CPClassInfo ci = jc.getConstantPool().getClass(indx);
720 final String type = ci.getClassName().getType();
721 if (!type.startsWith("[")) {
722 // no way to check arrays right now
723 out.append("if(stack[stack.length - 1].$instOf_")
724 .append(type.replace('/', '_'))
725 .append(" != 1) throw {};"); // XXX proper exception
730 case bc_instanceof: {
731 int indx = readIntArg(byteCodes, i);
732 CPClassInfo ci = jc.getConstantPool().getClass(indx);
733 out.append("stack.push(stack.pop().$instOf_")
734 .append(ci.getClassName().getInternalName().replace('/', '_'))
735 .append(" ? 1 : 0);");
740 out.append("{ var t = stack.pop(); stack = new Array(1); stack[0] = t; throw t; }");
744 out.append("throw 'unknown bytecode " + c + "';");
749 for (int j = prev; j <= i; j++) {
751 final int cc = (byteCodes[j] + 256) % 256;
752 out.append(Integer.toString(cc));
759 private int generateIf(byte[] byteCodes, int i, final String test) throws IOException {
760 int indx = i + readIntArg(byteCodes, i);
761 out.append("if (stack.pop() ").append(test).append(" stack.pop()) { gt = " + indx);
762 out.append("; continue; }");
766 private int readIntArg(byte[] byteCodes, int offsetInstruction) {
767 final int indxHi = byteCodes[offsetInstruction + 1] << 8;
768 final int indxLo = byteCodes[offsetInstruction + 2];
769 return (indxHi & 0xffffff00) | (indxLo & 0xff);
771 private int readInt4(byte[] byteCodes, int offsetInstruction) {
772 final int d = byteCodes[offsetInstruction + 0] << 24;
773 final int c = byteCodes[offsetInstruction + 1] << 16;
774 final int b = byteCodes[offsetInstruction + 2] << 8;
775 final int a = byteCodes[offsetInstruction + 3];
776 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
779 private static int countArgs(String descriptor, boolean[] hasReturnType, StringBuilder sig) {
782 Boolean count = null;
783 boolean array = false;
784 int firstPos = sig.length();
785 while (i < descriptor.length()) {
786 char ch = descriptor.charAt(i++);
812 hasReturnType[0] = true;
813 sig.insert(firstPos, ch);
815 sig.insert(firstPos, 'A');
822 hasReturnType[0] = false;
823 sig.insert(firstPos, 'V');
826 int next = descriptor.indexOf(';', i);
833 sig.append(descriptor.substring(i, next).replace('/', '_'));
835 sig.insert(firstPos, descriptor.substring(i, next).replace('/', '_'));
836 sig.insert(firstPos, ch);
838 sig.insert(firstPos, 'A');
840 hasReturnType[0] = true;
848 break; // invalid character
854 private void generateStaticField(Variable v) throws IOException {
856 .append(jc.getName().getInternalName().replace('/', '_'))
857 .append('_').append(v.getName()).append(" = 0;");
860 private String findMethodName(Method m) {
861 StringBuilder name = new StringBuilder();
862 String descr = m.getDescriptor();
863 if ("<init>".equals(m.getName())) { // NOI18N
864 name.append("cons"); // NOI18N
865 } else if ("<clinit>".equals(m.getName())) { // NOI18N
866 name.append("class"); // NOI18N
868 name.append(m.getName());
871 boolean hasReturn[] = { false };
872 countArgs(findDescriptor(m.getDescriptor()), hasReturn, name);
873 return name.toString();
876 private String findMethodName(CPMethodInfo mi, int[] cnt, boolean[] hasReturn) {
877 StringBuilder name = new StringBuilder();
878 String descr = mi.getDescriptor();
879 if ("<init>".equals(mi.getName())) { // NOI18N
880 name.append("cons"); // NOI18N
882 name.append(mi.getName());
884 cnt[0] = countArgs(findDescriptor(mi.getDescriptor()), hasReturn, name);
885 return name.toString();
888 private int invokeStaticMethod(byte[] byteCodes, int i, boolean isStatic)
890 int methodIndex = readIntArg(byteCodes, i);
891 CPMethodInfo mi = (CPMethodInfo) jc.getConstantPool().get(methodIndex);
892 boolean[] hasReturn = { false };
894 String mn = findMethodName(mi, cnt, hasReturn);
896 for (int j = cnt[0] - 1; j >= 0; j--) {
897 out.append("var v" + j).append(" = stack.pop(); ");
901 out.append("stack.push(");
903 final String in = mi.getClassName().getInternalName();
904 out.append(in.replace('/', '_'));
906 out.append(".prototype.");
914 out.append("stack.pop()");
917 for (int j = 0; j < cnt[0]; j++) {
931 private int invokeVirtualMethod(byte[] byteCodes, int i)
933 int methodIndex = readIntArg(byteCodes, i);
934 CPMethodInfo mi = (CPMethodInfo) jc.getConstantPool().get(methodIndex);
935 boolean[] hasReturn = { false };
937 String mn = findMethodName(mi, cnt, hasReturn);
939 for (int j = cnt[0] - 1; j >= 0; j--) {
940 out.append("var v" + j).append(" = stack.pop(); ");
942 out.append("var self = stack.pop(); ");
944 out.append("stack.push(");
950 for (int j = 0; j < cnt[0]; j++) {
963 private void addReference(String cn) throws IOException {
964 out.append(" /* needs ").append(cn).append(" */");
965 if (references != null) {
970 private void outType(String d, StringBuilder out) {
972 while (d.charAt(0) == '[') {
976 if (d.charAt(0) == 'L') {
977 assert d.charAt(d.length() - 1) == ';';
978 out.append(d.replace('/', '_').substring(0, d.length() - 1));
984 private String encodeConstant(CPEntry entry) {
986 if (entry instanceof CPClassInfo) {
987 v = "new java_lang_Class";
988 } else if (entry instanceof CPStringInfo) {
989 v = "\"" + entry.getValue().toString().replace("\"", "\\\"") + "\"";
991 v = entry.getValue().toString();
996 private String findDescriptor(String d) {
997 return d.replace('[', 'A');
1000 private boolean javaScriptBody(Method m, boolean isStatic) throws IOException {
1001 final ClassName extraAnn = ClassName.getClassName(JavaScriptBody.class.getName().replace('.', '/'));
1002 Annotation a = m.getAnnotation(extraAnn);
1004 final ElementValue annVal = a.getComponent("body").getValue();
1005 String body = ((PrimitiveElementValue) annVal).getValue().getValue().toString();
1007 final ArrayElementValue arrVal = (ArrayElementValue) a.getComponent("args").getValue();
1008 final int len = arrVal.getValues().length;
1009 String[] names = new String[len];
1010 for (int i = 0; i < len; i++) {
1011 names[i] = ((PrimitiveElementValue) arrVal.getValues()[i]).getValue().getValue().toString();
1013 out.append("\nfunction ").append(
1014 jc.getName().getInternalName().replace('/', '_')).append('_').append(findMethodName(m));
1019 out.append(names[0]);
1026 List<Parameter> args = m.getParameters();
1027 for (int i = 0; i < args.size(); i++) {
1029 out.append(names[index]);
1030 final String desc = findDescriptor(args.get(i).getDescriptor());
1034 out.append(") {").append("\n");
1036 out.append("\n}\n");