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 (Variable v : jc.getVariables()) {
95 out.append("\n this." + v.getName() + " = 0;");
99 ClassName sc = jc.getSuperClass();
101 out.append("\n").append(className)
102 .append(".prototype = new ").append(sc.getInternalName().replace('/', '_')).append(';');
104 for (Method m : jc.getMethods()) {
105 if (!m.isStatic() && !m.isPrivate() && !m.getName().contains("<init>")) {
106 compiler.generateMethodReference("\n" + className + ".prototype.", m);
109 out.append("\n" + className + ".prototype.$instOf_").append(className).append(" = true;");
110 for (ClassName superInterface : jc.getInterfaces()) {
111 out.append("\n" + className + ".prototype.$instOf_").append(superInterface.getInternalName().replace('/', '_')).append(" = true;");
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(String prefix, Method m) throws IOException {
156 final String name = findMethodName(m);
157 out.append(prefix).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 */");
359 out.append("stack.push(null);");
362 out.append("stack.push(-1);");
368 out.append("stack.push(0);");
374 out.append("stack.push(1);");
378 out.append("stack.push(2);");
381 out.append("stack.push(3);");
384 out.append("stack.push(4);");
387 out.append("stack.push(5);");
390 int indx = byteCodes[++i];
391 CPEntry entry = jc.getConstantPool().get(indx);
392 String v = encodeConstant(entry);
393 out.append("stack.push(").append(v).append(");");
398 int indx = readIntArg(byteCodes, i);
399 CPEntry entry = jc.getConstantPool().get(indx);
401 String v = encodeConstant(entry);
402 out.append("stack.push(").append(v).append(");");
410 out.append("{ var delta = stack.pop() - stack.pop(); stack.push(delta < 0 ?-1 : (delta == 0 ? 0 : 1)); }");
414 i = generateIf(byteCodes, i, "==");
418 int indx = i + readIntArg(byteCodes, i);
419 out.append("if (stack.pop() == 0) { gt = " + indx);
420 out.append("; continue; }");
425 int indx = i + readIntArg(byteCodes, i);
426 out.append("if (stack.pop() != 0) { gt = " + indx);
427 out.append("; continue; }");
432 int indx = i + readIntArg(byteCodes, i);
433 out.append("if (stack.pop() < 0) { gt = " + indx);
434 out.append("; continue; }");
439 int indx = i + readIntArg(byteCodes, i);
440 out.append("if (stack.pop() <= 0) { gt = " + indx);
441 out.append("; continue; }");
446 int indx = i + readIntArg(byteCodes, i);
447 out.append("if (stack.pop() > 0) { gt = " + indx);
448 out.append("; continue; }");
453 int indx = i + readIntArg(byteCodes, i);
454 out.append("if (stack.pop() >= 0) { gt = " + indx);
455 out.append("; continue; }");
460 int indx = i + readIntArg(byteCodes, i);
461 out.append("if (stack.pop()) { gt = " + indx);
462 out.append("; continue; }");
467 int indx = i + readIntArg(byteCodes, i);
468 out.append("if (!stack.pop()) { gt = " + indx);
469 out.append("; continue; }");
474 i = generateIf(byteCodes, i, "!=");
477 i = generateIf(byteCodes, i, ">");
480 i = generateIf(byteCodes, i, ">=");
483 i = generateIf(byteCodes, i, "<");
486 i = generateIf(byteCodes, i, "<=");
489 int indx = i + readIntArg(byteCodes, i);
490 out.append("gt = " + indx).append("; continue;");
494 case bc_invokeinterface: {
495 i = invokeVirtualMethod(byteCodes, i) + 2;
498 case bc_invokevirtual:
499 i = invokeVirtualMethod(byteCodes, i);
501 case bc_invokespecial:
502 i = invokeStaticMethod(byteCodes, i, false);
504 case bc_invokestatic:
505 i = invokeStaticMethod(byteCodes, i, true);
508 int indx = readIntArg(byteCodes, i);
509 CPClassInfo ci = jc.getConstantPool().getClass(indx);
510 out.append("stack.push(");
511 out.append("new ").append(ci.getClassName().getInternalName().replace('/','_'));
513 addReference(ci.getClassName().getInternalName());
518 int type = byteCodes[i++];
519 out.append("stack.push(new Array(stack.pop()));");
523 i += 2; // skip type of array
524 out.append("stack.push(new Array(stack.pop()));");
528 out.append("stack.push(stack.pop().length);");
538 out.append("{ var value = stack.pop(); var indx = stack.pop(); stack.pop()[indx] = value; }");
549 out.append("{ var indx = stack.pop(); stack.push(stack.pop()[indx]); }");
553 out.append("stack.push(stack[stack.length - 1]);");
556 out.append("stack.push(" + byteCodes[++i] + ");");
559 out.append("stack.push(" + readIntArg(byteCodes, i) + ");");
563 int indx = readIntArg(byteCodes, i);
564 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
565 out.append("stack.push(stack.pop().").append(fi.getFieldName()).append(");");
570 int indx = readIntArg(byteCodes, i);
571 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
572 final String in = fi.getClassName().getInternalName();
573 out.append("stack.push(").append(in.replace('/', '_'));
574 out.append('_').append(fi.getFieldName()).append(");");
580 int indx = readIntArg(byteCodes, i);
581 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
582 final String in = fi.getClassName().getInternalName();
583 out.append(in.replace('/', '_'));
584 out.append('_').append(fi.getFieldName()).append(" = stack.pop();");
590 int indx = readIntArg(byteCodes, i);
591 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
592 out.append("{ var v = stack.pop(); stack.pop().")
593 .append(fi.getFieldName()).append(" = v; }");
598 int indx = readIntArg(byteCodes, i);
599 CPClassInfo ci = jc.getConstantPool().getClass(indx);
600 final String type = ci.getClassName().getType();
601 if (!type.startsWith("[")) {
602 // no way to check arrays right now
603 out.append("if(stack[stack.length - 1].$instOf_")
604 .append(type.replace('/', '_'))
605 .append(" != 1) throw {};"); // XXX proper exception
610 case bc_instanceof: {
611 int indx = readIntArg(byteCodes, i);
612 CPClassInfo ci = jc.getConstantPool().getClass(indx);
613 out.append("stack.push(stack.pop().$instOf_")
614 .append(ci.getClassName().getInternalName().replace('/', '_'))
615 .append(" ? 1 : 0);");
622 for (int j = prev; j <= i; j++) {
624 final int cc = (byteCodes[j] + 256) % 256;
625 out.append(Integer.toString(cc));
632 private int generateIf(byte[] byteCodes, int i, final String test) throws IOException {
633 int indx = i + readIntArg(byteCodes, i);
634 out.append("if (stack.pop() ").append(test).append(" stack.pop()) { gt = " + indx);
635 out.append("; continue; }");
639 private int readIntArg(byte[] byteCodes, int offsetInstruction) {
640 final int indxHi = byteCodes[offsetInstruction + 1] << 8;
641 final int indxLo = byteCodes[offsetInstruction + 2];
642 return (indxHi & 0xffffff00) | (indxLo & 0xff);
645 private static int countArgs(String descriptor, boolean[] hasReturnType, StringBuilder sig) {
648 Boolean count = null;
649 boolean array = false;
650 int firstPos = sig.length();
651 while (i < descriptor.length()) {
652 char ch = descriptor.charAt(i++);
678 hasReturnType[0] = true;
679 sig.insert(firstPos, ch);
681 sig.insert(firstPos, 'A');
687 hasReturnType[0] = false;
688 sig.insert(firstPos, 'V');
691 int next = descriptor.indexOf(';', i);
698 sig.append(descriptor.substring(i, next).replace('/', '_'));
700 sig.insert(firstPos, descriptor.substring(i, next).replace('/', '_'));
701 sig.insert(firstPos, ch);
703 sig.insert(firstPos, 'A');
705 hasReturnType[0] = true;
713 break; // invalid character
719 private void generateStaticField(Variable v) throws IOException {
721 .append(jc.getName().getInternalName().replace('/', '_'))
722 .append('_').append(v.getName()).append(" = 0;");
725 private String findMethodName(Method m) {
726 StringBuilder name = new StringBuilder();
727 String descr = m.getDescriptor();
728 if ("<init>".equals(m.getName())) { // NOI18N
729 name.append("cons"); // NOI18N
730 } else if ("<clinit>".equals(m.getName())) { // NOI18N
731 name.append("class"); // NOI18N
733 name.append(m.getName());
736 boolean hasReturn[] = { false };
737 countArgs(findDescriptor(m.getDescriptor()), hasReturn, name);
738 return name.toString();
741 private String findMethodName(CPMethodInfo mi, int[] cnt, boolean[] hasReturn) {
742 StringBuilder name = new StringBuilder();
743 String descr = mi.getDescriptor();
744 if ("<init>".equals(mi.getName())) { // NOI18N
745 name.append("cons"); // NOI18N
747 name.append(mi.getName());
749 cnt[0] = countArgs(findDescriptor(mi.getDescriptor()), hasReturn, name);
750 return name.toString();
753 private int invokeStaticMethod(byte[] byteCodes, int i, boolean isStatic)
755 int methodIndex = readIntArg(byteCodes, i);
756 CPMethodInfo mi = (CPMethodInfo) jc.getConstantPool().get(methodIndex);
757 boolean[] hasReturn = { false };
759 String mn = findMethodName(mi, cnt, hasReturn);
761 for (int j = cnt[0] - 1; j >= 0; j--) {
762 out.append("var v" + j).append(" = stack.pop(); ");
766 out.append("stack.push(");
768 final String in = mi.getClassName().getInternalName();
769 out.append(in.replace('/', '_'));
775 out.append("stack.pop()");
778 for (int j = 0; j < cnt[0]; j++) {
792 private int invokeVirtualMethod(byte[] byteCodes, int i)
794 int methodIndex = readIntArg(byteCodes, i);
795 CPMethodInfo mi = (CPMethodInfo) jc.getConstantPool().get(methodIndex);
796 boolean[] hasReturn = { false };
798 String mn = findMethodName(mi, cnt, hasReturn);
800 for (int j = cnt[0] - 1; j >= 0; j--) {
801 out.append("var v" + j).append(" = stack.pop(); ");
803 out.append("var self = stack.pop(); ");
805 out.append("stack.push(");
811 for (int j = 0; j < cnt[0]; j++) {
824 private void addReference(String cn) {
825 if (references != null) {
830 private void outType(String d, StringBuilder out) {
832 while (d.charAt(0) == '[') {
836 if (d.charAt(0) == 'L') {
837 assert d.charAt(d.length() - 1) == ';';
838 out.append(d.replace('/', '_').substring(0, d.length() - 1));
844 private String encodeConstant(CPEntry entry) {
846 if (entry instanceof CPStringInfo) {
847 v = "\"" + entry.getValue().toString().replace("\"", "\\\"") + "\"";
849 v = entry.getValue().toString();
854 private String findDescriptor(String d) {
855 return d.replace('[', 'A');