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.isStatic() && !m.isPrivate() && !m.getName().contains("<init>")) {
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] + 256) % 256;
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, "==");
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() >= 0) { 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 int indx = i + readIntArg(byteCodes, i);
523 out.append("if (!stack.pop()) { gt = " + indx);
524 out.append("; continue; }");
529 i = generateIf(byteCodes, i, "!=");
532 i = generateIf(byteCodes, i, ">");
535 i = generateIf(byteCodes, i, ">=");
538 i = generateIf(byteCodes, i, "<");
541 i = generateIf(byteCodes, i, "<=");
544 int indx = i + readIntArg(byteCodes, i);
545 out.append("gt = " + indx).append("; continue;");
549 case bc_invokeinterface: {
550 i = invokeVirtualMethod(byteCodes, i) + 2;
553 case bc_invokevirtual:
554 i = invokeVirtualMethod(byteCodes, i);
556 case bc_invokespecial:
557 i = invokeStaticMethod(byteCodes, i, false);
559 case bc_invokestatic:
560 i = invokeStaticMethod(byteCodes, i, true);
563 int indx = readIntArg(byteCodes, i);
564 CPClassInfo ci = jc.getConstantPool().getClass(indx);
565 out.append("stack.push(");
566 out.append("new ").append(ci.getClassName().getInternalName().replace('/','_'));
568 addReference(ci.getClassName().getInternalName());
573 int type = byteCodes[i++];
574 out.append("stack.push(new Array(stack.pop()));");
578 i += 2; // skip type of array
579 out.append("stack.push(new Array(stack.pop()));");
583 out.append("stack.push(stack.pop().length);");
593 out.append("{ var value = stack.pop(); var indx = stack.pop(); stack.pop()[indx] = value; }");
604 out.append("{ var indx = stack.pop(); stack.push(stack.pop()[indx]); }");
608 out.append("stack.pop();");
610 out.append("stack.pop();");
613 out.append("stack.push(stack[stack.length - 1]);");
616 out.append("stack.push(" + byteCodes[++i] + ");");
619 out.append("stack.push(" + readIntArg(byteCodes, i) + ");");
623 int indx = readIntArg(byteCodes, i);
624 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
625 out.append("stack.push(stack.pop().").append(fi.getFieldName()).append(");");
630 int indx = readIntArg(byteCodes, i);
631 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
632 final String in = fi.getClassName().getInternalName();
633 out.append("stack.push(").append(in.replace('/', '_'));
634 out.append('_').append(fi.getFieldName()).append(");");
640 int indx = readIntArg(byteCodes, i);
641 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
642 final String in = fi.getClassName().getInternalName();
643 out.append(in.replace('/', '_'));
644 out.append('_').append(fi.getFieldName()).append(" = stack.pop();");
650 int indx = readIntArg(byteCodes, i);
651 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
652 out.append("{ var v = stack.pop(); stack.pop().")
653 .append(fi.getFieldName()).append(" = v; }");
658 int indx = readIntArg(byteCodes, i);
659 CPClassInfo ci = jc.getConstantPool().getClass(indx);
660 final String type = ci.getClassName().getType();
661 if (!type.startsWith("[")) {
662 // no way to check arrays right now
663 out.append("if(stack[stack.length - 1].$instOf_")
664 .append(type.replace('/', '_'))
665 .append(" != 1) throw {};"); // XXX proper exception
670 case bc_instanceof: {
671 int indx = readIntArg(byteCodes, i);
672 CPClassInfo ci = jc.getConstantPool().getClass(indx);
673 out.append("stack.push(stack.pop().$instOf_")
674 .append(ci.getClassName().getInternalName().replace('/', '_'))
675 .append(" ? 1 : 0);");
682 for (int j = prev; j <= i; j++) {
684 final int cc = (byteCodes[j] + 256) % 256;
685 out.append(Integer.toString(cc));
692 private int generateIf(byte[] byteCodes, int i, final String test) throws IOException {
693 int indx = i + readIntArg(byteCodes, i);
694 out.append("if (stack.pop() ").append(test).append(" stack.pop()) { gt = " + indx);
695 out.append("; continue; }");
699 private int readIntArg(byte[] byteCodes, int offsetInstruction) {
700 final int indxHi = byteCodes[offsetInstruction + 1] << 8;
701 final int indxLo = byteCodes[offsetInstruction + 2];
702 return (indxHi & 0xffffff00) | (indxLo & 0xff);
705 private static int countArgs(String descriptor, boolean[] hasReturnType, StringBuilder sig) {
708 Boolean count = null;
709 boolean array = false;
710 int firstPos = sig.length();
711 while (i < descriptor.length()) {
712 char ch = descriptor.charAt(i++);
738 hasReturnType[0] = true;
739 sig.insert(firstPos, ch);
741 sig.insert(firstPos, 'A');
748 hasReturnType[0] = false;
749 sig.insert(firstPos, 'V');
752 int next = descriptor.indexOf(';', i);
759 sig.append(descriptor.substring(i, next).replace('/', '_'));
761 sig.insert(firstPos, descriptor.substring(i, next).replace('/', '_'));
762 sig.insert(firstPos, ch);
764 sig.insert(firstPos, 'A');
766 hasReturnType[0] = true;
774 break; // invalid character
780 private void generateStaticField(Variable v) throws IOException {
782 .append(jc.getName().getInternalName().replace('/', '_'))
783 .append('_').append(v.getName()).append(" = 0;");
786 private String findMethodName(Method m) {
787 StringBuilder name = new StringBuilder();
788 String descr = m.getDescriptor();
789 if ("<init>".equals(m.getName())) { // NOI18N
790 name.append("cons"); // NOI18N
791 } else if ("<clinit>".equals(m.getName())) { // NOI18N
792 name.append("class"); // NOI18N
794 name.append(m.getName());
797 boolean hasReturn[] = { false };
798 countArgs(findDescriptor(m.getDescriptor()), hasReturn, name);
799 return name.toString();
802 private String findMethodName(CPMethodInfo mi, int[] cnt, boolean[] hasReturn) {
803 StringBuilder name = new StringBuilder();
804 String descr = mi.getDescriptor();
805 if ("<init>".equals(mi.getName())) { // NOI18N
806 name.append("cons"); // NOI18N
808 name.append(mi.getName());
810 cnt[0] = countArgs(findDescriptor(mi.getDescriptor()), hasReturn, name);
811 return name.toString();
814 private int invokeStaticMethod(byte[] byteCodes, int i, boolean isStatic)
816 int methodIndex = readIntArg(byteCodes, i);
817 CPMethodInfo mi = (CPMethodInfo) jc.getConstantPool().get(methodIndex);
818 boolean[] hasReturn = { false };
820 String mn = findMethodName(mi, cnt, hasReturn);
822 for (int j = cnt[0] - 1; j >= 0; j--) {
823 out.append("var v" + j).append(" = stack.pop(); ");
827 out.append("stack.push(");
829 final String in = mi.getClassName().getInternalName();
830 out.append(in.replace('/', '_'));
836 out.append("stack.pop()");
839 for (int j = 0; j < cnt[0]; j++) {
853 private int invokeVirtualMethod(byte[] byteCodes, int i)
855 int methodIndex = readIntArg(byteCodes, i);
856 CPMethodInfo mi = (CPMethodInfo) jc.getConstantPool().get(methodIndex);
857 boolean[] hasReturn = { false };
859 String mn = findMethodName(mi, cnt, hasReturn);
861 for (int j = cnt[0] - 1; j >= 0; j--) {
862 out.append("var v" + j).append(" = stack.pop(); ");
864 out.append("var self = stack.pop(); ");
866 out.append("stack.push(");
872 for (int j = 0; j < cnt[0]; j++) {
885 private void addReference(String cn) {
886 if (references != null) {
891 private void outType(String d, StringBuilder out) {
893 while (d.charAt(0) == '[') {
897 if (d.charAt(0) == 'L') {
898 assert d.charAt(d.length() - 1) == ';';
899 out.append(d.replace('/', '_').substring(0, d.length() - 1));
905 private String encodeConstant(CPEntry entry) {
907 if (entry instanceof CPClassInfo) {
908 v = "new java_lang_Class";
909 } else if (entry instanceof CPStringInfo) {
910 v = "\"" + entry.getValue().toString().replace("\"", "\\\"") + "\"";
912 v = entry.getValue().toString();
917 private String findDescriptor(String d) {
918 return d.replace('[', 'A');
921 private boolean javaScriptBody(Method m, boolean isStatic) throws IOException {
922 final ClassName extraAnn = ClassName.getClassName(JavaScriptBody.class.getName().replace('.', '/'));
923 Annotation a = m.getAnnotation(extraAnn);
925 final ElementValue annVal = a.getComponent("body").getValue();
926 String body = ((PrimitiveElementValue) annVal).getValue().getValue().toString();
928 final ArrayElementValue arrVal = (ArrayElementValue) a.getComponent("args").getValue();
929 final int len = arrVal.getValues().length;
930 String[] names = new String[len];
931 for (int i = 0; i < len; i++) {
932 names[i] = ((PrimitiveElementValue) arrVal.getValues()[i]).getValue().getValue().toString();
934 out.append("\nfunction ").append(
935 jc.getName().getInternalName().replace('/', '_')).append('_').append(findMethodName(m));
940 out.append(names[0]);
947 List<Parameter> args = m.getParameters();
948 for (int i = 0; i < args.size(); i++) {
950 out.append(names[index]);
951 final String desc = findDescriptor(args.get(i).getDescriptor());
955 out.append(") {").append("\n");