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 static org.netbeans.modules.classfile.ByteCodes.*;
26 import org.netbeans.modules.classfile.CPClassInfo;
27 import org.netbeans.modules.classfile.CPEntry;
28 import org.netbeans.modules.classfile.CPFieldInfo;
29 import org.netbeans.modules.classfile.CPMethodInfo;
30 import org.netbeans.modules.classfile.CPStringInfo;
31 import org.netbeans.modules.classfile.ClassFile;
32 import org.netbeans.modules.classfile.ClassName;
33 import org.netbeans.modules.classfile.Code;
34 import org.netbeans.modules.classfile.Method;
35 import org.netbeans.modules.classfile.Parameter;
36 import org.netbeans.modules.classfile.Variable;
38 /** Translator of the code inside class files to JavaScript.
40 * @author Jaroslav Tulach <jtulach@netbeans.org>
42 public final class ByteCodeToJavaScript {
43 private final ClassFile jc;
44 private final Appendable out;
45 private final Collection<? super String> references;
47 private ByteCodeToJavaScript(
48 ClassFile jc, Appendable out, Collection<? super String> references
52 this.references = references;
56 * Converts a given class file to a JavaScript version.
58 * @param classFile input stream with code of the .class file
59 * @param out a {@link StringBuilder} or similar to generate the output to
60 * @param references a write only collection where the system adds list of
61 * other classes that were referenced and should be loaded in order the
62 * generated JavaScript code works properly. The names are in internal
63 * JVM form so String is <code>java/lang/String</code>. Can be <code>null</code>
64 * if one is not interested in knowing references
65 * @throws IOException if something goes wrong during read or write or translating
68 public static void compile(
69 InputStream classFile, Appendable out,
70 Collection<? super String> references
71 ) throws IOException {
72 ClassFile jc = new ClassFile(classFile, true);
73 ByteCodeToJavaScript compiler = new ByteCodeToJavaScript(
76 List<String> toInitilize = new ArrayList<String>();
77 for (Method m : jc.getMethods()) {
79 compiler.generateStaticMethod(m, toInitilize);
81 compiler.generateInstanceMethod(m);
84 for (Variable v : jc.getVariables()) {
86 compiler.generateStaticField(v);
90 final String className = jc.getName().getInternalName().replace('/', '_');
91 out.append("\nfunction ").append(className);
93 for (Method m : jc.getMethods()) {
94 if (!m.isStatic() && !m.isPrivate() && !m.getName().contains("<init>")) {
95 compiler.generateMethodReference(m);
98 for (Variable v : jc.getVariables()) {
100 out.append("\n this." + v.getName() + " = 0;");
103 out.append("\n this.$instOf_").append(className).append(" = true;");
104 for (ClassName superInterface : jc.getInterfaces()) {
105 out.append("\n this.$instOf_").append(superInterface.getInternalName().replace('/', '_')).append(" = true;");
108 ClassName sc = jc.getSuperClass();
110 out.append("\n").append(className)
111 .append(".prototype = new ").append(sc.getInternalName().replace('/', '_'));
113 for (String init : toInitilize) {
114 out.append("\n").append(init).append("();");
117 private void generateStaticMethod(Method m, List<String> toInitilize) throws IOException {
118 final String mn = findMethodName(m);
119 out.append("\nfunction ").append(
120 jc.getName().getInternalName().replace('/', '_')
121 ).append('_').append(mn);
122 if (mn.equals("classV")) {
123 toInitilize.add(jc.getName().getInternalName().replace('/', '_') + '_' + mn);
127 List<Parameter> args = m.getParameters();
128 for (int index = 0, i = 0; i < args.size(); i++) {
130 out.append("arg").append(String.valueOf(index));
132 final String desc = findDescriptor(args.get(i).getDescriptor());
133 if ("D".equals(desc) || "J".equals(desc)) {
139 out.append(") {").append("\n");
140 final Code code = m.getCode();
142 int len = code.getMaxLocals();
143 for (int index = args.size(), i = args.size(); i < len; i++) {
145 out.append("arg").append(String.valueOf(i)).append(";\n");
147 out.append(" var stack = new Array();\n");
148 produceCode(code.getByteCodes());
150 out.append(" /* no code found for ").append(m.getTypeSignature()).append(" */\n");
155 private void generateMethodReference(Method m) throws IOException {
156 final String name = findMethodName(m);
157 out.append("\n this.").append(name).append(" = ")
158 .append(jc.getName().getInternalName().replace('/', '_'))
159 .append('_').append(name).append(";");
162 private void generateInstanceMethod(Method m) throws IOException {
163 out.append("\nfunction ").append(
164 jc.getName().getInternalName().replace('/', '_')
165 ).append('_').append(findMethodName(m));
168 List<Parameter> args = m.getParameters();
169 for (int index = 1, i = 0; i < args.size(); i++) {
171 out.append("arg").append(String.valueOf(index));
172 final String desc = findDescriptor(args.get(i).getDescriptor());
173 if ("D".equals(desc) || "J".equals(desc)) {
179 out.append(") {").append("\n");
180 final Code code = m.getCode();
182 int len = code.getMaxLocals();
183 for (int index = args.size(), i = args.size(); i < len; i++) {
185 out.append("arg").append(String.valueOf(i + 1)).append(";\n");
187 out.append(";\n var stack = new Array(");
188 out.append(Integer.toString(code.getMaxStack()));
190 produceCode(code.getByteCodes());
192 out.append(" /* no code found for ").append(m.getTypeSignature()).append(" */\n");
197 private void produceCode(byte[] byteCodes) throws IOException {
198 out.append("\n var gt = 0;\n for(;;) switch(gt) {\n");
199 for (int i = 0; i < byteCodes.length; i++) {
201 out.append(" case " + i).append(": ");
202 final int c = (byteCodes[i] + 256) % 256;
209 out.append("stack.push(arg0);");
216 out.append("stack.push(arg1);");
223 out.append("stack.push(arg2);");
230 out.append("stack.push(arg3);");
237 final int indx = (byteCodes[++i] + 256) % 256;
238 out.append("stack.push(arg").append(indx + ");");
246 final int indx = (byteCodes[++i] + 256) % 256;
247 out.append("arg" + indx).append(" = stack.pop()");
255 out.append("arg0 = stack.pop();");
262 out.append("arg1 = stack.pop();");
269 out.append("arg2 = stack.pop();");
276 out.append("arg3 = stack.pop();");
282 out.append("stack.push(stack.pop() + stack.pop());");
288 out.append("{ var tmp = stack.pop(); stack.push(stack.pop() - tmp); }");
294 out.append("stack.push(stack.pop() * stack.pop());");
298 out.append("{ var tmp = stack.pop(); stack.push(Math.floor(stack.pop() / tmp)); }");
302 out.append("{ var tmp = stack.pop(); stack.push(stack.pop() / tmp); }");
306 out.append("stack.push(stack.pop() & stack.pop());");
310 out.append("stack.push(stack.pop() | stack.pop());");
314 out.append("stack.push(stack.pop() ^ stack.pop());");
317 final int varIndx = (byteCodes[++i] + 256) % 256;
318 final int incrBy = (byteCodes[++i] + 256) % 256;
320 out.append("arg" + varIndx).append("++;");
322 out.append("arg" + varIndx).append(" += " + incrBy).append(";");
327 out.append("return;");
334 out.append("return stack.pop();");
345 out.append("/* number conversion */");
351 out.append("stack.push(Math.floor(stack.pop()));");
356 out.append("/* number conversion */");
362 out.append("stack.push(0);");
368 out.append("stack.push(1);");
372 out.append("stack.push(2);");
375 out.append("stack.push(3);");
378 out.append("stack.push(4);");
381 out.append("stack.push(5);");
384 int indx = byteCodes[++i];
385 CPEntry entry = jc.getConstantPool().get(indx);
386 String v = encodeConstant(entry);
387 out.append("stack.push(").append(v).append(");");
392 int indx = readIntArg(byteCodes, i);
393 CPEntry entry = jc.getConstantPool().get(indx);
395 String v = encodeConstant(entry);
396 out.append("stack.push(").append(v).append(");");
404 out.append("{ var delta = stack.pop() - stack.pop(); stack.push(delta < 0 ?-1 : (delta == 0 ? 0 : 1)); }");
408 i = generateIf(byteCodes, i, "==");
412 int indx = i + readIntArg(byteCodes, i);
413 out.append("if (stack.pop() == 0) { gt = " + indx);
414 out.append("; continue; }");
419 int indx = i + readIntArg(byteCodes, i);
420 out.append("if (stack.pop() != 0) { gt = " + indx);
421 out.append("; continue; }");
426 int indx = i + readIntArg(byteCodes, i);
427 out.append("if (stack.pop() < 0) { gt = " + indx);
428 out.append("; continue; }");
433 int indx = i + readIntArg(byteCodes, i);
434 out.append("if (stack.pop() <= 0) { gt = " + indx);
435 out.append("; continue; }");
440 int indx = i + readIntArg(byteCodes, i);
441 out.append("if (stack.pop() > 0) { gt = " + indx);
442 out.append("; continue; }");
447 int indx = i + readIntArg(byteCodes, i);
448 out.append("if (stack.pop() >= 0) { gt = " + indx);
449 out.append("; continue; }");
454 int indx = i + readIntArg(byteCodes, i);
455 out.append("if (stack.pop()) { gt = " + indx);
456 out.append("; continue; }");
461 int indx = i + readIntArg(byteCodes, i);
462 out.append("if (!stack.pop()) { gt = " + indx);
463 out.append("; continue; }");
468 i = generateIf(byteCodes, i, "!=");
471 i = generateIf(byteCodes, i, ">");
474 i = generateIf(byteCodes, i, ">=");
477 i = generateIf(byteCodes, i, "<");
480 i = generateIf(byteCodes, i, "<=");
483 int indx = i + readIntArg(byteCodes, i);
484 out.append("gt = " + indx).append("; continue;");
488 case bc_invokeinterface:
489 case bc_invokevirtual:
490 i = invokeVirtualMethod(byteCodes, i);
492 case bc_invokespecial:
493 i = invokeStaticMethod(byteCodes, i, false);
495 case bc_invokestatic:
496 i = invokeStaticMethod(byteCodes, i, true);
499 int indx = readIntArg(byteCodes, i);
500 CPClassInfo ci = jc.getConstantPool().getClass(indx);
501 out.append("stack.push(");
502 out.append("new ").append(ci.getClassName().getInternalName().replace('/','_'));
504 addReference(ci.getClassName().getInternalName());
509 int type = byteCodes[i++];
510 out.append("stack.push(new Array(stack.pop()));");
514 i += 2; // skip type of array
515 out.append("stack.push(new Array(stack.pop()));");
519 out.append("stack.push(stack.pop().length);");
529 out.append("{ var value = stack.pop(); var indx = stack.pop(); stack.pop()[indx] = value; }");
540 out.append("{ var indx = stack.pop(); stack.push(stack.pop()[indx]); }");
544 out.append("stack.push(stack[stack.length - 1]);");
547 out.append("stack.push(" + byteCodes[++i] + ");");
550 out.append("stack.push(" + readIntArg(byteCodes, i) + ");");
554 int indx = readIntArg(byteCodes, i);
555 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
556 out.append("stack.push(stack.pop().").append(fi.getFieldName()).append(");");
561 int indx = readIntArg(byteCodes, i);
562 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
563 final String in = fi.getClassName().getInternalName();
564 out.append("stack.push(").append(in.replace('/', '_'));
565 out.append('_').append(fi.getFieldName()).append(");");
571 int indx = readIntArg(byteCodes, i);
572 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
573 final String in = fi.getClassName().getInternalName();
574 out.append(in.replace('/', '_'));
575 out.append('_').append(fi.getFieldName()).append(" = stack.pop();");
581 int indx = readIntArg(byteCodes, i);
582 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
583 out.append("{ var v = stack.pop(); stack.pop().")
584 .append(fi.getFieldName()).append(" = v; }");
589 int indx = readIntArg(byteCodes, i);
590 CPClassInfo ci = jc.getConstantPool().getClass(indx);
591 out.append("if(stack[stack.length - 1].$instOf_")
592 .append(ci.getClassName().getInternalName().replace('/', '_'))
593 .append(" != 1) throw {};"); // XXX proper exception
597 case bc_instanceof: {
598 int indx = readIntArg(byteCodes, i);
599 CPClassInfo ci = jc.getConstantPool().getClass(indx);
600 out.append("stack.push(stack.pop().$instOf_")
601 .append(ci.getClassName().getInternalName().replace('/', '_'))
602 .append(" ? 1 : 0);");
609 for (int j = prev; j <= i; j++) {
611 final int cc = (byteCodes[j] + 256) % 256;
612 out.append(Integer.toString(cc));
619 private int generateIf(byte[] byteCodes, int i, final String test) throws IOException {
620 int indx = i + readIntArg(byteCodes, i);
621 out.append("if (stack.pop() ").append(test).append(" stack.pop()) { gt = " + indx);
622 out.append("; continue; }");
626 private int readIntArg(byte[] byteCodes, int offsetInstruction) {
627 final int indxHi = byteCodes[offsetInstruction + 1] << 8;
628 final int indxLo = byteCodes[offsetInstruction + 2];
629 return (indxHi & 0xffffff00) | (indxLo & 0xff);
632 private static int countArgs(String descriptor, boolean[] hasReturnType, StringBuilder sig) {
635 Boolean count = null;
636 boolean array = false;
637 int firstPos = sig.length();
638 while (i < descriptor.length()) {
639 char ch = descriptor.charAt(i++);
665 hasReturnType[0] = true;
666 sig.insert(firstPos, ch);
668 sig.insert(firstPos, 'A');
674 hasReturnType[0] = false;
675 sig.insert(firstPos, 'V');
678 int next = descriptor.indexOf(';', i);
685 sig.append(descriptor.substring(i, next).replace('/', '_'));
687 sig.insert(firstPos, descriptor.substring(i, next).replace('/', '_'));
688 sig.insert(firstPos, ch);
690 sig.insert(firstPos, 'A');
692 hasReturnType[0] = true;
700 break; // invalid character
706 private void generateStaticField(Variable v) throws IOException {
708 .append(jc.getName().getInternalName().replace('/', '_'))
709 .append('_').append(v.getName()).append(" = 0;");
712 private String findMethodName(Method m) {
713 StringBuilder tmp = new StringBuilder();
714 if ("<init>".equals(m.getName())) { // NOI18N
715 tmp.append("consV"); // NOI18N
716 } else if ("<clinit>".equals(m.getName())) { // NOI18N
717 tmp.append("classV"); // NOI18N
719 tmp.append(m.getName());
720 outType(m.getReturnType(), tmp);
722 List<Parameter> args = m.getParameters();
723 for (Parameter t : args) {
724 outType(t.getDescriptor(), tmp);
726 return tmp.toString();
729 private String findMethodName(CPMethodInfo mi, int[] cnt, boolean[] hasReturn) {
730 StringBuilder name = new StringBuilder();
731 if ("<init>".equals(mi.getName())) { // NOI18N
732 name.append("cons"); // NOI18N
734 name.append(mi.getName());
736 cnt[0] = countArgs(findDescriptor(mi.getDescriptor()), hasReturn, name);
737 return name.toString();
740 private int invokeStaticMethod(byte[] byteCodes, int i, boolean isStatic)
742 int methodIndex = readIntArg(byteCodes, i);
743 CPMethodInfo mi = (CPMethodInfo) jc.getConstantPool().get(methodIndex);
744 boolean[] hasReturn = { false };
746 String mn = findMethodName(mi, cnt, hasReturn);
748 for (int j = cnt[0] - 1; j >= 0; j--) {
749 out.append("var v" + j).append(" = stack.pop(); ");
753 out.append("stack.push(");
755 final String in = mi.getClassName().getInternalName();
756 out.append(in.replace('/', '_'));
762 out.append("stack.pop()");
765 for (int j = 0; j < cnt[0]; j++) {
779 private int invokeVirtualMethod(byte[] byteCodes, int i)
781 int methodIndex = readIntArg(byteCodes, i);
782 CPMethodInfo mi = (CPMethodInfo) jc.getConstantPool().get(methodIndex);
783 boolean[] hasReturn = { false };
785 String mn = findMethodName(mi, cnt, hasReturn);
787 for (int j = cnt[0] - 1; j >= 0; j--) {
788 out.append("var v" + j).append(" = stack.pop(); ");
790 out.append("var self = stack.pop(); ");
792 out.append("stack.push(");
798 for (int j = 0; j < cnt[0]; j++) {
811 private void addReference(String cn) {
812 if (references != null) {
817 private void outType(String d, StringBuilder out) {
819 while (d.charAt(0) == '[') {
823 if (d.charAt(0) == 'L') {
824 assert d.charAt(d.length() - 1) == ';';
825 out.append(d.replace('/', '_').substring(0, d.length() - 1));
831 private String encodeConstant(CPEntry entry) {
833 if (entry instanceof CPStringInfo) {
834 v = "\"" + entry.getValue().toString().replace("\"", "\\\"") + "\"";
836 v = entry.getValue().toString();
841 private String findDescriptor(String d) {
842 return d.replace('[', 'A');