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_invokeinterface: {
573 i = invokeVirtualMethod(byteCodes, i) + 2;
576 case bc_invokevirtual:
577 i = invokeVirtualMethod(byteCodes, i);
579 case bc_invokespecial:
580 i = invokeStaticMethod(byteCodes, i, false);
582 case bc_invokestatic:
583 i = invokeStaticMethod(byteCodes, i, true);
586 int indx = readIntArg(byteCodes, i);
587 CPClassInfo ci = jc.getConstantPool().getClass(indx);
588 out.append("stack.push(");
589 out.append("new ").append(ci.getClassName().getInternalName().replace('/','_'));
591 addReference(ci.getClassName().getInternalName());
596 int type = byteCodes[i++];
597 out.append("stack.push(new Array(stack.pop()));");
601 i += 2; // skip type of array
602 out.append("stack.push(new Array(stack.pop()));");
606 out.append("stack.push(stack.pop().length);");
616 out.append("{ var value = stack.pop(); var indx = stack.pop(); stack.pop()[indx] = value; }");
627 out.append("{ var indx = stack.pop(); stack.push(stack.pop()[indx]); }");
631 out.append("stack.pop();");
633 out.append("stack.pop();");
636 out.append("stack.push(stack[stack.length - 1]);");
639 out.append("stack.push(" + byteCodes[++i] + ");");
642 out.append("stack.push(" + readIntArg(byteCodes, i) + ");");
646 int indx = readIntArg(byteCodes, i);
647 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
648 out.append("stack.push(stack.pop().").append(fi.getFieldName()).append(");");
653 int indx = readIntArg(byteCodes, i);
654 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
655 final String in = fi.getClassName().getInternalName();
656 out.append("stack.push(").append(in.replace('/', '_'));
657 out.append('_').append(fi.getFieldName()).append(");");
663 int indx = readIntArg(byteCodes, i);
664 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
665 final String in = fi.getClassName().getInternalName();
666 out.append(in.replace('/', '_'));
667 out.append('_').append(fi.getFieldName()).append(" = stack.pop();");
673 int indx = readIntArg(byteCodes, i);
674 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
675 out.append("{ var v = stack.pop(); stack.pop().")
676 .append(fi.getFieldName()).append(" = v; }");
681 int indx = readIntArg(byteCodes, i);
682 CPClassInfo ci = jc.getConstantPool().getClass(indx);
683 final String type = ci.getClassName().getType();
684 if (!type.startsWith("[")) {
685 // no way to check arrays right now
686 out.append("if(stack[stack.length - 1].$instOf_")
687 .append(type.replace('/', '_'))
688 .append(" != 1) throw {};"); // XXX proper exception
693 case bc_instanceof: {
694 int indx = readIntArg(byteCodes, i);
695 CPClassInfo ci = jc.getConstantPool().getClass(indx);
696 out.append("stack.push(stack.pop().$instOf_")
697 .append(ci.getClassName().getInternalName().replace('/', '_'))
698 .append(" ? 1 : 0);");
703 out.append("{ var t = stack.pop(); stack = new Array(1); stack[0] = t; throw t; }");
707 out.append("throw 'unknown bytecode " + c + "';");
712 for (int j = prev; j <= i; j++) {
714 final int cc = (byteCodes[j] + 256) % 256;
715 out.append(Integer.toString(cc));
722 private int generateIf(byte[] byteCodes, int i, final String test) throws IOException {
723 int indx = i + readIntArg(byteCodes, i);
724 out.append("if (stack.pop() ").append(test).append(" stack.pop()) { gt = " + indx);
725 out.append("; continue; }");
729 private int readIntArg(byte[] byteCodes, int offsetInstruction) {
730 final int indxHi = byteCodes[offsetInstruction + 1] << 8;
731 final int indxLo = byteCodes[offsetInstruction + 2];
732 return (indxHi & 0xffffff00) | (indxLo & 0xff);
735 private static int countArgs(String descriptor, boolean[] hasReturnType, StringBuilder sig) {
738 Boolean count = null;
739 boolean array = false;
740 int firstPos = sig.length();
741 while (i < descriptor.length()) {
742 char ch = descriptor.charAt(i++);
768 hasReturnType[0] = true;
769 sig.insert(firstPos, ch);
771 sig.insert(firstPos, 'A');
778 hasReturnType[0] = false;
779 sig.insert(firstPos, 'V');
782 int next = descriptor.indexOf(';', i);
789 sig.append(descriptor.substring(i, next).replace('/', '_'));
791 sig.insert(firstPos, descriptor.substring(i, next).replace('/', '_'));
792 sig.insert(firstPos, ch);
794 sig.insert(firstPos, 'A');
796 hasReturnType[0] = true;
804 break; // invalid character
810 private void generateStaticField(Variable v) throws IOException {
812 .append(jc.getName().getInternalName().replace('/', '_'))
813 .append('_').append(v.getName()).append(" = 0;");
816 private String findMethodName(Method m) {
817 StringBuilder name = new StringBuilder();
818 String descr = m.getDescriptor();
819 if ("<init>".equals(m.getName())) { // NOI18N
820 name.append("cons"); // NOI18N
821 } else if ("<clinit>".equals(m.getName())) { // NOI18N
822 name.append("class"); // NOI18N
824 name.append(m.getName());
827 boolean hasReturn[] = { false };
828 countArgs(findDescriptor(m.getDescriptor()), hasReturn, name);
829 return name.toString();
832 private String findMethodName(CPMethodInfo mi, int[] cnt, boolean[] hasReturn) {
833 StringBuilder name = new StringBuilder();
834 String descr = mi.getDescriptor();
835 if ("<init>".equals(mi.getName())) { // NOI18N
836 name.append("cons"); // NOI18N
838 name.append(mi.getName());
840 cnt[0] = countArgs(findDescriptor(mi.getDescriptor()), hasReturn, name);
841 return name.toString();
844 private int invokeStaticMethod(byte[] byteCodes, int i, boolean isStatic)
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(); ");
857 out.append("stack.push(");
859 final String in = mi.getClassName().getInternalName();
860 out.append(in.replace('/', '_'));
862 out.append(".prototype.");
870 out.append("stack.pop()");
873 for (int j = 0; j < cnt[0]; j++) {
887 private int invokeVirtualMethod(byte[] byteCodes, int i)
889 int methodIndex = readIntArg(byteCodes, i);
890 CPMethodInfo mi = (CPMethodInfo) jc.getConstantPool().get(methodIndex);
891 boolean[] hasReturn = { false };
893 String mn = findMethodName(mi, cnt, hasReturn);
895 for (int j = cnt[0] - 1; j >= 0; j--) {
896 out.append("var v" + j).append(" = stack.pop(); ");
898 out.append("var self = stack.pop(); ");
900 out.append("stack.push(");
906 for (int j = 0; j < cnt[0]; j++) {
919 private void addReference(String cn) throws IOException {
920 out.append(" /* needs ").append(cn).append(" */");
921 if (references != null) {
926 private void outType(String d, StringBuilder out) {
928 while (d.charAt(0) == '[') {
932 if (d.charAt(0) == 'L') {
933 assert d.charAt(d.length() - 1) == ';';
934 out.append(d.replace('/', '_').substring(0, d.length() - 1));
940 private String encodeConstant(CPEntry entry) {
942 if (entry instanceof CPClassInfo) {
943 v = "new java_lang_Class";
944 } else if (entry instanceof CPStringInfo) {
945 v = "\"" + entry.getValue().toString().replace("\"", "\\\"") + "\"";
947 v = entry.getValue().toString();
952 private String findDescriptor(String d) {
953 return d.replace('[', 'A');
956 private boolean javaScriptBody(Method m, boolean isStatic) throws IOException {
957 final ClassName extraAnn = ClassName.getClassName(JavaScriptBody.class.getName().replace('.', '/'));
958 Annotation a = m.getAnnotation(extraAnn);
960 final ElementValue annVal = a.getComponent("body").getValue();
961 String body = ((PrimitiveElementValue) annVal).getValue().getValue().toString();
963 final ArrayElementValue arrVal = (ArrayElementValue) a.getComponent("args").getValue();
964 final int len = arrVal.getValues().length;
965 String[] names = new String[len];
966 for (int i = 0; i < len; i++) {
967 names[i] = ((PrimitiveElementValue) arrVal.getValues()[i]).getValue().getValue().toString();
969 out.append("\nfunction ").append(
970 jc.getName().getInternalName().replace('/', '_')).append('_').append(findMethodName(m));
975 out.append(names[0]);
982 List<Parameter> args = m.getParameters();
983 for (int i = 0; i < args.size(); i++) {
985 out.append(names[index]);
986 final String desc = findDescriptor(args.get(i).getDescriptor());
990 out.append(") {").append("\n");