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.CPLongInfo;
28 import org.netbeans.modules.classfile.CPMethodInfo;
29 import org.netbeans.modules.classfile.ClassFile;
30 import org.netbeans.modules.classfile.Code;
31 import org.netbeans.modules.classfile.Method;
32 import org.netbeans.modules.classfile.Parameter;
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);
62 private void generateStaticMethod(Method m) throws IOException {
63 out.append("\nfunction ").append(
64 jc.getName().getExternalName().replace('.', '_')
68 out.append(m.getReturnType());
69 List<Parameter> args = m.getParameters();
70 for (Parameter t : args) {
71 out.append(t.getDescriptor());
75 for (int index = 0, i = 0; i < args.size(); i++) {
77 out.append("arg").append(String.valueOf(index));
79 final String desc = args.get(i).getDescriptor();
80 if ("D".equals(desc) || "J".equals(desc)) {
86 out.append(") {").append("\n");
87 final Code code = m.getCode();
88 int len = code.getMaxLocals();
89 for (int index = args.size(), i = args.size(); i < len; i++) {
91 out.append("arg").append(String.valueOf(i)).append(";\n");
93 out.append(";\n var stack = new Array(");
94 out.append(Integer.toString(code.getMaxStack()));
96 produceCode(code.getByteCodes());
100 private void produceCode(byte[] byteCodes) throws IOException {
101 out.append("\nvar gt = 0;\nfor(;;) switch(gt) {\n");
102 for (int i = 0; i < byteCodes.length; i++) {
104 out.append(" case " + i).append(": ");
105 final int c = (byteCodes[i] + 256) % 256;
112 out.append("stack.push(arg0);");
119 out.append("stack.push(arg1);");
126 out.append("stack.push(arg2);");
133 out.append("stack.push(arg3);");
140 final int indx = (byteCodes[++i] + 256) % 256;
141 out.append("stack.push(arg").append(indx + ");");
149 out.append("arg0 = stack.pop();");
156 out.append("arg1 = stack.pop();");
163 out.append("arg2 = stack.pop();");
170 out.append("arg3 = stack.pop();");
176 out.append("stack.push(stack.pop() + stack.pop());");
182 out.append("{ var tmp = stack.pop(); stack.push(stack.pop() - tmp); }");
188 out.append("stack.push(stack.pop() * stack.pop());");
192 out.append("{ var tmp = stack.pop(); stack.push(Math.floor(stack.pop() / tmp)); }");
196 out.append("{ var tmp = stack.pop(); stack.push(stack.pop() / tmp); }");
200 out.append("stack.push(stack.pop() & stack.pop());");
204 out.append("stack.push(stack.pop() | stack.pop());");
208 out.append("stack.push(stack.pop() ^ stack.pop());");
211 final int varIndx = (byteCodes[++i] + 256) % 256;
212 final int incrBy = (byteCodes[++i] + 256) % 256;
214 out.append("arg" + varIndx).append("++;");
216 out.append("arg" + varIndx).append(" += " + incrBy).append(";");
224 out.append("return stack.pop();");
235 out.append("/* number conversion */");
241 out.append("stack.push(Math.floor(stack.pop()));");
246 out.append("/* number conversion */");
252 out.append("stack.push(0);");
258 out.append("stack.push(1);");
262 out.append("stack.push(2);");
265 out.append("stack.push(3);");
268 out.append("stack.push(4);");
271 out.append("stack.push(5);");
275 int indx = readIntArg(byteCodes, i);
276 CPEntry entry = jc.getConstantPool().get(indx);
278 out.append("stack.push(" + entry.getValue() + ");");
282 i = generateIf(byteCodes, i, "==");
286 int indx = i + readIntArg(byteCodes, i);
287 out.append("if (stack.pop() == 0) { gt = " + indx);
288 out.append("; continue; }");
293 i = generateIf(byteCodes, i, "!=");
296 i = generateIf(byteCodes, i, ">");
299 i = generateIf(byteCodes, i, ">=");
302 i = generateIf(byteCodes, i, "<");
305 i = generateIf(byteCodes, i, "<=");
308 int indx = i + readIntArg(byteCodes, i);
309 out.append("gt = " + indx).append("; continue;");
313 case bc_invokestatic: {
314 int methodIndex = readIntArg(byteCodes, i);
315 CPMethodInfo mi = (CPMethodInfo) jc.getConstantPool().get(methodIndex);
316 boolean[] hasReturn = { false };
317 StringBuilder signature = new StringBuilder();
318 int cnt = countArgs(mi.getDescriptor(), hasReturn, signature);
321 out.append("stack.push(");
323 out.append(mi.getClassName().getInternalName().replace('/', '_'));
325 out.append(mi.getName());
326 out.append(signature.toString());
329 for (int j = 0; j < cnt; j++) {
331 out.append("stack.pop()");
343 int indx = readIntArg(byteCodes, i);
344 CPClassInfo ci = jc.getConstantPool().getClass(indx);
345 out.append("stack.push(");
346 out.append("new ").append(ci.getClassName().getExternalName().replace('.','_'));
352 out.append("stack.push(stack[stack.length - 1]);");
355 out.append("stack.push(" + byteCodes[++i] + ");");
357 case bc_invokevirtual:
358 case bc_invokespecial: {
359 int indx = readIntArg(byteCodes, i);
360 CPMethodInfo mi = (CPMethodInfo) jc.getConstantPool().get(indx);
361 out.append("{ var tmp = stack.pop(); tmp." + mi.getMethodName() + "(); }");
366 int indx = readIntArg(byteCodes, i);
367 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
368 out.append(" stack.push(stack.pop().").append(fi.getFieldName()).append(");");
375 for (int j = prev; j <= i; j++) {
377 final int cc = (byteCodes[j] + 256) % 256;
378 out.append(Integer.toString(cc));
385 private int generateIf(byte[] byteCodes, int i, final String test) throws IOException {
386 int indx = i + readIntArg(byteCodes, i);
387 out.append("if (stack.pop() ").append(test).append(" stack.pop()) { gt = " + indx);
388 out.append("; continue; }");
392 private int readIntArg(byte[] byteCodes, int offsetInstruction) {
393 final int indxHi = byteCodes[offsetInstruction + 1] << 8;
394 final int indxLo = byteCodes[offsetInstruction + 2];
395 return (indxHi & 0xffffff00) | (indxLo & 0xff);
398 private static int countArgs(String descriptor, boolean[] hasReturnType, StringBuilder sig) {
401 Boolean count = null;
402 while (i < descriptor.length()) {
403 char ch = descriptor.charAt(i++);
423 hasReturnType[0] = true;
429 hasReturnType[0] = false;
433 i = descriptor.indexOf(';', i);
437 hasReturnType[0] = true;
444 break; // invalid character