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;");
105 ClassName sc = jc.getSuperClass();
107 out.append("\n").append(className)
108 .append(".prototype = new ").append(sc.getInternalName().replace('/', '_'));
110 for (String init : toInitilize) {
111 out.append("\n").append(init).append("();");
114 private void generateStaticMethod(Method m, List<String> toInitilize) throws IOException {
115 final String mn = findMethodName(m);
116 out.append("\nfunction ").append(
117 jc.getName().getInternalName().replace('/', '_')
118 ).append('_').append(mn);
119 if (mn.equals("classV")) {
120 toInitilize.add(jc.getName().getInternalName().replace('/', '_') + '_' + mn);
124 List<Parameter> args = m.getParameters();
125 for (int index = 0, i = 0; i < args.size(); i++) {
127 out.append("arg").append(String.valueOf(index));
129 final String desc = args.get(i).getDescriptor();
130 if ("D".equals(desc) || "J".equals(desc)) {
136 out.append(") {").append("\n");
137 final Code code = m.getCode();
139 int len = code.getMaxLocals();
140 for (int index = args.size(), i = args.size(); i < len; i++) {
142 out.append("arg").append(String.valueOf(i)).append(";\n");
144 out.append(" var stack = new Array();\n");
145 produceCode(code.getByteCodes());
147 out.append(" /* no code found for ").append(m.getTypeSignature()).append(" */\n");
152 private void generateMethodReference(Method m) throws IOException {
153 final String name = findMethodName(m);
154 out.append("\n this.").append(name).append(" = ")
155 .append(jc.getName().getInternalName().replace('/', '_'))
156 .append('_').append(name).append(";");
159 private void generateInstanceMethod(Method m) throws IOException {
160 out.append("\nfunction ").append(
161 jc.getName().getInternalName().replace('/', '_')
162 ).append('_').append(findMethodName(m));
165 List<Parameter> args = m.getParameters();
166 for (int index = 1, i = 0; i < args.size(); i++) {
168 out.append("arg").append(String.valueOf(index));
169 final String desc = args.get(i).getDescriptor();
170 if ("D".equals(desc) || "J".equals(desc)) {
176 out.append(") {").append("\n");
177 final Code code = m.getCode();
179 int len = code.getMaxLocals();
180 for (int index = args.size(), i = args.size(); i < len; i++) {
182 out.append("arg").append(String.valueOf(i + 1)).append(";\n");
184 out.append(";\n var stack = new Array(");
185 out.append(Integer.toString(code.getMaxStack()));
187 produceCode(code.getByteCodes());
189 out.append(" /* no code found for ").append(m.getTypeSignature()).append(" */\n");
194 private void produceCode(byte[] byteCodes) throws IOException {
195 out.append("\n var gt = 0;\n for(;;) switch(gt) {\n");
196 for (int i = 0; i < byteCodes.length; i++) {
198 out.append(" case " + i).append(": ");
199 final int c = (byteCodes[i] + 256) % 256;
206 out.append("stack.push(arg0);");
213 out.append("stack.push(arg1);");
220 out.append("stack.push(arg2);");
227 out.append("stack.push(arg3);");
234 final int indx = (byteCodes[++i] + 256) % 256;
235 out.append("stack.push(arg").append(indx + ");");
243 out.append("arg0 = stack.pop();");
250 out.append("arg1 = stack.pop();");
257 out.append("arg2 = stack.pop();");
264 out.append("arg3 = stack.pop();");
270 out.append("stack.push(stack.pop() + stack.pop());");
276 out.append("{ var tmp = stack.pop(); stack.push(stack.pop() - tmp); }");
282 out.append("stack.push(stack.pop() * stack.pop());");
286 out.append("{ var tmp = stack.pop(); stack.push(Math.floor(stack.pop() / tmp)); }");
290 out.append("{ var tmp = stack.pop(); stack.push(stack.pop() / tmp); }");
294 out.append("stack.push(stack.pop() & stack.pop());");
298 out.append("stack.push(stack.pop() | stack.pop());");
302 out.append("stack.push(stack.pop() ^ stack.pop());");
305 final int varIndx = (byteCodes[++i] + 256) % 256;
306 final int incrBy = (byteCodes[++i] + 256) % 256;
308 out.append("arg" + varIndx).append("++;");
310 out.append("arg" + varIndx).append(" += " + incrBy).append(";");
315 out.append("return;");
322 out.append("return stack.pop();");
333 out.append("/* number conversion */");
339 out.append("stack.push(Math.floor(stack.pop()));");
344 out.append("/* number conversion */");
350 out.append("stack.push(0);");
356 out.append("stack.push(1);");
360 out.append("stack.push(2);");
363 out.append("stack.push(3);");
366 out.append("stack.push(4);");
369 out.append("stack.push(5);");
372 int indx = byteCodes[++i];
373 CPEntry entry = jc.getConstantPool().get(indx);
374 String v = encodeConstant(entry);
375 out.append("stack.push(").append(v).append(");");
380 int indx = readIntArg(byteCodes, i);
381 CPEntry entry = jc.getConstantPool().get(indx);
383 String v = encodeConstant(entry);
384 out.append("stack.push(").append(v).append(");");
392 out.append("{ var delta = stack.pop() - stack.pop(); stack.push(delta < 0 ?-1 : (delta == 0 ? 0 : 1)); }");
396 i = generateIf(byteCodes, i, "==");
400 int indx = i + readIntArg(byteCodes, i);
401 out.append("if (stack.pop() == 0) { gt = " + indx);
402 out.append("; continue; }");
407 int indx = i + readIntArg(byteCodes, i);
408 out.append("if (stack.pop() != 0) { gt = " + indx);
409 out.append("; continue; }");
414 int indx = i + readIntArg(byteCodes, i);
415 out.append("if (stack.pop() < 0) { gt = " + indx);
416 out.append("; continue; }");
421 int indx = i + readIntArg(byteCodes, i);
422 out.append("if (stack.pop() <= 0) { gt = " + indx);
423 out.append("; continue; }");
428 int indx = i + readIntArg(byteCodes, i);
429 out.append("if (stack.pop() > 0) { gt = " + indx);
430 out.append("; continue; }");
435 int indx = i + readIntArg(byteCodes, i);
436 out.append("if (stack.pop() >= 0) { gt = " + indx);
437 out.append("; continue; }");
442 int indx = i + readIntArg(byteCodes, i);
443 out.append("if (stack.pop()) { gt = " + indx);
444 out.append("; continue; }");
449 int indx = i + readIntArg(byteCodes, i);
450 out.append("if (!stack.pop()) { gt = " + indx);
451 out.append("; continue; }");
456 i = generateIf(byteCodes, i, "!=");
459 i = generateIf(byteCodes, i, ">");
462 i = generateIf(byteCodes, i, ">=");
465 i = generateIf(byteCodes, i, "<");
468 i = generateIf(byteCodes, i, "<=");
471 int indx = i + readIntArg(byteCodes, i);
472 out.append("gt = " + indx).append("; continue;");
476 case bc_invokeinterface:
477 case bc_invokevirtual:
478 i = invokeVirtualMethod(byteCodes, i);
480 case bc_invokespecial:
481 i = invokeStaticMethod(byteCodes, i, false);
483 case bc_invokestatic:
484 i = invokeStaticMethod(byteCodes, i, true);
487 int indx = readIntArg(byteCodes, i);
488 CPClassInfo ci = jc.getConstantPool().getClass(indx);
489 out.append("stack.push(");
490 out.append("new ").append(ci.getClassName().getInternalName().replace('/','_'));
492 addReference(ci.getClassName().getInternalName());
497 int type = byteCodes[i++];
498 out.append("stack.push(new Array(stack.pop()));");
502 i += 2; // skip type of array
503 out.append("stack.push(new Array(stack.pop()));");
507 out.append("stack.push(stack.pop().length);");
517 out.append("{ var value = stack.pop(); var indx = stack.pop(); stack.pop()[indx] = value; }");
528 out.append("{ var indx = stack.pop(); stack.push(stack.pop()[indx]); }");
532 out.append("stack.push(stack[stack.length - 1]);");
535 out.append("stack.push(" + byteCodes[++i] + ");");
538 int indx = readIntArg(byteCodes, i);
539 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
540 out.append("stack.push(stack.pop().").append(fi.getFieldName()).append(");");
545 int indx = readIntArg(byteCodes, i);
546 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
547 final String in = fi.getClassName().getInternalName();
548 out.append("stack.push(").append(in.replace('/', '_'));
549 out.append('_').append(fi.getFieldName()).append(");");
555 int indx = readIntArg(byteCodes, i);
556 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
557 final String in = fi.getClassName().getInternalName();
558 out.append(in.replace('/', '_'));
559 out.append('_').append(fi.getFieldName()).append(" = stack.pop();");
565 int indx = readIntArg(byteCodes, i);
566 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
567 out.append("{ var v = stack.pop(); stack.pop().")
568 .append(fi.getFieldName()).append(" = v; }");
572 case bc_instanceof: {
573 int indx = readIntArg(byteCodes, i);
574 CPClassInfo ci = jc.getConstantPool().getClass(indx);
575 out.append("stack.push(stack.pop().$instOf_")
576 .append(ci.getClassName().getInternalName().replace('/', '_'))
577 .append(" ? 1 : 0);");
583 for (int j = prev; j <= i; j++) {
585 final int cc = (byteCodes[j] + 256) % 256;
586 out.append(Integer.toString(cc));
593 private int generateIf(byte[] byteCodes, int i, final String test) throws IOException {
594 int indx = i + readIntArg(byteCodes, i);
595 out.append("if (stack.pop() ").append(test).append(" stack.pop()) { gt = " + indx);
596 out.append("; continue; }");
600 private int readIntArg(byte[] byteCodes, int offsetInstruction) {
601 final int indxHi = byteCodes[offsetInstruction + 1] << 8;
602 final int indxLo = byteCodes[offsetInstruction + 2];
603 return (indxHi & 0xffffff00) | (indxLo & 0xff);
606 private static int countArgs(String descriptor, boolean[] hasReturnType, StringBuilder sig) {
609 Boolean count = null;
610 int firstPos = sig.length();
611 while (i < descriptor.length()) {
612 char ch = descriptor.charAt(i++);
632 hasReturnType[0] = true;
633 sig.insert(firstPos, ch);
638 hasReturnType[0] = false;
639 sig.insert(firstPos, 'V');
642 int next = descriptor.indexOf(';', i);
646 sig.append(descriptor.substring(i, next).replace('/', '_'));
648 sig.insert(firstPos, descriptor.substring(i, next).replace('/', '_'));
649 sig.insert(firstPos, ch);
650 hasReturnType[0] = true;
658 break; // invalid character
664 private void generateStaticField(Variable v) throws IOException {
666 .append(jc.getName().getInternalName().replace('/', '_'))
667 .append('_').append(v.getName()).append(" = 0;");
670 private String findMethodName(Method m) {
671 StringBuilder tmp = new StringBuilder();
672 if ("<init>".equals(m.getName())) { // NOI18N
673 tmp.append("consV"); // NOI18N
674 } else if ("<clinit>".equals(m.getName())) { // NOI18N
675 tmp.append("classV"); // NOI18N
677 tmp.append(m.getName());
678 outType(m.getReturnType(), tmp);
680 List<Parameter> args = m.getParameters();
681 for (Parameter t : args) {
682 outType(t.getDescriptor(), tmp);
684 return tmp.toString();
687 private String findMethodName(CPMethodInfo mi, int[] cnt, boolean[] hasReturn) {
688 StringBuilder name = new StringBuilder();
689 if ("<init>".equals(mi.getName())) { // NOI18N
690 name.append("cons"); // NOI18N
692 name.append(mi.getName());
694 cnt[0] = countArgs(mi.getDescriptor(), hasReturn, name);
695 return name.toString();
698 private int invokeStaticMethod(byte[] byteCodes, int i, boolean isStatic)
700 int methodIndex = readIntArg(byteCodes, i);
701 CPMethodInfo mi = (CPMethodInfo) jc.getConstantPool().get(methodIndex);
702 boolean[] hasReturn = { false };
704 String mn = findMethodName(mi, cnt, hasReturn);
706 for (int j = cnt[0] - 1; j >= 0; j--) {
707 out.append("var v" + j).append(" = stack.pop(); ");
711 out.append("stack.push(");
713 final String in = mi.getClassName().getInternalName();
714 out.append(in.replace('/', '_'));
720 out.append("stack.pop()");
723 for (int j = 0; j < cnt[0]; j++) {
737 private int invokeVirtualMethod(byte[] byteCodes, int i)
739 int methodIndex = readIntArg(byteCodes, i);
740 CPMethodInfo mi = (CPMethodInfo) jc.getConstantPool().get(methodIndex);
741 boolean[] hasReturn = { false };
743 String mn = findMethodName(mi, cnt, hasReturn);
745 for (int j = cnt[0] - 1; j >= 0; j--) {
746 out.append("var v" + j).append(" = stack.pop(); ");
748 out.append("var self = stack.pop(); ");
750 out.append("stack.push(");
756 for (int j = 0; j < cnt[0]; j++) {
769 private void addReference(String cn) {
770 if (references != null) {
775 private void outType(final String d, StringBuilder out) {
776 if (d.charAt(0) == 'L') {
777 assert d.charAt(d.length() - 1) == ';';
778 out.append(d.replace('/', '_').substring(0, d.length() - 1));
784 private String encodeConstant(CPEntry entry) {
786 if (entry instanceof CPStringInfo) {
787 v = "\"" + entry.getValue().toString().replace("\"", "\\\"") + "\"";
789 v = entry.getValue().toString();