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;");
121 out.append("\n}\n\nfunction ").append(className).append("_proto() {");
122 out.append("\n if (").append(className).
123 append(".prototype.$instOf_").append(className).append(") {");
124 out.append("\n return ").append(className).append(".prototype;");
126 ClassName sc = jc.getSuperClass();
128 out.append("\n ").append(sc.getInternalName().replace('/', '_')).append("_proto();");
129 out.append("\n ").append(className)
130 .append(".prototype = new ").append(sc.getInternalName().replace('/', '_')).append(';');
132 for (Method m : jc.getMethods()) {
133 if (!m.getName().contains("<init>") && !m.getName().contains("<cinit>")) {
134 compiler.generateMethodReference("\n " + className + ".prototype.", m);
137 out.append("\n " + className + ".prototype.$instOf_").append(className).append(" = true;");
138 for (ClassName superInterface : jc.getInterfaces()) {
139 out.append("\n " + className + ".prototype.$instOf_").append(superInterface.getInternalName().replace('/', '_')).append(" = true;");
141 out.append("\n return ").append(className).append(".prototype;");
143 out.append("\n").append(className).append("_proto();");
144 StringBuilder sb = new StringBuilder();
145 for (String init : toInitilize) {
146 sb.append("\n").append(init).append("();");
148 return sb.toString();
150 private void generateStaticMethod(Method m, List<String> toInitilize) throws IOException {
151 if (javaScriptBody(m, true)) {
154 final String mn = findMethodName(m);
155 out.append("\nfunction ").append(
156 jc.getName().getInternalName().replace('/', '_')
157 ).append('_').append(mn);
158 if (mn.equals("classV")) {
159 toInitilize.add(jc.getName().getInternalName().replace('/', '_') + '_' + mn);
163 List<Parameter> args = m.getParameters();
164 for (int index = 0, i = 0; i < args.size(); i++) {
166 out.append("arg").append(String.valueOf(index));
168 final String desc = findDescriptor(args.get(i).getDescriptor());
169 if ("D".equals(desc) || "J".equals(desc)) {
175 out.append(") {").append("\n");
176 final Code code = m.getCode();
178 int len = code.getMaxLocals();
179 for (int index = args.size(), i = args.size(); i < len; i++) {
181 out.append("arg").append(String.valueOf(i)).append(";\n");
183 out.append(" var stack = new Array();\n");
184 produceCode(code.getByteCodes());
186 out.append(" /* no code found for ").append(m.getTypeSignature()).append(" */\n");
191 private void generateMethodReference(String prefix, Method m) throws IOException {
192 final String name = findMethodName(m);
193 out.append(prefix).append(name).append(" = ")
194 .append(jc.getName().getInternalName().replace('/', '_'))
195 .append('_').append(name).append(";");
198 private void generateInstanceMethod(Method m) throws IOException {
199 if (javaScriptBody(m, false)) {
202 out.append("\nfunction ").append(
203 jc.getName().getInternalName().replace('/', '_')
204 ).append('_').append(findMethodName(m));
207 List<Parameter> args = m.getParameters();
208 for (int index = 1, i = 0; i < args.size(); i++) {
210 out.append("arg").append(String.valueOf(index));
211 final String desc = findDescriptor(args.get(i).getDescriptor());
212 if ("D".equals(desc) || "J".equals(desc)) {
218 out.append(") {").append("\n");
219 final Code code = m.getCode();
221 int len = code.getMaxLocals();
222 for (int index = args.size(), i = args.size(); i < len; i++) {
224 out.append("arg").append(String.valueOf(i + 1)).append(";\n");
226 out.append(";\n var stack = new Array();\n");
227 produceCode(code.getByteCodes());
229 out.append(" /* no code found for ").append(m.getTypeSignature()).append(" */\n");
234 private void produceCode(byte[] byteCodes) throws IOException {
235 out.append("\n var gt = 0;\n for(;;) switch(gt) {\n");
236 for (int i = 0; i < byteCodes.length; i++) {
238 out.append(" case " + i).append(": ");
239 final int c = (byteCodes[i] + 256) % 256;
246 out.append("stack.push(arg0);");
253 out.append("stack.push(arg1);");
260 out.append("stack.push(arg2);");
267 out.append("stack.push(arg3);");
274 final int indx = (byteCodes[++i] + 256) % 256;
275 out.append("stack.push(arg").append(indx + ");");
283 final int indx = (byteCodes[++i] + 256) % 256;
284 out.append("arg" + indx).append(" = stack.pop()");
292 out.append("arg0 = stack.pop();");
299 out.append("arg1 = stack.pop();");
306 out.append("arg2 = stack.pop();");
313 out.append("arg3 = stack.pop();");
319 out.append("stack.push(stack.pop() + stack.pop());");
325 out.append("{ var tmp = stack.pop(); stack.push(stack.pop() - tmp); }");
331 out.append("stack.push(stack.pop() * stack.pop());");
335 out.append("{ var tmp = stack.pop(); stack.push(Math.floor(stack.pop() / tmp)); }");
339 out.append("{ var tmp = stack.pop(); stack.push(stack.pop() / tmp); }");
343 out.append("stack.push(stack.pop() & stack.pop());");
347 out.append("stack.push(stack.pop() | stack.pop());");
351 out.append("stack.push(stack.pop() ^ stack.pop());");
357 out.append("stack.push(- stack.pop());");
361 out.append("{ var v = stack.pop(); stack.push(stack.pop() << v); }");
365 out.append("{ var v = stack.pop(); stack.push(stack.pop() >> v); }");
369 out.append("{ var v = stack.pop(); stack.push(stack.pop() >>> v); }");
372 final int varIndx = (byteCodes[++i] + 256) % 256;
373 final int incrBy = byteCodes[++i];
375 out.append("arg" + varIndx).append("++;");
377 out.append("arg" + varIndx).append(" += " + incrBy).append(";");
382 out.append("return;");
389 out.append("return stack.pop();");
400 out.append("/* number conversion */");
406 out.append("stack.push(Math.floor(stack.pop()));");
411 out.append("/* number conversion */");
414 out.append("stack.push(null);");
417 out.append("stack.push(-1);");
423 out.append("stack.push(0);");
429 out.append("stack.push(1);");
433 out.append("stack.push(2);");
436 out.append("stack.push(3);");
439 out.append("stack.push(4);");
442 out.append("stack.push(5);");
445 int indx = byteCodes[++i];
446 CPEntry entry = jc.getConstantPool().get(indx);
447 String v = encodeConstant(entry);
448 out.append("stack.push(").append(v).append(");");
453 int indx = readIntArg(byteCodes, i);
454 CPEntry entry = jc.getConstantPool().get(indx);
456 String v = encodeConstant(entry);
457 out.append("stack.push(").append(v).append(");");
465 out.append("{ var delta = stack.pop() - stack.pop(); stack.push(delta < 0 ?-1 : (delta == 0 ? 0 : 1)); }");
469 i = generateIf(byteCodes, i, "===");
472 i = generateIf(byteCodes, i, "!=");
475 i = generateIf(byteCodes, i, "==");
479 int indx = i + readIntArg(byteCodes, i);
480 out.append("if (stack.pop() == 0) { gt = " + indx);
481 out.append("; continue; }");
486 int indx = i + readIntArg(byteCodes, i);
487 out.append("if (stack.pop() != 0) { gt = " + indx);
488 out.append("; continue; }");
493 int indx = i + readIntArg(byteCodes, i);
494 out.append("if (stack.pop() < 0) { gt = " + indx);
495 out.append("; continue; }");
500 int indx = i + readIntArg(byteCodes, i);
501 out.append("if (stack.pop() <= 0) { gt = " + indx);
502 out.append("; continue; }");
507 int indx = i + readIntArg(byteCodes, i);
508 out.append("if (stack.pop() > 0) { gt = " + indx);
509 out.append("; continue; }");
514 int indx = i + readIntArg(byteCodes, i);
515 out.append("if (stack.pop() >= 0) { gt = " + indx);
516 out.append("; continue; }");
521 int indx = i + readIntArg(byteCodes, i);
522 out.append("if (stack.pop()) { gt = " + indx);
523 out.append("; continue; }");
528 int indx = i + readIntArg(byteCodes, i);
529 out.append("if (!stack.pop()) { gt = " + indx);
530 out.append("; continue; }");
535 i = generateIf(byteCodes, i, "!=");
538 i = generateIf(byteCodes, i, ">");
541 i = generateIf(byteCodes, i, ">=");
544 i = generateIf(byteCodes, i, "<");
547 i = generateIf(byteCodes, i, "<=");
550 int indx = i + readIntArg(byteCodes, i);
551 out.append("gt = " + indx).append("; continue;");
555 case bc_invokeinterface: {
556 i = invokeVirtualMethod(byteCodes, i) + 2;
559 case bc_invokevirtual:
560 i = invokeVirtualMethod(byteCodes, i);
562 case bc_invokespecial:
563 i = invokeStaticMethod(byteCodes, i, false);
565 case bc_invokestatic:
566 i = invokeStaticMethod(byteCodes, i, true);
569 int indx = readIntArg(byteCodes, i);
570 CPClassInfo ci = jc.getConstantPool().getClass(indx);
571 out.append("stack.push(");
572 out.append("new ").append(ci.getClassName().getInternalName().replace('/','_'));
574 addReference(ci.getClassName().getInternalName());
579 int type = byteCodes[i++];
580 out.append("stack.push(new Array(stack.pop()));");
584 i += 2; // skip type of array
585 out.append("stack.push(new Array(stack.pop()));");
589 out.append("stack.push(stack.pop().length);");
599 out.append("{ var value = stack.pop(); var indx = stack.pop(); stack.pop()[indx] = value; }");
610 out.append("{ var indx = stack.pop(); stack.push(stack.pop()[indx]); }");
614 out.append("stack.pop();");
616 out.append("stack.pop();");
619 out.append("stack.push(stack[stack.length - 1]);");
622 out.append("stack.push(" + byteCodes[++i] + ");");
625 out.append("stack.push(" + readIntArg(byteCodes, i) + ");");
629 int indx = readIntArg(byteCodes, i);
630 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
631 out.append("stack.push(stack.pop().").append(fi.getFieldName()).append(");");
636 int indx = readIntArg(byteCodes, i);
637 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
638 final String in = fi.getClassName().getInternalName();
639 out.append("stack.push(").append(in.replace('/', '_'));
640 out.append('_').append(fi.getFieldName()).append(");");
646 int indx = readIntArg(byteCodes, i);
647 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
648 final String in = fi.getClassName().getInternalName();
649 out.append(in.replace('/', '_'));
650 out.append('_').append(fi.getFieldName()).append(" = stack.pop();");
656 int indx = readIntArg(byteCodes, i);
657 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
658 out.append("{ var v = stack.pop(); stack.pop().")
659 .append(fi.getFieldName()).append(" = v; }");
664 int indx = readIntArg(byteCodes, i);
665 CPClassInfo ci = jc.getConstantPool().getClass(indx);
666 final String type = ci.getClassName().getType();
667 if (!type.startsWith("[")) {
668 // no way to check arrays right now
669 out.append("if(stack[stack.length - 1].$instOf_")
670 .append(type.replace('/', '_'))
671 .append(" != 1) throw {};"); // XXX proper exception
676 case bc_instanceof: {
677 int indx = readIntArg(byteCodes, i);
678 CPClassInfo ci = jc.getConstantPool().getClass(indx);
679 out.append("stack.push(stack.pop().$instOf_")
680 .append(ci.getClassName().getInternalName().replace('/', '_'))
681 .append(" ? 1 : 0);");
686 out.append("{ var t = stack.pop(); stack = new Array(1); stack[0] = t; throw t; }");
690 out.append("throw 'unknown bytecode " + c + "';");
695 for (int j = prev; j <= i; j++) {
697 final int cc = (byteCodes[j] + 256) % 256;
698 out.append(Integer.toString(cc));
705 private int generateIf(byte[] byteCodes, int i, final String test) throws IOException {
706 int indx = i + readIntArg(byteCodes, i);
707 out.append("if (stack.pop() ").append(test).append(" stack.pop()) { gt = " + indx);
708 out.append("; continue; }");
712 private int readIntArg(byte[] byteCodes, int offsetInstruction) {
713 final int indxHi = byteCodes[offsetInstruction + 1] << 8;
714 final int indxLo = byteCodes[offsetInstruction + 2];
715 return (indxHi & 0xffffff00) | (indxLo & 0xff);
718 private static int countArgs(String descriptor, boolean[] hasReturnType, StringBuilder sig) {
721 Boolean count = null;
722 boolean array = false;
723 int firstPos = sig.length();
724 while (i < descriptor.length()) {
725 char ch = descriptor.charAt(i++);
751 hasReturnType[0] = true;
752 sig.insert(firstPos, ch);
754 sig.insert(firstPos, 'A');
761 hasReturnType[0] = false;
762 sig.insert(firstPos, 'V');
765 int next = descriptor.indexOf(';', i);
772 sig.append(descriptor.substring(i, next).replace('/', '_'));
774 sig.insert(firstPos, descriptor.substring(i, next).replace('/', '_'));
775 sig.insert(firstPos, ch);
777 sig.insert(firstPos, 'A');
779 hasReturnType[0] = true;
787 break; // invalid character
793 private void generateStaticField(Variable v) throws IOException {
795 .append(jc.getName().getInternalName().replace('/', '_'))
796 .append('_').append(v.getName()).append(" = 0;");
799 private String findMethodName(Method m) {
800 StringBuilder name = new StringBuilder();
801 String descr = m.getDescriptor();
802 if ("<init>".equals(m.getName())) { // NOI18N
803 name.append("cons"); // NOI18N
804 } else if ("<clinit>".equals(m.getName())) { // NOI18N
805 name.append("class"); // NOI18N
807 name.append(m.getName());
810 boolean hasReturn[] = { false };
811 countArgs(findDescriptor(m.getDescriptor()), hasReturn, name);
812 return name.toString();
815 private String findMethodName(CPMethodInfo mi, int[] cnt, boolean[] hasReturn) {
816 StringBuilder name = new StringBuilder();
817 String descr = mi.getDescriptor();
818 if ("<init>".equals(mi.getName())) { // NOI18N
819 name.append("cons"); // NOI18N
821 name.append(mi.getName());
823 cnt[0] = countArgs(findDescriptor(mi.getDescriptor()), hasReturn, name);
824 return name.toString();
827 private int invokeStaticMethod(byte[] byteCodes, int i, boolean isStatic)
829 int methodIndex = readIntArg(byteCodes, i);
830 CPMethodInfo mi = (CPMethodInfo) jc.getConstantPool().get(methodIndex);
831 boolean[] hasReturn = { false };
833 String mn = findMethodName(mi, cnt, hasReturn);
835 for (int j = cnt[0] - 1; j >= 0; j--) {
836 out.append("var v" + j).append(" = stack.pop(); ");
840 out.append("stack.push(");
842 final String in = mi.getClassName().getInternalName();
843 out.append(in.replace('/', '_'));
845 out.append(".prototype.");
853 out.append("stack.pop()");
856 for (int j = 0; j < cnt[0]; j++) {
870 private int invokeVirtualMethod(byte[] byteCodes, int i)
872 int methodIndex = readIntArg(byteCodes, i);
873 CPMethodInfo mi = (CPMethodInfo) jc.getConstantPool().get(methodIndex);
874 boolean[] hasReturn = { false };
876 String mn = findMethodName(mi, cnt, hasReturn);
878 for (int j = cnt[0] - 1; j >= 0; j--) {
879 out.append("var v" + j).append(" = stack.pop(); ");
881 out.append("var self = stack.pop(); ");
883 out.append("stack.push(");
889 for (int j = 0; j < cnt[0]; j++) {
902 private void addReference(String cn) throws IOException {
903 out.append(" /* needs ").append(cn).append(" */");
904 if (references != null) {
909 private void outType(String d, StringBuilder out) {
911 while (d.charAt(0) == '[') {
915 if (d.charAt(0) == 'L') {
916 assert d.charAt(d.length() - 1) == ';';
917 out.append(d.replace('/', '_').substring(0, d.length() - 1));
923 private String encodeConstant(CPEntry entry) {
925 if (entry instanceof CPClassInfo) {
926 v = "new java_lang_Class";
927 } else if (entry instanceof CPStringInfo) {
928 v = "\"" + entry.getValue().toString().replace("\"", "\\\"") + "\"";
930 v = entry.getValue().toString();
935 private String findDescriptor(String d) {
936 return d.replace('[', 'A');
939 private boolean javaScriptBody(Method m, boolean isStatic) throws IOException {
940 final ClassName extraAnn = ClassName.getClassName(JavaScriptBody.class.getName().replace('.', '/'));
941 Annotation a = m.getAnnotation(extraAnn);
943 final ElementValue annVal = a.getComponent("body").getValue();
944 String body = ((PrimitiveElementValue) annVal).getValue().getValue().toString();
946 final ArrayElementValue arrVal = (ArrayElementValue) a.getComponent("args").getValue();
947 final int len = arrVal.getValues().length;
948 String[] names = new String[len];
949 for (int i = 0; i < len; i++) {
950 names[i] = ((PrimitiveElementValue) arrVal.getValues()[i]).getValue().getValue().toString();
952 out.append("\nfunction ").append(
953 jc.getName().getInternalName().replace('/', '_')).append('_').append(findMethodName(m));
958 out.append(names[0]);
965 List<Parameter> args = m.getParameters();
966 for (int i = 0; i < args.size(); i++) {
968 out.append(names[index]);
969 final String desc = findDescriptor(args.get(i).getDescriptor());
973 out.append(") {").append("\n");