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;");
85 out.append("\n this.$instOf_").append(className).append(" = true;");
87 ClassName sc = jc.getSuperClass();
89 out.append("\n ").append(className)
90 .append(".prototype = new ").append(sc.getExternalName().replace('.', '_'));
93 private void generateStaticMethod(Method m) throws IOException {
94 out.append("\nfunction ").append(
95 jc.getName().getExternalName().replace('.', '_')
96 ).append('_').append(findMethodName(m));
99 List<Parameter> args = m.getParameters();
100 for (int index = 0, i = 0; i < args.size(); i++) {
102 out.append("arg").append(String.valueOf(index));
104 final String desc = args.get(i).getDescriptor();
105 if ("D".equals(desc) || "J".equals(desc)) {
111 out.append(") {").append("\n");
112 final Code code = m.getCode();
113 int len = code.getMaxLocals();
114 for (int index = args.size(), i = args.size(); i < len; i++) {
116 out.append("arg").append(String.valueOf(i)).append(";\n");
118 out.append(" var stack = new Array(");
119 out.append(Integer.toString(code.getMaxStack()));
121 produceCode(code.getByteCodes());
125 private void generateMethodReference(Method m) throws IOException {
126 final String name = findMethodName(m);
127 out.append("\n this.").append(name).append(" = ")
128 .append(jc.getName().getExternalName().replace('.', '_'))
129 .append('_').append(name).append(";");
132 private void generateInstanceMethod(Method m) throws IOException {
133 out.append("\nfunction ").append(
134 jc.getName().getExternalName().replace('.', '_')
135 ).append('_').append(findMethodName(m));
138 List<Parameter> args = m.getParameters();
139 for (int index = 1, i = 0; i < args.size(); i++) {
141 out.append("arg").append(String.valueOf(index));
142 final String desc = args.get(i).getDescriptor();
143 if ("D".equals(desc) || "J".equals(desc)) {
149 out.append(") {").append("\n");
150 final Code code = m.getCode();
151 int len = code.getMaxLocals();
152 for (int index = args.size(), i = args.size(); i < len; i++) {
154 out.append("arg").append(String.valueOf(i + 1)).append(";\n");
156 out.append(";\n var stack = new Array(");
157 out.append(Integer.toString(code.getMaxStack()));
159 produceCode(code.getByteCodes());
163 private void produceCode(byte[] byteCodes) throws IOException {
164 out.append("\n var gt = 0;\n for(;;) switch(gt) {\n");
165 for (int i = 0; i < byteCodes.length; i++) {
167 out.append(" case " + i).append(": ");
168 final int c = (byteCodes[i] + 256) % 256;
175 out.append("stack.push(arg0);");
182 out.append("stack.push(arg1);");
189 out.append("stack.push(arg2);");
196 out.append("stack.push(arg3);");
203 final int indx = (byteCodes[++i] + 256) % 256;
204 out.append("stack.push(arg").append(indx + ");");
212 out.append("arg0 = stack.pop();");
219 out.append("arg1 = stack.pop();");
226 out.append("arg2 = stack.pop();");
233 out.append("arg3 = stack.pop();");
239 out.append("stack.push(stack.pop() + stack.pop());");
245 out.append("{ var tmp = stack.pop(); stack.push(stack.pop() - tmp); }");
251 out.append("stack.push(stack.pop() * stack.pop());");
255 out.append("{ var tmp = stack.pop(); stack.push(Math.floor(stack.pop() / tmp)); }");
259 out.append("{ var tmp = stack.pop(); stack.push(stack.pop() / tmp); }");
263 out.append("stack.push(stack.pop() & stack.pop());");
267 out.append("stack.push(stack.pop() | stack.pop());");
271 out.append("stack.push(stack.pop() ^ stack.pop());");
274 final int varIndx = (byteCodes[++i] + 256) % 256;
275 final int incrBy = (byteCodes[++i] + 256) % 256;
277 out.append("arg" + varIndx).append("++;");
279 out.append("arg" + varIndx).append(" += " + incrBy).append(";");
284 out.append("return;");
291 out.append("return stack.pop();");
302 out.append("/* number conversion */");
308 out.append("stack.push(Math.floor(stack.pop()));");
313 out.append("/* number conversion */");
319 out.append("stack.push(0);");
325 out.append("stack.push(1);");
329 out.append("stack.push(2);");
332 out.append("stack.push(3);");
335 out.append("stack.push(4);");
338 out.append("stack.push(5);");
342 int indx = readIntArg(byteCodes, i);
343 CPEntry entry = jc.getConstantPool().get(indx);
345 out.append("stack.push(" + entry.getValue() + ");");
349 i = generateIf(byteCodes, i, "==");
353 int indx = i + readIntArg(byteCodes, i);
354 out.append("if (stack.pop() == 0) { gt = " + indx);
355 out.append("; continue; }");
360 int indx = i + readIntArg(byteCodes, i);
361 out.append("if (stack.pop()) { gt = " + indx);
362 out.append("; continue; }");
367 int indx = i + readIntArg(byteCodes, i);
368 out.append("if (!stack.pop()) { gt = " + indx);
369 out.append("; continue; }");
374 i = generateIf(byteCodes, i, "!=");
377 i = generateIf(byteCodes, i, ">");
380 i = generateIf(byteCodes, i, ">=");
383 i = generateIf(byteCodes, i, "<");
386 i = generateIf(byteCodes, i, "<=");
389 int indx = i + readIntArg(byteCodes, i);
390 out.append("gt = " + indx).append("; continue;");
394 case bc_invokeinterface:
395 case bc_invokevirtual:
396 i = invokeVirtualMethod(byteCodes, i);
398 case bc_invokespecial:
399 i = invokeStaticMethod(byteCodes, i, false);
401 case bc_invokestatic:
402 i = invokeStaticMethod(byteCodes, i, true);
405 int indx = readIntArg(byteCodes, i);
406 CPClassInfo ci = jc.getConstantPool().getClass(indx);
407 out.append("stack.push(");
408 out.append("new ").append(ci.getClassName().getExternalName().replace('.','_'));
414 out.append("stack.push(stack[stack.length - 1]);");
417 out.append("stack.push(" + byteCodes[++i] + ");");
420 int indx = readIntArg(byteCodes, i);
421 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
422 out.append(" stack.push(stack.pop().").append(fi.getFieldName()).append(");");
427 int indx = readIntArg(byteCodes, i);
428 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
429 out.append("stack.push(").append(fi.getClassName().getExternalName().replace('.', '_'));
430 out.append('_').append(fi.getFieldName()).append(");");
435 int indx = readIntArg(byteCodes, i);
436 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
437 out.append(fi.getClassName().getExternalName().replace('.', '_'));
438 out.append('_').append(fi.getFieldName()).append(" = stack.pop();");
443 int indx = readIntArg(byteCodes, i);
444 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
445 out.append("{ var v = stack.pop(); stack.pop().")
446 .append(fi.getFieldName()).append(" = v; }");
450 case bc_instanceof: {
451 int indx = readIntArg(byteCodes, i);
452 CPClassInfo ci = jc.getConstantPool().getClass(indx);
453 out.append("stack.push(stack.pop().$instOf_")
454 .append(ci.getClassName().getExternalName().replace('.', '_'))
455 .append(" ? 1 : 0);");
461 for (int j = prev; j <= i; j++) {
463 final int cc = (byteCodes[j] + 256) % 256;
464 out.append(Integer.toString(cc));
471 private int generateIf(byte[] byteCodes, int i, final String test) throws IOException {
472 int indx = i + readIntArg(byteCodes, i);
473 out.append("if (stack.pop() ").append(test).append(" stack.pop()) { gt = " + indx);
474 out.append("; continue; }");
478 private int readIntArg(byte[] byteCodes, int offsetInstruction) {
479 final int indxHi = byteCodes[offsetInstruction + 1] << 8;
480 final int indxLo = byteCodes[offsetInstruction + 2];
481 return (indxHi & 0xffffff00) | (indxLo & 0xff);
484 private static int countArgs(String descriptor, boolean[] hasReturnType, StringBuilder sig) {
487 Boolean count = null;
488 int firstPos = sig.length();
489 while (i < descriptor.length()) {
490 char ch = descriptor.charAt(i++);
510 hasReturnType[0] = true;
511 sig.insert(firstPos, ch);
516 hasReturnType[0] = false;
517 sig.insert(firstPos, 'V');
520 int next = descriptor.indexOf(';', i);
524 sig.append(descriptor.substring(i, next).replace('/', '_'));
526 sig.insert(firstPos, descriptor.substring(i, next).replace('/', '_'));
527 sig.insert(firstPos, ch);
528 hasReturnType[0] = true;
536 break; // invalid character
542 private void generateStaticField(Variable v) throws IOException {
544 .append(jc.getName().getExternalName().replace('.', '_'))
545 .append('_').append(v.getName()).append(" = 0;");
548 private String findMethodName(Method m) {
549 StringBuilder out = new StringBuilder();
550 if ("<init>".equals(m.getName())) { // NOI18N
551 out.append("consV"); // NOI18N
553 out.append(m.getName());
554 outType(m.getReturnType(), out);
556 List<Parameter> args = m.getParameters();
557 for (Parameter t : args) {
558 outType(t.getDescriptor(), out);
560 return out.toString();
563 private String findMethodName(CPMethodInfo mi, int[] cnt, boolean[] hasReturn) {
564 StringBuilder name = new StringBuilder();
565 if ("<init>".equals(mi.getName())) { // NOI18N
566 name.append("cons"); // NOI18N
568 name.append(mi.getName());
570 cnt[0] = countArgs(mi.getDescriptor(), hasReturn, name);
571 return name.toString();
574 private int invokeStaticMethod(byte[] byteCodes, int i, boolean isStatic)
576 int methodIndex = readIntArg(byteCodes, i);
577 CPMethodInfo mi = (CPMethodInfo) jc.getConstantPool().get(methodIndex);
578 boolean[] hasReturn = { false };
580 String mn = findMethodName(mi, cnt, hasReturn);
582 for (int j = cnt[0] - 1; j >= 0; j--) {
583 out.append("var v" + j).append(" = stack.pop(); ");
587 out.append("stack.push(");
589 out.append(mi.getClassName().getInternalName().replace('/', '_'));
595 out.append("stack.pop()");
598 for (int j = 0; j < cnt[0]; j++) {
611 private int invokeVirtualMethod(byte[] byteCodes, int i)
613 int methodIndex = readIntArg(byteCodes, i);
614 CPMethodInfo mi = (CPMethodInfo) jc.getConstantPool().get(methodIndex);
615 boolean[] hasReturn = { false };
617 String mn = findMethodName(mi, cnt, hasReturn);
619 for (int j = cnt[0] - 1; j >= 0; j--) {
620 out.append("var v" + j).append(" = stack.pop(); ");
622 out.append("var self = stack.pop(); ");
624 out.append("stack.push(");
630 for (int j = 0; j < cnt[0]; j++) {
643 private void outType(final String d, StringBuilder out) {
644 if (d.charAt(0) == 'L') {
645 assert d.charAt(d.length() - 1) == ';';
646 out.append(d.replace('/', '_').substring(0, d.length() - 1));