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;
33 import org.netbeans.modules.classfile.Variable;
35 /** Translator of the code inside class files to JavaScript.
37 * @author Jaroslav Tulach <jtulach@netbeans.org>
39 public final class ByteCodeToJavaScript {
40 private final ClassFile jc;
41 private final Appendable out;
43 private ByteCodeToJavaScript(ClassFile jc, Appendable out) {
48 /** Converts a given class file to a JavaScript version.
49 * @param fileName the name of the file we are reading
50 * @param classFile input stream with code of the .class file
51 * @param out a {@link StringBuilder} or similar to generate the output to
52 * @throws IOException if something goes wrong during read or write or translating
54 public static void compile(String fileName, InputStream classFile, Appendable out) throws IOException {
55 ClassFile jc = new ClassFile(classFile, true);
56 ByteCodeToJavaScript compiler = new ByteCodeToJavaScript(jc, out);
57 for (Method m : jc.getMethods()) {
59 compiler.generateStaticMethod(m);
62 for (Variable v : jc.getVariables()) {
64 compiler.generateStaticField(v);
68 private void generateStaticMethod(Method m) throws IOException {
69 out.append("\nfunction ").append(
70 jc.getName().getExternalName().replace('.', '_')
74 out.append(m.getReturnType());
75 List<Parameter> args = m.getParameters();
76 for (Parameter t : args) {
77 out.append(t.getDescriptor());
81 for (int index = 0, i = 0; i < args.size(); i++) {
83 out.append("arg").append(String.valueOf(index));
85 final String desc = args.get(i).getDescriptor();
86 if ("D".equals(desc) || "J".equals(desc)) {
92 out.append(") {").append("\n");
93 final Code code = m.getCode();
94 int len = code.getMaxLocals();
95 for (int index = args.size(), i = args.size(); i < len; i++) {
97 out.append("arg").append(String.valueOf(i)).append(";\n");
99 out.append(";\n var stack = new Array(");
100 out.append(Integer.toString(code.getMaxStack()));
102 produceCode(code.getByteCodes());
106 private void produceCode(byte[] byteCodes) throws IOException {
107 out.append("\nvar gt = 0;\nfor(;;) switch(gt) {\n");
108 for (int i = 0; i < byteCodes.length; i++) {
110 out.append(" case " + i).append(": ");
111 final int c = (byteCodes[i] + 256) % 256;
118 out.append("stack.push(arg0);");
125 out.append("stack.push(arg1);");
132 out.append("stack.push(arg2);");
139 out.append("stack.push(arg3);");
146 final int indx = (byteCodes[++i] + 256) % 256;
147 out.append("stack.push(arg").append(indx + ");");
155 out.append("arg0 = stack.pop();");
162 out.append("arg1 = stack.pop();");
169 out.append("arg2 = stack.pop();");
176 out.append("arg3 = stack.pop();");
182 out.append("stack.push(stack.pop() + stack.pop());");
188 out.append("{ var tmp = stack.pop(); stack.push(stack.pop() - tmp); }");
194 out.append("stack.push(stack.pop() * stack.pop());");
198 out.append("{ var tmp = stack.pop(); stack.push(Math.floor(stack.pop() / tmp)); }");
202 out.append("{ var tmp = stack.pop(); stack.push(stack.pop() / tmp); }");
206 out.append("stack.push(stack.pop() & stack.pop());");
210 out.append("stack.push(stack.pop() | stack.pop());");
214 out.append("stack.push(stack.pop() ^ stack.pop());");
217 final int varIndx = (byteCodes[++i] + 256) % 256;
218 final int incrBy = (byteCodes[++i] + 256) % 256;
220 out.append("arg" + varIndx).append("++;");
222 out.append("arg" + varIndx).append(" += " + incrBy).append(";");
230 out.append("return stack.pop();");
241 out.append("/* number conversion */");
247 out.append("stack.push(Math.floor(stack.pop()));");
252 out.append("/* number conversion */");
258 out.append("stack.push(0);");
264 out.append("stack.push(1);");
268 out.append("stack.push(2);");
271 out.append("stack.push(3);");
274 out.append("stack.push(4);");
277 out.append("stack.push(5);");
281 int indx = readIntArg(byteCodes, i);
282 CPEntry entry = jc.getConstantPool().get(indx);
284 out.append("stack.push(" + entry.getValue() + ");");
288 i = generateIf(byteCodes, i, "==");
292 int indx = i + readIntArg(byteCodes, i);
293 out.append("if (stack.pop() == 0) { gt = " + indx);
294 out.append("; continue; }");
299 i = generateIf(byteCodes, i, "!=");
302 i = generateIf(byteCodes, i, ">");
305 i = generateIf(byteCodes, i, ">=");
308 i = generateIf(byteCodes, i, "<");
311 i = generateIf(byteCodes, i, "<=");
314 int indx = i + readIntArg(byteCodes, i);
315 out.append("gt = " + indx).append("; continue;");
319 case bc_invokestatic: {
320 int methodIndex = readIntArg(byteCodes, i);
321 CPMethodInfo mi = (CPMethodInfo) jc.getConstantPool().get(methodIndex);
322 boolean[] hasReturn = { false };
323 StringBuilder signature = new StringBuilder();
324 int cnt = countArgs(mi.getDescriptor(), hasReturn, signature);
327 out.append("stack.push(");
329 out.append(mi.getClassName().getInternalName().replace('/', '_'));
331 out.append(mi.getName());
332 out.append(signature.toString());
335 for (int j = 0; j < cnt; j++) {
337 out.append("stack.pop()");
349 int indx = readIntArg(byteCodes, i);
350 CPClassInfo ci = jc.getConstantPool().getClass(indx);
351 out.append("stack.push(");
352 out.append("new ").append(ci.getClassName().getExternalName().replace('.','_'));
358 out.append("stack.push(stack[stack.length - 1]);");
361 out.append("stack.push(" + byteCodes[++i] + ");");
363 case bc_invokevirtual:
364 case bc_invokespecial: {
365 int indx = readIntArg(byteCodes, i);
366 CPMethodInfo mi = (CPMethodInfo) jc.getConstantPool().get(indx);
367 out.append("{ var tmp = stack.pop(); tmp." + mi.getMethodName() + "(); }");
372 int indx = readIntArg(byteCodes, i);
373 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
374 out.append(" stack.push(stack.pop().").append(fi.getFieldName()).append(");");
379 int indx = readIntArg(byteCodes, i);
380 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
381 out.append("stack.push(").append(fi.getClassName().getExternalName().replace('.', '_'));
382 out.append('_').append(fi.getFieldName()).append(");");
387 int indx = readIntArg(byteCodes, i);
388 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
389 out.append(fi.getClassName().getExternalName().replace('.', '_'));
390 out.append('_').append(fi.getFieldName()).append(" = stack.pop();");
397 for (int j = prev; j <= i; j++) {
399 final int cc = (byteCodes[j] + 256) % 256;
400 out.append(Integer.toString(cc));
407 private int generateIf(byte[] byteCodes, int i, final String test) throws IOException {
408 int indx = i + readIntArg(byteCodes, i);
409 out.append("if (stack.pop() ").append(test).append(" stack.pop()) { gt = " + indx);
410 out.append("; continue; }");
414 private int readIntArg(byte[] byteCodes, int offsetInstruction) {
415 final int indxHi = byteCodes[offsetInstruction + 1] << 8;
416 final int indxLo = byteCodes[offsetInstruction + 2];
417 return (indxHi & 0xffffff00) | (indxLo & 0xff);
420 private static int countArgs(String descriptor, boolean[] hasReturnType, StringBuilder sig) {
423 Boolean count = null;
424 while (i < descriptor.length()) {
425 char ch = descriptor.charAt(i++);
445 hasReturnType[0] = true;
451 hasReturnType[0] = false;
455 i = descriptor.indexOf(';', i);
459 hasReturnType[0] = true;
466 break; // invalid character
472 private void generateStaticField(Variable v) throws IOException {
474 .append(jc.getName().getExternalName().replace('.', '_'))
475 .append('_').append(v.getName()).append(" = 0;");