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()) {
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 = 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 = 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 out.append("arg0 = stack.pop();");
253 out.append("arg1 = stack.pop();");
260 out.append("arg2 = stack.pop();");
267 out.append("arg3 = stack.pop();");
273 out.append("stack.push(stack.pop() + stack.pop());");
279 out.append("{ var tmp = stack.pop(); stack.push(stack.pop() - tmp); }");
285 out.append("stack.push(stack.pop() * stack.pop());");
289 out.append("{ var tmp = stack.pop(); stack.push(Math.floor(stack.pop() / tmp)); }");
293 out.append("{ var tmp = stack.pop(); stack.push(stack.pop() / tmp); }");
297 out.append("stack.push(stack.pop() & stack.pop());");
301 out.append("stack.push(stack.pop() | stack.pop());");
305 out.append("stack.push(stack.pop() ^ stack.pop());");
308 final int varIndx = (byteCodes[++i] + 256) % 256;
309 final int incrBy = (byteCodes[++i] + 256) % 256;
311 out.append("arg" + varIndx).append("++;");
313 out.append("arg" + varIndx).append(" += " + incrBy).append(";");
318 out.append("return;");
325 out.append("return stack.pop();");
336 out.append("/* number conversion */");
342 out.append("stack.push(Math.floor(stack.pop()));");
347 out.append("/* number conversion */");
353 out.append("stack.push(0);");
359 out.append("stack.push(1);");
363 out.append("stack.push(2);");
366 out.append("stack.push(3);");
369 out.append("stack.push(4);");
372 out.append("stack.push(5);");
375 int indx = byteCodes[++i];
376 CPEntry entry = jc.getConstantPool().get(indx);
377 String v = encodeConstant(entry);
378 out.append("stack.push(").append(v).append(");");
383 int indx = readIntArg(byteCodes, i);
384 CPEntry entry = jc.getConstantPool().get(indx);
386 String v = encodeConstant(entry);
387 out.append("stack.push(").append(v).append(");");
395 out.append("{ var delta = stack.pop() - stack.pop(); stack.push(delta < 0 ?-1 : (delta == 0 ? 0 : 1)); }");
399 i = generateIf(byteCodes, i, "==");
403 int indx = i + readIntArg(byteCodes, i);
404 out.append("if (stack.pop() == 0) { gt = " + indx);
405 out.append("; continue; }");
410 int indx = i + readIntArg(byteCodes, i);
411 out.append("if (stack.pop() != 0) { gt = " + indx);
412 out.append("; continue; }");
417 int indx = i + readIntArg(byteCodes, i);
418 out.append("if (stack.pop() < 0) { gt = " + indx);
419 out.append("; continue; }");
424 int indx = i + readIntArg(byteCodes, i);
425 out.append("if (stack.pop() <= 0) { gt = " + indx);
426 out.append("; continue; }");
431 int indx = i + readIntArg(byteCodes, i);
432 out.append("if (stack.pop() > 0) { gt = " + indx);
433 out.append("; continue; }");
438 int indx = i + readIntArg(byteCodes, i);
439 out.append("if (stack.pop() >= 0) { gt = " + indx);
440 out.append("; continue; }");
445 int indx = i + readIntArg(byteCodes, i);
446 out.append("if (stack.pop()) { gt = " + indx);
447 out.append("; continue; }");
452 int indx = i + readIntArg(byteCodes, i);
453 out.append("if (!stack.pop()) { gt = " + indx);
454 out.append("; continue; }");
459 i = generateIf(byteCodes, i, "!=");
462 i = generateIf(byteCodes, i, ">");
465 i = generateIf(byteCodes, i, ">=");
468 i = generateIf(byteCodes, i, "<");
471 i = generateIf(byteCodes, i, "<=");
474 int indx = i + readIntArg(byteCodes, i);
475 out.append("gt = " + indx).append("; continue;");
479 case bc_invokeinterface:
480 case bc_invokevirtual:
481 i = invokeVirtualMethod(byteCodes, i);
483 case bc_invokespecial:
484 i = invokeStaticMethod(byteCodes, i, false);
486 case bc_invokestatic:
487 i = invokeStaticMethod(byteCodes, i, true);
490 int indx = readIntArg(byteCodes, i);
491 CPClassInfo ci = jc.getConstantPool().getClass(indx);
492 out.append("stack.push(");
493 out.append("new ").append(ci.getClassName().getInternalName().replace('/','_'));
495 addReference(ci.getClassName().getInternalName());
500 int type = byteCodes[i++];
501 out.append("stack.push(new Array(stack.pop()));");
505 i += 2; // skip type of array
506 out.append("stack.push(new Array(stack.pop()));");
510 out.append("stack.push(stack.pop().length);");
520 out.append("{ var value = stack.pop(); var indx = stack.pop(); stack.pop()[indx] = value; }");
531 out.append("{ var indx = stack.pop(); stack.push(stack.pop()[indx]); }");
535 out.append("stack.push(stack[stack.length - 1]);");
538 out.append("stack.push(" + byteCodes[++i] + ");");
541 int indx = readIntArg(byteCodes, i);
542 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
543 out.append("stack.push(stack.pop().").append(fi.getFieldName()).append(");");
548 int indx = readIntArg(byteCodes, i);
549 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
550 final String in = fi.getClassName().getInternalName();
551 out.append("stack.push(").append(in.replace('/', '_'));
552 out.append('_').append(fi.getFieldName()).append(");");
558 int indx = readIntArg(byteCodes, i);
559 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
560 final String in = fi.getClassName().getInternalName();
561 out.append(in.replace('/', '_'));
562 out.append('_').append(fi.getFieldName()).append(" = stack.pop();");
568 int indx = readIntArg(byteCodes, i);
569 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
570 out.append("{ var v = stack.pop(); stack.pop().")
571 .append(fi.getFieldName()).append(" = v; }");
576 int indx = readIntArg(byteCodes, i);
577 CPClassInfo ci = jc.getConstantPool().getClass(indx);
578 out.append("if(stack[stack.length - 1].$instOf_")
579 .append(ci.getClassName().getInternalName().replace('/', '_'))
580 .append(" != 1) throw {};"); // XXX proper exception
584 case bc_instanceof: {
585 int indx = readIntArg(byteCodes, i);
586 CPClassInfo ci = jc.getConstantPool().getClass(indx);
587 out.append("stack.push(stack.pop().$instOf_")
588 .append(ci.getClassName().getInternalName().replace('/', '_'))
589 .append(" ? 1 : 0);");
596 for (int j = prev; j <= i; j++) {
598 final int cc = (byteCodes[j] + 256) % 256;
599 out.append(Integer.toString(cc));
606 private int generateIf(byte[] byteCodes, int i, final String test) throws IOException {
607 int indx = i + readIntArg(byteCodes, i);
608 out.append("if (stack.pop() ").append(test).append(" stack.pop()) { gt = " + indx);
609 out.append("; continue; }");
613 private int readIntArg(byte[] byteCodes, int offsetInstruction) {
614 final int indxHi = byteCodes[offsetInstruction + 1] << 8;
615 final int indxLo = byteCodes[offsetInstruction + 2];
616 return (indxHi & 0xffffff00) | (indxLo & 0xff);
619 private static int countArgs(String descriptor, boolean[] hasReturnType, StringBuilder sig) {
622 Boolean count = null;
623 int firstPos = sig.length();
624 while (i < descriptor.length()) {
625 char ch = descriptor.charAt(i++);
645 hasReturnType[0] = true;
646 sig.insert(firstPos, ch);
651 hasReturnType[0] = false;
652 sig.insert(firstPos, 'V');
655 int next = descriptor.indexOf(';', i);
659 sig.append(descriptor.substring(i, next).replace('/', '_'));
661 sig.insert(firstPos, descriptor.substring(i, next).replace('/', '_'));
662 sig.insert(firstPos, ch);
663 hasReturnType[0] = true;
671 break; // invalid character
677 private void generateStaticField(Variable v) throws IOException {
679 .append(jc.getName().getInternalName().replace('/', '_'))
680 .append('_').append(v.getName()).append(" = 0;");
683 private String findMethodName(Method m) {
684 StringBuilder tmp = new StringBuilder();
685 if ("<init>".equals(m.getName())) { // NOI18N
686 tmp.append("consV"); // NOI18N
687 } else if ("<clinit>".equals(m.getName())) { // NOI18N
688 tmp.append("classV"); // NOI18N
690 tmp.append(m.getName());
691 outType(m.getReturnType(), tmp);
693 List<Parameter> args = m.getParameters();
694 for (Parameter t : args) {
695 outType(t.getDescriptor(), tmp);
697 return tmp.toString();
700 private String findMethodName(CPMethodInfo mi, int[] cnt, boolean[] hasReturn) {
701 StringBuilder name = new StringBuilder();
702 if ("<init>".equals(mi.getName())) { // NOI18N
703 name.append("cons"); // NOI18N
705 name.append(mi.getName());
707 cnt[0] = countArgs(mi.getDescriptor(), hasReturn, name);
708 return name.toString();
711 private int invokeStaticMethod(byte[] byteCodes, int i, boolean isStatic)
713 int methodIndex = readIntArg(byteCodes, i);
714 CPMethodInfo mi = (CPMethodInfo) jc.getConstantPool().get(methodIndex);
715 boolean[] hasReturn = { false };
717 String mn = findMethodName(mi, cnt, hasReturn);
719 for (int j = cnt[0] - 1; j >= 0; j--) {
720 out.append("var v" + j).append(" = stack.pop(); ");
724 out.append("stack.push(");
726 final String in = mi.getClassName().getInternalName();
727 out.append(in.replace('/', '_'));
733 out.append("stack.pop()");
736 for (int j = 0; j < cnt[0]; j++) {
750 private int invokeVirtualMethod(byte[] byteCodes, int i)
752 int methodIndex = readIntArg(byteCodes, i);
753 CPMethodInfo mi = (CPMethodInfo) jc.getConstantPool().get(methodIndex);
754 boolean[] hasReturn = { false };
756 String mn = findMethodName(mi, cnt, hasReturn);
758 for (int j = cnt[0] - 1; j >= 0; j--) {
759 out.append("var v" + j).append(" = stack.pop(); ");
761 out.append("var self = stack.pop(); ");
763 out.append("stack.push(");
769 for (int j = 0; j < cnt[0]; j++) {
782 private void addReference(String cn) {
783 if (references != null) {
788 private void outType(final String d, StringBuilder out) {
789 if (d.charAt(0) == 'L') {
790 assert d.charAt(d.length() - 1) == ';';
791 out.append(d.replace('/', '_').substring(0, d.length() - 1));
797 private String encodeConstant(CPEntry entry) {
799 if (entry instanceof CPStringInfo) {
800 v = "\"" + entry.getValue().toString().replace("\"", "\\\"") + "\"";
802 v = entry.getValue().toString();