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.Collection;
23 import java.util.List;
24 import static org.netbeans.modules.classfile.ByteCodes.*;
25 import org.netbeans.modules.classfile.CPClassInfo;
26 import org.netbeans.modules.classfile.CPEntry;
27 import org.netbeans.modules.classfile.CPFieldInfo;
28 import org.netbeans.modules.classfile.CPMethodInfo;
29 import org.netbeans.modules.classfile.ClassFile;
30 import org.netbeans.modules.classfile.ClassName;
31 import org.netbeans.modules.classfile.Code;
32 import org.netbeans.modules.classfile.Method;
33 import org.netbeans.modules.classfile.Parameter;
34 import org.netbeans.modules.classfile.Variable;
36 /** Translator of the code inside class files to JavaScript.
38 * @author Jaroslav Tulach <jtulach@netbeans.org>
40 public final class ByteCodeToJavaScript {
41 private final ClassFile jc;
42 private final Appendable out;
43 private final Collection<? super String> references;
45 private ByteCodeToJavaScript(
46 ClassFile jc, Appendable out, Collection<? super String> references
50 this.references = references;
54 * Converts a given class file to a JavaScript version.
56 * @param classFile input stream with code of the .class file
57 * @param out a {@link StringBuilder} or similar to generate the output to
58 * @param references a write only collection where the system adds list of
59 * other classes that were referenced and should be loaded in order the
60 * generated JavaScript code works properly. The names are in internal
61 * JVM form so String is <code>java/lang/String</code>. Can be <code>null</code>
62 * if one is not interested in knowing references
63 * @throws IOException if something goes wrong during read or write or translating
66 public static void compile(
67 InputStream classFile, Appendable out,
68 Collection<? super String> references
69 ) throws IOException {
70 ClassFile jc = new ClassFile(classFile, true);
71 ByteCodeToJavaScript compiler = new ByteCodeToJavaScript(
74 for (Method m : jc.getMethods()) {
76 compiler.generateStaticMethod(m);
78 compiler.generateInstanceMethod(m);
81 for (Variable v : jc.getVariables()) {
83 compiler.generateStaticField(v);
87 final String className = jc.getName().getInternalName().replace('/', '_');
88 out.append("\nfunction ").append(className);
90 for (Method m : jc.getMethods()) {
92 compiler.generateMethodReference(m);
95 for (Variable v : jc.getVariables()) {
97 out.append("\n this." + v.getName() + " = 0;");
100 out.append("\n this.$instOf_").append(className).append(" = true;");
102 ClassName sc = jc.getSuperClass();
104 out.append("\n ").append(className)
105 .append(".prototype = new ").append(sc.getInternalName().replace('/', '_'));
108 private void generateStaticMethod(Method m) throws IOException {
109 out.append("\nfunction ").append(
110 jc.getName().getInternalName().replace('/', '_')
111 ).append('_').append(findMethodName(m));
114 List<Parameter> args = m.getParameters();
115 for (int index = 0, i = 0; i < args.size(); i++) {
117 out.append("arg").append(String.valueOf(index));
119 final String desc = args.get(i).getDescriptor();
120 if ("D".equals(desc) || "J".equals(desc)) {
126 out.append(") {").append("\n");
127 final Code code = m.getCode();
129 int len = code.getMaxLocals();
130 for (int index = args.size(), i = args.size(); i < len; i++) {
132 out.append("arg").append(String.valueOf(i)).append(";\n");
134 out.append(" var stack = new Array(");
135 out.append(Integer.toString(code.getMaxStack()));
137 produceCode(code.getByteCodes());
139 out.append(" /* no code found for ").append(m.getTypeSignature()).append(" */\n");
144 private void generateMethodReference(Method m) throws IOException {
145 final String name = findMethodName(m);
146 out.append("\n this.").append(name).append(" = ")
147 .append(jc.getName().getInternalName().replace('/', '_'))
148 .append('_').append(name).append(";");
151 private void generateInstanceMethod(Method m) throws IOException {
152 out.append("\nfunction ").append(
153 jc.getName().getInternalName().replace('/', '_')
154 ).append('_').append(findMethodName(m));
157 List<Parameter> args = m.getParameters();
158 for (int index = 1, i = 0; i < args.size(); i++) {
160 out.append("arg").append(String.valueOf(index));
161 final String desc = args.get(i).getDescriptor();
162 if ("D".equals(desc) || "J".equals(desc)) {
168 out.append(") {").append("\n");
169 final Code code = m.getCode();
171 int len = code.getMaxLocals();
172 for (int index = args.size(), i = args.size(); i < len; i++) {
174 out.append("arg").append(String.valueOf(i + 1)).append(";\n");
176 out.append(";\n var stack = new Array(");
177 out.append(Integer.toString(code.getMaxStack()));
179 produceCode(code.getByteCodes());
181 out.append(" /* no code found for ").append(m.getTypeSignature()).append(" */\n");
186 private void produceCode(byte[] byteCodes) throws IOException {
187 out.append("\n var gt = 0;\n for(;;) switch(gt) {\n");
188 for (int i = 0; i < byteCodes.length; i++) {
190 out.append(" case " + i).append(": ");
191 final int c = (byteCodes[i] + 256) % 256;
198 out.append("stack.push(arg0);");
205 out.append("stack.push(arg1);");
212 out.append("stack.push(arg2);");
219 out.append("stack.push(arg3);");
226 final int indx = (byteCodes[++i] + 256) % 256;
227 out.append("stack.push(arg").append(indx + ");");
235 out.append("arg0 = stack.pop();");
242 out.append("arg1 = stack.pop();");
249 out.append("arg2 = stack.pop();");
256 out.append("arg3 = stack.pop();");
262 out.append("stack.push(stack.pop() + stack.pop());");
268 out.append("{ var tmp = stack.pop(); stack.push(stack.pop() - tmp); }");
274 out.append("stack.push(stack.pop() * stack.pop());");
278 out.append("{ var tmp = stack.pop(); stack.push(Math.floor(stack.pop() / tmp)); }");
282 out.append("{ var tmp = stack.pop(); stack.push(stack.pop() / tmp); }");
286 out.append("stack.push(stack.pop() & stack.pop());");
290 out.append("stack.push(stack.pop() | stack.pop());");
294 out.append("stack.push(stack.pop() ^ stack.pop());");
297 final int varIndx = (byteCodes[++i] + 256) % 256;
298 final int incrBy = (byteCodes[++i] + 256) % 256;
300 out.append("arg" + varIndx).append("++;");
302 out.append("arg" + varIndx).append(" += " + incrBy).append(";");
307 out.append("return;");
314 out.append("return stack.pop();");
325 out.append("/* number conversion */");
331 out.append("stack.push(Math.floor(stack.pop()));");
336 out.append("/* number conversion */");
342 out.append("stack.push(0);");
348 out.append("stack.push(1);");
352 out.append("stack.push(2);");
355 out.append("stack.push(3);");
358 out.append("stack.push(4);");
361 out.append("stack.push(5);");
364 int indx = byteCodes[i++];
365 CPEntry entry = jc.getConstantPool().get(indx);
366 out.append("stack.push(" + entry.getValue() + ");");
371 int indx = readIntArg(byteCodes, i);
372 CPEntry entry = jc.getConstantPool().get(indx);
374 out.append("stack.push(" + entry.getValue() + ");");
382 out.append("{ var delta = stack.pop() - stack.pop(); stack.push(delta < 0 ?-1 : (delta == 0 ? 0 : 1)); }");
386 i = generateIf(byteCodes, i, "==");
390 int indx = i + readIntArg(byteCodes, i);
391 out.append("if (stack.pop() == 0) { gt = " + indx);
392 out.append("; continue; }");
397 int indx = i + readIntArg(byteCodes, i);
398 out.append("if (stack.pop() != 0) { gt = " + indx);
399 out.append("; continue; }");
404 int indx = i + readIntArg(byteCodes, i);
405 out.append("if (stack.pop() < 0) { gt = " + indx);
406 out.append("; continue; }");
411 int indx = i + readIntArg(byteCodes, i);
412 out.append("if (stack.pop() <= 0) { gt = " + indx);
413 out.append("; continue; }");
418 int indx = i + readIntArg(byteCodes, i);
419 out.append("if (stack.pop() > 0) { gt = " + indx);
420 out.append("; continue; }");
425 int indx = i + readIntArg(byteCodes, i);
426 out.append("if (stack.pop() >= 0) { gt = " + indx);
427 out.append("; continue; }");
432 int indx = i + readIntArg(byteCodes, i);
433 out.append("if (stack.pop()) { gt = " + indx);
434 out.append("; continue; }");
439 int indx = i + readIntArg(byteCodes, i);
440 out.append("if (!stack.pop()) { gt = " + indx);
441 out.append("; continue; }");
446 i = generateIf(byteCodes, i, "!=");
449 i = generateIf(byteCodes, i, ">");
452 i = generateIf(byteCodes, i, ">=");
455 i = generateIf(byteCodes, i, "<");
458 i = generateIf(byteCodes, i, "<=");
461 int indx = i + readIntArg(byteCodes, i);
462 out.append("gt = " + indx).append("; continue;");
466 case bc_invokeinterface:
467 case bc_invokevirtual:
468 i = invokeVirtualMethod(byteCodes, i);
470 case bc_invokespecial:
471 i = invokeStaticMethod(byteCodes, i, false);
473 case bc_invokestatic:
474 i = invokeStaticMethod(byteCodes, i, true);
477 int indx = readIntArg(byteCodes, i);
478 CPClassInfo ci = jc.getConstantPool().getClass(indx);
479 out.append("stack.push(");
480 out.append("new ").append(ci.getClassName().getInternalName().replace('/','_'));
482 addReference(ci.getClassName().getInternalName());
487 out.append("stack.push(stack[stack.length - 1]);");
490 out.append("stack.push(" + byteCodes[++i] + ");");
493 int indx = readIntArg(byteCodes, i);
494 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
495 out.append(" stack.push(stack.pop().").append(fi.getFieldName()).append(");");
500 int indx = readIntArg(byteCodes, i);
501 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
502 final String in = fi.getClassName().getInternalName();
503 out.append("stack.push(").append(in.replace('/', '_'));
504 out.append('_').append(fi.getFieldName()).append(");");
510 int indx = readIntArg(byteCodes, i);
511 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
512 final String in = fi.getClassName().getInternalName();
513 out.append(in.replace('/', '_'));
514 out.append('_').append(fi.getFieldName()).append(" = stack.pop();");
520 int indx = readIntArg(byteCodes, i);
521 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
522 out.append("{ var v = stack.pop(); stack.pop().")
523 .append(fi.getFieldName()).append(" = v; }");
527 case bc_instanceof: {
528 int indx = readIntArg(byteCodes, i);
529 CPClassInfo ci = jc.getConstantPool().getClass(indx);
530 out.append("stack.push(stack.pop().$instOf_")
531 .append(ci.getClassName().getInternalName().replace('/', '_'))
532 .append(" ? 1 : 0);");
538 for (int j = prev; j <= i; j++) {
540 final int cc = (byteCodes[j] + 256) % 256;
541 out.append(Integer.toString(cc));
548 private int generateIf(byte[] byteCodes, int i, final String test) throws IOException {
549 int indx = i + readIntArg(byteCodes, i);
550 out.append("if (stack.pop() ").append(test).append(" stack.pop()) { gt = " + indx);
551 out.append("; continue; }");
555 private int readIntArg(byte[] byteCodes, int offsetInstruction) {
556 final int indxHi = byteCodes[offsetInstruction + 1] << 8;
557 final int indxLo = byteCodes[offsetInstruction + 2];
558 return (indxHi & 0xffffff00) | (indxLo & 0xff);
561 private static int countArgs(String descriptor, boolean[] hasReturnType, StringBuilder sig) {
564 Boolean count = null;
565 int firstPos = sig.length();
566 while (i < descriptor.length()) {
567 char ch = descriptor.charAt(i++);
587 hasReturnType[0] = true;
588 sig.insert(firstPos, ch);
593 hasReturnType[0] = false;
594 sig.insert(firstPos, 'V');
597 int next = descriptor.indexOf(';', i);
601 sig.append(descriptor.substring(i, next).replace('/', '_'));
603 sig.insert(firstPos, descriptor.substring(i, next).replace('/', '_'));
604 sig.insert(firstPos, ch);
605 hasReturnType[0] = true;
613 break; // invalid character
619 private void generateStaticField(Variable v) throws IOException {
621 .append(jc.getName().getInternalName().replace('/', '_'))
622 .append('_').append(v.getName()).append(" = 0;");
625 private String findMethodName(Method m) {
626 StringBuilder tmp = new StringBuilder();
627 if ("<init>".equals(m.getName())) { // NOI18N
628 tmp.append("consV"); // NOI18N
629 } else if ("<clinit>".equals(m.getName())) { // NOI18N
630 tmp.append("classV"); // NOI18N
632 tmp.append(m.getName());
633 outType(m.getReturnType(), tmp);
635 List<Parameter> args = m.getParameters();
636 for (Parameter t : args) {
637 outType(t.getDescriptor(), tmp);
639 return tmp.toString();
642 private String findMethodName(CPMethodInfo mi, int[] cnt, boolean[] hasReturn) {
643 StringBuilder name = new StringBuilder();
644 if ("<init>".equals(mi.getName())) { // NOI18N
645 name.append("cons"); // NOI18N
647 name.append(mi.getName());
649 cnt[0] = countArgs(mi.getDescriptor(), hasReturn, name);
650 return name.toString();
653 private int invokeStaticMethod(byte[] byteCodes, int i, boolean isStatic)
655 int methodIndex = readIntArg(byteCodes, i);
656 CPMethodInfo mi = (CPMethodInfo) jc.getConstantPool().get(methodIndex);
657 boolean[] hasReturn = { false };
659 String mn = findMethodName(mi, cnt, hasReturn);
661 for (int j = cnt[0] - 1; j >= 0; j--) {
662 out.append("var v" + j).append(" = stack.pop(); ");
666 out.append("stack.push(");
668 final String in = mi.getClassName().getInternalName();
669 out.append(in.replace('/', '_'));
675 out.append("stack.pop()");
678 for (int j = 0; j < cnt[0]; j++) {
692 private int invokeVirtualMethod(byte[] byteCodes, int i)
694 int methodIndex = readIntArg(byteCodes, i);
695 CPMethodInfo mi = (CPMethodInfo) jc.getConstantPool().get(methodIndex);
696 boolean[] hasReturn = { false };
698 String mn = findMethodName(mi, cnt, hasReturn);
700 for (int j = cnt[0] - 1; j >= 0; j--) {
701 out.append("var v" + j).append(" = stack.pop(); ");
703 out.append("var self = stack.pop(); ");
705 out.append("stack.push(");
711 for (int j = 0; j < cnt[0]; j++) {
724 private void addReference(String cn) {
725 if (references != null) {
730 private void outType(final String d, StringBuilder out) {
731 if (d.charAt(0) == 'L') {
732 assert d.charAt(d.length() - 1) == ';';
733 out.append(d.replace('/', '_').substring(0, d.length() - 1));