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 int indx = i + readIntArg(byteCodes, i);
360 out.append("if (stack.pop()) { gt = " + indx);
361 out.append("; continue; }");
366 int indx = i + readIntArg(byteCodes, i);
367 out.append("if (!stack.pop()) { gt = " + indx);
368 out.append("; continue; }");
373 i = generateIf(byteCodes, i, "!=");
376 i = generateIf(byteCodes, i, ">");
379 i = generateIf(byteCodes, i, ">=");
382 i = generateIf(byteCodes, i, "<");
385 i = generateIf(byteCodes, i, "<=");
388 int indx = i + readIntArg(byteCodes, i);
389 out.append("gt = " + indx).append("; continue;");
393 case bc_invokeinterface:
394 case bc_invokevirtual:
395 i = invokeVirtualMethod(byteCodes, i);
397 case bc_invokespecial:
398 i = invokeStaticMethod(byteCodes, i, false);
400 case bc_invokestatic:
401 i = invokeStaticMethod(byteCodes, i, true);
404 int indx = readIntArg(byteCodes, i);
405 CPClassInfo ci = jc.getConstantPool().getClass(indx);
406 out.append("stack.push(");
407 out.append("new ").append(ci.getClassName().getExternalName().replace('.','_'));
413 out.append("stack.push(stack[stack.length - 1]);");
416 out.append("stack.push(" + byteCodes[++i] + ");");
419 int indx = readIntArg(byteCodes, i);
420 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
421 out.append(" stack.push(stack.pop().").append(fi.getFieldName()).append(");");
426 int indx = readIntArg(byteCodes, i);
427 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
428 out.append("stack.push(").append(fi.getClassName().getExternalName().replace('.', '_'));
429 out.append('_').append(fi.getFieldName()).append(");");
434 int indx = readIntArg(byteCodes, i);
435 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
436 out.append(fi.getClassName().getExternalName().replace('.', '_'));
437 out.append('_').append(fi.getFieldName()).append(" = stack.pop();");
442 int indx = readIntArg(byteCodes, i);
443 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
444 out.append("{ var v = stack.pop(); stack.pop().")
445 .append(fi.getFieldName()).append(" = v; }");
452 for (int j = prev; j <= i; j++) {
454 final int cc = (byteCodes[j] + 256) % 256;
455 out.append(Integer.toString(cc));
462 private int generateIf(byte[] byteCodes, int i, final String test) throws IOException {
463 int indx = i + readIntArg(byteCodes, i);
464 out.append("if (stack.pop() ").append(test).append(" stack.pop()) { gt = " + indx);
465 out.append("; continue; }");
469 private int readIntArg(byte[] byteCodes, int offsetInstruction) {
470 final int indxHi = byteCodes[offsetInstruction + 1] << 8;
471 final int indxLo = byteCodes[offsetInstruction + 2];
472 return (indxHi & 0xffffff00) | (indxLo & 0xff);
475 private static int countArgs(String descriptor, boolean[] hasReturnType, StringBuilder sig) {
478 Boolean count = null;
479 int firstPos = sig.length();
480 while (i < descriptor.length()) {
481 char ch = descriptor.charAt(i++);
501 hasReturnType[0] = true;
502 sig.insert(firstPos, ch);
507 hasReturnType[0] = false;
508 sig.insert(firstPos, 'V');
511 int next = descriptor.indexOf(';', i);
515 sig.append(descriptor.substring(i, next).replace('/', '_'));
517 sig.insert(firstPos, descriptor.substring(i, next).replace('/', '_'));
518 sig.insert(firstPos, ch);
519 hasReturnType[0] = true;
527 break; // invalid character
533 private void generateStaticField(Variable v) throws IOException {
535 .append(jc.getName().getExternalName().replace('.', '_'))
536 .append('_').append(v.getName()).append(" = 0;");
539 private String findMethodName(Method m) {
540 StringBuilder out = new StringBuilder();
541 if ("<init>".equals(m.getName())) { // NOI18N
542 out.append("consV"); // NOI18N
544 out.append(m.getName());
545 outType(m.getReturnType(), out);
547 List<Parameter> args = m.getParameters();
548 for (Parameter t : args) {
549 outType(t.getDescriptor(), out);
551 return out.toString();
554 private String findMethodName(CPMethodInfo mi, int[] cnt, boolean[] hasReturn) {
555 StringBuilder name = new StringBuilder();
556 if ("<init>".equals(mi.getName())) { // NOI18N
557 name.append("cons"); // NOI18N
559 name.append(mi.getName());
561 cnt[0] = countArgs(mi.getDescriptor(), hasReturn, name);
562 return name.toString();
565 private int invokeStaticMethod(byte[] byteCodes, int i, boolean isStatic)
567 int methodIndex = readIntArg(byteCodes, i);
568 CPMethodInfo mi = (CPMethodInfo) jc.getConstantPool().get(methodIndex);
569 boolean[] hasReturn = { false };
571 String mn = findMethodName(mi, cnt, hasReturn);
573 for (int j = cnt[0] - 1; j >= 0; j--) {
574 out.append("var v" + j).append(" = stack.pop(); ");
578 out.append("stack.push(");
580 out.append(mi.getClassName().getInternalName().replace('/', '_'));
586 out.append("stack.pop()");
589 for (int j = 0; j < cnt[0]; j++) {
602 private int invokeVirtualMethod(byte[] byteCodes, int i)
604 int methodIndex = readIntArg(byteCodes, i);
605 CPMethodInfo mi = (CPMethodInfo) jc.getConstantPool().get(methodIndex);
606 boolean[] hasReturn = { false };
608 String mn = findMethodName(mi, cnt, hasReturn);
610 for (int j = cnt[0] - 1; j >= 0; j--) {
611 out.append("var v" + j).append(" = stack.pop(); ");
613 out.append("var self = stack.pop(); ");
615 out.append("stack.push(");
621 for (int j = 0; j < cnt[0]; j++) {
634 private void outType(final String d, StringBuilder out) {
635 if (d.charAt(0) == 'L') {
636 assert d.charAt(d.length() - 1) == ';';
637 out.append(d.replace('/', '_').substring(0, d.length() - 1));