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()) {
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 generateInstanceMethod(Method m) throws IOException {
117 out.append("\nfunction ").append(
118 jc.getName().getExternalName().replace('.', '_')
119 ).append('_').append(findMethodName(m));
122 List<Parameter> args = m.getParameters();
123 for (int index = 1, i = 0; i < args.size(); i++) {
125 out.append("arg").append(String.valueOf(index));
126 final String desc = args.get(i).getDescriptor();
127 if ("D".equals(desc) || "J".equals(desc)) {
133 out.append(") {").append("\n");
134 final Code code = m.getCode();
135 int len = code.getMaxLocals();
136 for (int index = args.size(), i = args.size(); i < len; i++) {
138 out.append("arg").append(String.valueOf(i + 1)).append(";\n");
140 out.append(";\n var stack = new Array(");
141 out.append(Integer.toString(code.getMaxStack()));
143 produceCode(code.getByteCodes());
147 private void produceCode(byte[] byteCodes) throws IOException {
148 out.append("\n var gt = 0;\n for(;;) switch(gt) {\n");
149 for (int i = 0; i < byteCodes.length; i++) {
151 out.append(" case " + i).append(": ");
152 final int c = (byteCodes[i] + 256) % 256;
159 out.append("stack.push(arg0);");
166 out.append("stack.push(arg1);");
173 out.append("stack.push(arg2);");
180 out.append("stack.push(arg3);");
187 final int indx = (byteCodes[++i] + 256) % 256;
188 out.append("stack.push(arg").append(indx + ");");
196 out.append("arg0 = stack.pop();");
203 out.append("arg1 = stack.pop();");
210 out.append("arg2 = stack.pop();");
217 out.append("arg3 = stack.pop();");
223 out.append("stack.push(stack.pop() + stack.pop());");
229 out.append("{ var tmp = stack.pop(); stack.push(stack.pop() - tmp); }");
235 out.append("stack.push(stack.pop() * stack.pop());");
239 out.append("{ var tmp = stack.pop(); stack.push(Math.floor(stack.pop() / tmp)); }");
243 out.append("{ var tmp = stack.pop(); stack.push(stack.pop() / tmp); }");
247 out.append("stack.push(stack.pop() & stack.pop());");
251 out.append("stack.push(stack.pop() | stack.pop());");
255 out.append("stack.push(stack.pop() ^ stack.pop());");
258 final int varIndx = (byteCodes[++i] + 256) % 256;
259 final int incrBy = (byteCodes[++i] + 256) % 256;
261 out.append("arg" + varIndx).append("++;");
263 out.append("arg" + varIndx).append(" += " + incrBy).append(";");
268 out.append("return;");
275 out.append("return stack.pop();");
286 out.append("/* number conversion */");
292 out.append("stack.push(Math.floor(stack.pop()));");
297 out.append("/* number conversion */");
303 out.append("stack.push(0);");
309 out.append("stack.push(1);");
313 out.append("stack.push(2);");
316 out.append("stack.push(3);");
319 out.append("stack.push(4);");
322 out.append("stack.push(5);");
326 int indx = readIntArg(byteCodes, i);
327 CPEntry entry = jc.getConstantPool().get(indx);
329 out.append("stack.push(" + entry.getValue() + ");");
333 i = generateIf(byteCodes, i, "==");
337 int indx = i + readIntArg(byteCodes, i);
338 out.append("if (stack.pop() == 0) { gt = " + indx);
339 out.append("; continue; }");
344 i = generateIf(byteCodes, i, "!=");
347 i = generateIf(byteCodes, i, ">");
350 i = generateIf(byteCodes, i, ">=");
353 i = generateIf(byteCodes, i, "<");
356 i = generateIf(byteCodes, i, "<=");
359 int indx = i + readIntArg(byteCodes, i);
360 out.append("gt = " + indx).append("; continue;");
364 case bc_invokespecial:
365 i = invokeStaticMethod(byteCodes, i, false);
367 case bc_invokestatic:
368 i = invokeStaticMethod(byteCodes, i, true);
371 int indx = readIntArg(byteCodes, i);
372 CPClassInfo ci = jc.getConstantPool().getClass(indx);
373 out.append("stack.push(");
374 out.append("new ").append(ci.getClassName().getExternalName().replace('.','_'));
380 out.append("stack.push(stack[stack.length - 1]);");
383 out.append("stack.push(" + byteCodes[++i] + ");");
386 int indx = readIntArg(byteCodes, i);
387 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
388 out.append(" stack.push(stack.pop().").append(fi.getFieldName()).append(");");
393 int indx = readIntArg(byteCodes, i);
394 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
395 out.append("stack.push(").append(fi.getClassName().getExternalName().replace('.', '_'));
396 out.append('_').append(fi.getFieldName()).append(");");
401 int indx = readIntArg(byteCodes, i);
402 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
403 out.append(fi.getClassName().getExternalName().replace('.', '_'));
404 out.append('_').append(fi.getFieldName()).append(" = stack.pop();");
409 int indx = readIntArg(byteCodes, i);
410 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
411 out.append("{ var v = stack.pop(); stack.pop().")
412 .append(fi.getFieldName()).append(" = v; }");
419 for (int j = prev; j <= i; j++) {
421 final int cc = (byteCodes[j] + 256) % 256;
422 out.append(Integer.toString(cc));
429 private int generateIf(byte[] byteCodes, int i, final String test) throws IOException {
430 int indx = i + readIntArg(byteCodes, i);
431 out.append("if (stack.pop() ").append(test).append(" stack.pop()) { gt = " + indx);
432 out.append("; continue; }");
436 private int readIntArg(byte[] byteCodes, int offsetInstruction) {
437 final int indxHi = byteCodes[offsetInstruction + 1] << 8;
438 final int indxLo = byteCodes[offsetInstruction + 2];
439 return (indxHi & 0xffffff00) | (indxLo & 0xff);
442 private static int countArgs(String descriptor, boolean[] hasReturnType, StringBuilder sig) {
445 Boolean count = null;
446 int firstPos = sig.length();
447 while (i < descriptor.length()) {
448 char ch = descriptor.charAt(i++);
468 hasReturnType[0] = true;
469 sig.insert(firstPos, ch);
474 hasReturnType[0] = false;
475 sig.insert(firstPos, 'V');
478 i = descriptor.indexOf(';', i);
482 hasReturnType[0] = true;
489 break; // invalid character
495 private void generateStaticField(Variable v) throws IOException {
497 .append(jc.getName().getExternalName().replace('.', '_'))
498 .append('_').append(v.getName()).append(" = 0;");
501 private String findMethodName(Method m) {
502 StringBuilder out = new StringBuilder();
503 if ("<init>".equals(m.getName())) { // NOI18N
504 out.append("consV"); // NOI18N
506 out.append(m.getName());
507 out.append(m.getReturnType());
509 List<Parameter> args = m.getParameters();
510 for (Parameter t : args) {
511 out.append(t.getDescriptor());
513 return out.toString();
516 private String findMethodName(CPMethodInfo mi, int[] cnt, boolean[] hasReturn) {
517 StringBuilder name = new StringBuilder();
518 if ("<init>".equals(mi.getName())) { // NOI18N
519 name.append("cons"); // NOI18N
521 name.append(mi.getName());
523 cnt[0] = countArgs(mi.getDescriptor(), hasReturn, name);
524 return name.toString();
527 private int invokeStaticMethod(byte[] byteCodes, int i, boolean isStatic)
529 int methodIndex = readIntArg(byteCodes, i);
530 CPMethodInfo mi = (CPMethodInfo) jc.getConstantPool().get(methodIndex);
531 boolean[] hasReturn = { false };
533 String mn = findMethodName(mi, cnt, hasReturn);
535 for (int j = cnt[0] - 1; j >= 0; j--) {
536 out.append("var v" + j).append(" = stack.pop(); ");
540 out.append("stack.push(");
542 out.append(mi.getClassName().getInternalName().replace('/', '_'));
548 out.append("stack.pop()");
551 for (int j = 0; j < cnt[0]; j++) {