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.java4browser;
20 import java.io.IOException;
21 import java.io.InputStream;
22 import java.util.List;
23 import static org.netbeans.modules.classfile.ByteCodes.*;
24 import org.netbeans.modules.classfile.CPClassInfo;
25 import org.netbeans.modules.classfile.CPEntry;
26 import org.netbeans.modules.classfile.CPFieldInfo;
27 import org.netbeans.modules.classfile.CPMethodInfo;
28 import org.netbeans.modules.classfile.ClassFile;
29 import org.netbeans.modules.classfile.Code;
30 import org.netbeans.modules.classfile.Method;
31 import org.netbeans.modules.classfile.Parameter;
32 import org.netbeans.modules.classfile.Variable;
34 /** Translator of the code inside class files to JavaScript.
36 * @author Jaroslav Tulach <jtulach@netbeans.org>
38 public final class ByteCodeToJavaScript {
39 private final ClassFile jc;
40 private final Appendable out;
42 private ByteCodeToJavaScript(ClassFile jc, Appendable out) {
47 /** Converts a given class file to a JavaScript version.
48 * @param fileName the name of the file we are reading
49 * @param classFile input stream with code of the .class file
50 * @param out a {@link StringBuilder} or similar to generate the output to
51 * @throws IOException if something goes wrong during read or write or translating
53 public static void compile(String fileName, InputStream classFile, Appendable out) throws IOException {
54 ClassFile jc = new ClassFile(classFile, true);
55 ByteCodeToJavaScript compiler = new ByteCodeToJavaScript(jc, out);
56 for (Method m : jc.getMethods()) {
58 compiler.generateStaticMethod(m);
60 compiler.generateInstanceMethod(m);
63 for (Variable v : jc.getVariables()) {
65 compiler.generateStaticField(v);
68 out.append("function java_lang_Object_consV(self){}\n"); // XXX temporary
70 out.append("\nfunction ").append(jc.getName().getExternalName().replace('.', '_'));
72 for (Method m : jc.getMethods()) {
74 compiler.generateMethodReference(m);
77 for (Variable v : jc.getVariables()) {
79 out.append("\n this." + v.getName() + " = 0;");
84 private void generateStaticMethod(Method m) throws IOException {
85 out.append("\nfunction ").append(
86 jc.getName().getExternalName().replace('.', '_')
87 ).append('_').append(findMethodName(m));
90 List<Parameter> args = m.getParameters();
91 for (int index = 0, i = 0; i < args.size(); i++) {
93 out.append("arg").append(String.valueOf(index));
95 final String desc = args.get(i).getDescriptor();
96 if ("D".equals(desc) || "J".equals(desc)) {
102 out.append(") {").append("\n");
103 final Code code = m.getCode();
104 int len = code.getMaxLocals();
105 for (int index = args.size(), i = args.size(); i < len; i++) {
107 out.append("arg").append(String.valueOf(i)).append(";\n");
109 out.append(" var stack = new Array(");
110 out.append(Integer.toString(code.getMaxStack()));
112 produceCode(code.getByteCodes());
116 private void generateMethodReference(Method m) throws IOException {
117 final String name = findMethodName(m);
118 out.append("\n this.").append(name).append(" = ")
119 .append(jc.getName().getExternalName().replace('.', '_'))
120 .append('_').append(name).append(";");
123 private void generateInstanceMethod(Method m) throws IOException {
124 out.append("\nfunction ").append(
125 jc.getName().getExternalName().replace('.', '_')
126 ).append('_').append(findMethodName(m));
129 List<Parameter> args = m.getParameters();
130 for (int index = 1, i = 0; i < args.size(); i++) {
132 out.append("arg").append(String.valueOf(index));
133 final String desc = args.get(i).getDescriptor();
134 if ("D".equals(desc) || "J".equals(desc)) {
140 out.append(") {").append("\n");
141 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 + 1)).append(";\n");
147 out.append(";\n var stack = new Array(");
148 out.append(Integer.toString(code.getMaxStack()));
150 produceCode(code.getByteCodes());
154 private void produceCode(byte[] byteCodes) throws IOException {
155 out.append("\n var gt = 0;\n for(;;) switch(gt) {\n");
156 for (int i = 0; i < byteCodes.length; i++) {
158 out.append(" case " + i).append(": ");
159 final int c = (byteCodes[i] + 256) % 256;
166 out.append("stack.push(arg0);");
173 out.append("stack.push(arg1);");
180 out.append("stack.push(arg2);");
187 out.append("stack.push(arg3);");
194 final int indx = (byteCodes[++i] + 256) % 256;
195 out.append("stack.push(arg").append(indx + ");");
203 out.append("arg0 = stack.pop();");
210 out.append("arg1 = stack.pop();");
217 out.append("arg2 = stack.pop();");
224 out.append("arg3 = stack.pop();");
230 out.append("stack.push(stack.pop() + stack.pop());");
236 out.append("{ var tmp = stack.pop(); stack.push(stack.pop() - tmp); }");
242 out.append("stack.push(stack.pop() * stack.pop());");
246 out.append("{ var tmp = stack.pop(); stack.push(Math.floor(stack.pop() / tmp)); }");
250 out.append("{ var tmp = stack.pop(); stack.push(stack.pop() / tmp); }");
254 out.append("stack.push(stack.pop() & stack.pop());");
258 out.append("stack.push(stack.pop() | stack.pop());");
262 out.append("stack.push(stack.pop() ^ stack.pop());");
265 final int varIndx = (byteCodes[++i] + 256) % 256;
266 final int incrBy = (byteCodes[++i] + 256) % 256;
268 out.append("arg" + varIndx).append("++;");
270 out.append("arg" + varIndx).append(" += " + incrBy).append(";");
275 out.append("return;");
282 out.append("return stack.pop();");
293 out.append("/* number conversion */");
299 out.append("stack.push(Math.floor(stack.pop()));");
304 out.append("/* number conversion */");
310 out.append("stack.push(0);");
316 out.append("stack.push(1);");
320 out.append("stack.push(2);");
323 out.append("stack.push(3);");
326 out.append("stack.push(4);");
329 out.append("stack.push(5);");
333 int indx = readIntArg(byteCodes, i);
334 CPEntry entry = jc.getConstantPool().get(indx);
336 out.append("stack.push(" + entry.getValue() + ");");
340 i = generateIf(byteCodes, i, "==");
344 int indx = i + readIntArg(byteCodes, i);
345 out.append("if (stack.pop() == 0) { gt = " + indx);
346 out.append("; continue; }");
351 i = generateIf(byteCodes, i, "!=");
354 i = generateIf(byteCodes, i, ">");
357 i = generateIf(byteCodes, i, ">=");
360 i = generateIf(byteCodes, i, "<");
363 i = generateIf(byteCodes, i, "<=");
366 int indx = i + readIntArg(byteCodes, i);
367 out.append("gt = " + indx).append("; continue;");
371 case bc_invokevirtual:
372 i = invokeVirtualMethod(byteCodes, i);
374 case bc_invokespecial:
375 i = invokeStaticMethod(byteCodes, i, false);
377 case bc_invokestatic:
378 i = invokeStaticMethod(byteCodes, i, true);
381 int indx = readIntArg(byteCodes, i);
382 CPClassInfo ci = jc.getConstantPool().getClass(indx);
383 out.append("stack.push(");
384 out.append("new ").append(ci.getClassName().getExternalName().replace('.','_'));
390 out.append("stack.push(stack[stack.length - 1]);");
393 out.append("stack.push(" + byteCodes[++i] + ");");
396 int indx = readIntArg(byteCodes, i);
397 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
398 out.append(" stack.push(stack.pop().").append(fi.getFieldName()).append(");");
403 int indx = readIntArg(byteCodes, i);
404 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
405 out.append("stack.push(").append(fi.getClassName().getExternalName().replace('.', '_'));
406 out.append('_').append(fi.getFieldName()).append(");");
411 int indx = readIntArg(byteCodes, i);
412 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
413 out.append(fi.getClassName().getExternalName().replace('.', '_'));
414 out.append('_').append(fi.getFieldName()).append(" = stack.pop();");
419 int indx = readIntArg(byteCodes, i);
420 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
421 out.append("{ var v = stack.pop(); stack.pop().")
422 .append(fi.getFieldName()).append(" = v; }");
429 for (int j = prev; j <= i; j++) {
431 final int cc = (byteCodes[j] + 256) % 256;
432 out.append(Integer.toString(cc));
439 private int generateIf(byte[] byteCodes, int i, final String test) throws IOException {
440 int indx = i + readIntArg(byteCodes, i);
441 out.append("if (stack.pop() ").append(test).append(" stack.pop()) { gt = " + indx);
442 out.append("; continue; }");
446 private int readIntArg(byte[] byteCodes, int offsetInstruction) {
447 final int indxHi = byteCodes[offsetInstruction + 1] << 8;
448 final int indxLo = byteCodes[offsetInstruction + 2];
449 return (indxHi & 0xffffff00) | (indxLo & 0xff);
452 private static int countArgs(String descriptor, boolean[] hasReturnType, StringBuilder sig) {
455 Boolean count = null;
456 int firstPos = sig.length();
457 while (i < descriptor.length()) {
458 char ch = descriptor.charAt(i++);
478 hasReturnType[0] = true;
479 sig.insert(firstPos, ch);
484 hasReturnType[0] = false;
485 sig.insert(firstPos, 'V');
488 i = descriptor.indexOf(';', i);
492 hasReturnType[0] = true;
499 break; // invalid character
505 private void generateStaticField(Variable v) throws IOException {
507 .append(jc.getName().getExternalName().replace('.', '_'))
508 .append('_').append(v.getName()).append(" = 0;");
511 private String findMethodName(Method m) {
512 StringBuilder out = new StringBuilder();
513 if ("<init>".equals(m.getName())) { // NOI18N
514 out.append("consV"); // NOI18N
516 out.append(m.getName());
517 out.append(m.getReturnType());
519 List<Parameter> args = m.getParameters();
520 for (Parameter t : args) {
521 out.append(t.getDescriptor());
523 return out.toString();
526 private String findMethodName(CPMethodInfo mi, int[] cnt, boolean[] hasReturn) {
527 StringBuilder name = new StringBuilder();
528 if ("<init>".equals(mi.getName())) { // NOI18N
529 name.append("cons"); // NOI18N
531 name.append(mi.getName());
533 cnt[0] = countArgs(mi.getDescriptor(), hasReturn, name);
534 return name.toString();
537 private int invokeStaticMethod(byte[] byteCodes, int i, boolean isStatic)
539 int methodIndex = readIntArg(byteCodes, i);
540 CPMethodInfo mi = (CPMethodInfo) jc.getConstantPool().get(methodIndex);
541 boolean[] hasReturn = { false };
543 String mn = findMethodName(mi, cnt, hasReturn);
545 for (int j = cnt[0] - 1; j >= 0; j--) {
546 out.append("var v" + j).append(" = stack.pop(); ");
550 out.append("stack.push(");
552 out.append(mi.getClassName().getInternalName().replace('/', '_'));
558 out.append("stack.pop()");
561 for (int j = 0; j < cnt[0]; j++) {
574 private int invokeVirtualMethod(byte[] byteCodes, int i)
576 int methodIndex = readIntArg(byteCodes, i);
577 CPMethodInfo mi = (CPMethodInfo) jc.getConstantPool().get(methodIndex);
578 boolean[] hasReturn = { false };
580 String mn = findMethodName(mi, cnt, hasReturn);
582 for (int j = cnt[0] - 1; j >= 0; j--) {
583 out.append("var v" + j).append(" = stack.pop(); ");
585 out.append("var self = stack.pop(); ");
587 out.append("stack.push(");
593 for (int j = 0; j < cnt[0]; j++) {