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.ClassName;
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);
61 compiler.generateInstanceMethod(m);
64 for (Variable v : jc.getVariables()) {
66 compiler.generateStaticField(v);
69 out.append("function java_lang_Object(){}\n"); // XXX temporary
70 out.append("function java_lang_Object_consV(self){}\n"); // XXX temporary
72 final String className = jc.getName().getExternalName().replace('.', '_');
73 out.append("\nfunction ").append(className);
75 for (Method m : jc.getMethods()) {
77 compiler.generateMethodReference(m);
80 for (Variable v : jc.getVariables()) {
82 out.append("\n this." + v.getName() + " = 0;");
86 ClassName sc = jc.getSuperClass();
88 out.append("\n ").append(className)
89 .append(".prototype = new ").append(sc.getExternalName().replace('.', '_'));
92 private void generateStaticMethod(Method m) throws IOException {
93 out.append("\nfunction ").append(
94 jc.getName().getExternalName().replace('.', '_')
95 ).append('_').append(findMethodName(m));
98 List<Parameter> args = m.getParameters();
99 for (int index = 0, i = 0; i < args.size(); i++) {
101 out.append("arg").append(String.valueOf(index));
103 final String desc = args.get(i).getDescriptor();
104 if ("D".equals(desc) || "J".equals(desc)) {
110 out.append(") {").append("\n");
111 final Code code = m.getCode();
112 int len = code.getMaxLocals();
113 for (int index = args.size(), i = args.size(); i < len; i++) {
115 out.append("arg").append(String.valueOf(i)).append(";\n");
117 out.append(" var stack = new Array(");
118 out.append(Integer.toString(code.getMaxStack()));
120 produceCode(code.getByteCodes());
124 private void generateMethodReference(Method m) throws IOException {
125 final String name = findMethodName(m);
126 out.append("\n this.").append(name).append(" = ")
127 .append(jc.getName().getExternalName().replace('.', '_'))
128 .append('_').append(name).append(";");
131 private void generateInstanceMethod(Method m) throws IOException {
132 out.append("\nfunction ").append(
133 jc.getName().getExternalName().replace('.', '_')
134 ).append('_').append(findMethodName(m));
137 List<Parameter> args = m.getParameters();
138 for (int index = 1, i = 0; i < args.size(); i++) {
140 out.append("arg").append(String.valueOf(index));
141 final String desc = args.get(i).getDescriptor();
142 if ("D".equals(desc) || "J".equals(desc)) {
148 out.append(") {").append("\n");
149 final Code code = m.getCode();
150 int len = code.getMaxLocals();
151 for (int index = args.size(), i = args.size(); i < len; i++) {
153 out.append("arg").append(String.valueOf(i + 1)).append(";\n");
155 out.append(";\n var stack = new Array(");
156 out.append(Integer.toString(code.getMaxStack()));
158 produceCode(code.getByteCodes());
162 private void produceCode(byte[] byteCodes) throws IOException {
163 out.append("\n var gt = 0;\n for(;;) switch(gt) {\n");
164 for (int i = 0; i < byteCodes.length; i++) {
166 out.append(" case " + i).append(": ");
167 final int c = (byteCodes[i] + 256) % 256;
174 out.append("stack.push(arg0);");
181 out.append("stack.push(arg1);");
188 out.append("stack.push(arg2);");
195 out.append("stack.push(arg3);");
202 final int indx = (byteCodes[++i] + 256) % 256;
203 out.append("stack.push(arg").append(indx + ");");
211 out.append("arg0 = stack.pop();");
218 out.append("arg1 = stack.pop();");
225 out.append("arg2 = stack.pop();");
232 out.append("arg3 = stack.pop();");
238 out.append("stack.push(stack.pop() + stack.pop());");
244 out.append("{ var tmp = stack.pop(); stack.push(stack.pop() - tmp); }");
250 out.append("stack.push(stack.pop() * stack.pop());");
254 out.append("{ var tmp = stack.pop(); stack.push(Math.floor(stack.pop() / tmp)); }");
258 out.append("{ var tmp = stack.pop(); stack.push(stack.pop() / tmp); }");
262 out.append("stack.push(stack.pop() & stack.pop());");
266 out.append("stack.push(stack.pop() | stack.pop());");
270 out.append("stack.push(stack.pop() ^ stack.pop());");
273 final int varIndx = (byteCodes[++i] + 256) % 256;
274 final int incrBy = (byteCodes[++i] + 256) % 256;
276 out.append("arg" + varIndx).append("++;");
278 out.append("arg" + varIndx).append(" += " + incrBy).append(";");
283 out.append("return;");
290 out.append("return stack.pop();");
301 out.append("/* number conversion */");
307 out.append("stack.push(Math.floor(stack.pop()));");
312 out.append("/* number conversion */");
318 out.append("stack.push(0);");
324 out.append("stack.push(1);");
328 out.append("stack.push(2);");
331 out.append("stack.push(3);");
334 out.append("stack.push(4);");
337 out.append("stack.push(5);");
341 int indx = readIntArg(byteCodes, i);
342 CPEntry entry = jc.getConstantPool().get(indx);
344 out.append("stack.push(" + entry.getValue() + ");");
348 i = generateIf(byteCodes, i, "==");
352 int indx = i + readIntArg(byteCodes, i);
353 out.append("if (stack.pop() == 0) { gt = " + indx);
354 out.append("; continue; }");
359 i = generateIf(byteCodes, i, "!=");
362 i = generateIf(byteCodes, i, ">");
365 i = generateIf(byteCodes, i, ">=");
368 i = generateIf(byteCodes, i, "<");
371 i = generateIf(byteCodes, i, "<=");
374 int indx = i + readIntArg(byteCodes, i);
375 out.append("gt = " + indx).append("; continue;");
379 case bc_invokevirtual:
380 i = invokeVirtualMethod(byteCodes, i);
382 case bc_invokespecial:
383 i = invokeStaticMethod(byteCodes, i, false);
385 case bc_invokestatic:
386 i = invokeStaticMethod(byteCodes, i, true);
389 int indx = readIntArg(byteCodes, i);
390 CPClassInfo ci = jc.getConstantPool().getClass(indx);
391 out.append("stack.push(");
392 out.append("new ").append(ci.getClassName().getExternalName().replace('.','_'));
398 out.append("stack.push(stack[stack.length - 1]);");
401 out.append("stack.push(" + byteCodes[++i] + ");");
404 int indx = readIntArg(byteCodes, i);
405 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
406 out.append(" stack.push(stack.pop().").append(fi.getFieldName()).append(");");
411 int indx = readIntArg(byteCodes, i);
412 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
413 out.append("stack.push(").append(fi.getClassName().getExternalName().replace('.', '_'));
414 out.append('_').append(fi.getFieldName()).append(");");
419 int indx = readIntArg(byteCodes, i);
420 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
421 out.append(fi.getClassName().getExternalName().replace('.', '_'));
422 out.append('_').append(fi.getFieldName()).append(" = stack.pop();");
427 int indx = readIntArg(byteCodes, i);
428 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
429 out.append("{ var v = stack.pop(); stack.pop().")
430 .append(fi.getFieldName()).append(" = v; }");
437 for (int j = prev; j <= i; j++) {
439 final int cc = (byteCodes[j] + 256) % 256;
440 out.append(Integer.toString(cc));
447 private int generateIf(byte[] byteCodes, int i, final String test) throws IOException {
448 int indx = i + readIntArg(byteCodes, i);
449 out.append("if (stack.pop() ").append(test).append(" stack.pop()) { gt = " + indx);
450 out.append("; continue; }");
454 private int readIntArg(byte[] byteCodes, int offsetInstruction) {
455 final int indxHi = byteCodes[offsetInstruction + 1] << 8;
456 final int indxLo = byteCodes[offsetInstruction + 2];
457 return (indxHi & 0xffffff00) | (indxLo & 0xff);
460 private static int countArgs(String descriptor, boolean[] hasReturnType, StringBuilder sig) {
463 Boolean count = null;
464 int firstPos = sig.length();
465 while (i < descriptor.length()) {
466 char ch = descriptor.charAt(i++);
486 hasReturnType[0] = true;
487 sig.insert(firstPos, ch);
492 hasReturnType[0] = false;
493 sig.insert(firstPos, 'V');
496 i = descriptor.indexOf(';', i);
500 hasReturnType[0] = true;
507 break; // invalid character
513 private void generateStaticField(Variable v) throws IOException {
515 .append(jc.getName().getExternalName().replace('.', '_'))
516 .append('_').append(v.getName()).append(" = 0;");
519 private String findMethodName(Method m) {
520 StringBuilder out = new StringBuilder();
521 if ("<init>".equals(m.getName())) { // NOI18N
522 out.append("consV"); // NOI18N
524 out.append(m.getName());
525 out.append(m.getReturnType());
527 List<Parameter> args = m.getParameters();
528 for (Parameter t : args) {
529 out.append(t.getDescriptor());
531 return out.toString();
534 private String findMethodName(CPMethodInfo mi, int[] cnt, boolean[] hasReturn) {
535 StringBuilder name = new StringBuilder();
536 if ("<init>".equals(mi.getName())) { // NOI18N
537 name.append("cons"); // NOI18N
539 name.append(mi.getName());
541 cnt[0] = countArgs(mi.getDescriptor(), hasReturn, name);
542 return name.toString();
545 private int invokeStaticMethod(byte[] byteCodes, int i, boolean isStatic)
547 int methodIndex = readIntArg(byteCodes, i);
548 CPMethodInfo mi = (CPMethodInfo) jc.getConstantPool().get(methodIndex);
549 boolean[] hasReturn = { false };
551 String mn = findMethodName(mi, cnt, hasReturn);
553 for (int j = cnt[0] - 1; j >= 0; j--) {
554 out.append("var v" + j).append(" = stack.pop(); ");
558 out.append("stack.push(");
560 out.append(mi.getClassName().getInternalName().replace('/', '_'));
566 out.append("stack.pop()");
569 for (int j = 0; j < cnt[0]; j++) {
582 private int invokeVirtualMethod(byte[] byteCodes, int i)
584 int methodIndex = readIntArg(byteCodes, i);
585 CPMethodInfo mi = (CPMethodInfo) jc.getConstantPool().get(methodIndex);
586 boolean[] hasReturn = { false };
588 String mn = findMethodName(mi, cnt, hasReturn);
590 for (int j = cnt[0] - 1; j >= 0; j--) {
591 out.append("var v" + j).append(" = stack.pop(); ");
593 out.append("var self = stack.pop(); ");
595 out.append("stack.push(");
601 for (int j = 0; j < cnt[0]; j++) {