The compilation to JavaScript now identifies list of external references and provides them back to the caller
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);
86 out.append("function java_lang_Object(){}\n"); // XXX temporary
87 out.append("function java_lang_Object_consV(self){}\n"); // XXX temporary
89 final String className = jc.getName().getInternalName().replace('/', '_');
90 out.append("\nfunction ").append(className);
92 for (Method m : jc.getMethods()) {
94 compiler.generateMethodReference(m);
97 for (Variable v : jc.getVariables()) {
99 out.append("\n this." + v.getName() + " = 0;");
102 out.append("\n this.$instOf_").append(className).append(" = true;");
104 ClassName sc = jc.getSuperClass();
106 out.append("\n ").append(className)
107 .append(".prototype = new ").append(sc.getInternalName().replace('/', '_'));
110 private void generateStaticMethod(Method m) throws IOException {
111 out.append("\nfunction ").append(
112 jc.getName().getInternalName().replace('/', '_')
113 ).append('_').append(findMethodName(m));
116 List<Parameter> args = m.getParameters();
117 for (int index = 0, i = 0; i < args.size(); i++) {
119 out.append("arg").append(String.valueOf(index));
121 final String desc = args.get(i).getDescriptor();
122 if ("D".equals(desc) || "J".equals(desc)) {
128 out.append(") {").append("\n");
129 final Code code = m.getCode();
131 int len = code.getMaxLocals();
132 for (int index = args.size(), i = args.size(); i < len; i++) {
134 out.append("arg").append(String.valueOf(i)).append(";\n");
136 out.append(" var stack = new Array(");
137 out.append(Integer.toString(code.getMaxStack()));
139 produceCode(code.getByteCodes());
141 out.append(" /* no code found for ").append(m.getTypeSignature()).append(" */\n");
146 private void generateMethodReference(Method m) throws IOException {
147 final String name = findMethodName(m);
148 out.append("\n this.").append(name).append(" = ")
149 .append(jc.getName().getInternalName().replace('/', '_'))
150 .append('_').append(name).append(";");
153 private void generateInstanceMethod(Method m) throws IOException {
154 out.append("\nfunction ").append(
155 jc.getName().getInternalName().replace('/', '_')
156 ).append('_').append(findMethodName(m));
159 List<Parameter> args = m.getParameters();
160 for (int index = 1, i = 0; i < args.size(); i++) {
162 out.append("arg").append(String.valueOf(index));
163 final String desc = args.get(i).getDescriptor();
164 if ("D".equals(desc) || "J".equals(desc)) {
170 out.append(") {").append("\n");
171 final Code code = m.getCode();
173 int len = code.getMaxLocals();
174 for (int index = args.size(), i = args.size(); i < len; i++) {
176 out.append("arg").append(String.valueOf(i + 1)).append(";\n");
178 out.append(";\n var stack = new Array(");
179 out.append(Integer.toString(code.getMaxStack()));
181 produceCode(code.getByteCodes());
183 out.append(" /* no code found for ").append(m.getTypeSignature()).append(" */\n");
188 private void produceCode(byte[] byteCodes) throws IOException {
189 out.append("\n var gt = 0;\n for(;;) switch(gt) {\n");
190 for (int i = 0; i < byteCodes.length; i++) {
192 out.append(" case " + i).append(": ");
193 final int c = (byteCodes[i] + 256) % 256;
200 out.append("stack.push(arg0);");
207 out.append("stack.push(arg1);");
214 out.append("stack.push(arg2);");
221 out.append("stack.push(arg3);");
228 final int indx = (byteCodes[++i] + 256) % 256;
229 out.append("stack.push(arg").append(indx + ");");
237 out.append("arg0 = stack.pop();");
244 out.append("arg1 = stack.pop();");
251 out.append("arg2 = stack.pop();");
258 out.append("arg3 = stack.pop();");
264 out.append("stack.push(stack.pop() + stack.pop());");
270 out.append("{ var tmp = stack.pop(); stack.push(stack.pop() - tmp); }");
276 out.append("stack.push(stack.pop() * stack.pop());");
280 out.append("{ var tmp = stack.pop(); stack.push(Math.floor(stack.pop() / tmp)); }");
284 out.append("{ var tmp = stack.pop(); stack.push(stack.pop() / tmp); }");
288 out.append("stack.push(stack.pop() & stack.pop());");
292 out.append("stack.push(stack.pop() | stack.pop());");
296 out.append("stack.push(stack.pop() ^ stack.pop());");
299 final int varIndx = (byteCodes[++i] + 256) % 256;
300 final int incrBy = (byteCodes[++i] + 256) % 256;
302 out.append("arg" + varIndx).append("++;");
304 out.append("arg" + varIndx).append(" += " + incrBy).append(";");
309 out.append("return;");
316 out.append("return stack.pop();");
327 out.append("/* number conversion */");
333 out.append("stack.push(Math.floor(stack.pop()));");
338 out.append("/* number conversion */");
344 out.append("stack.push(0);");
350 out.append("stack.push(1);");
354 out.append("stack.push(2);");
357 out.append("stack.push(3);");
360 out.append("stack.push(4);");
363 out.append("stack.push(5);");
367 int indx = readIntArg(byteCodes, i);
368 CPEntry entry = jc.getConstantPool().get(indx);
370 out.append("stack.push(" + entry.getValue() + ");");
374 i = generateIf(byteCodes, i, "==");
378 int indx = i + readIntArg(byteCodes, i);
379 out.append("if (stack.pop() == 0) { gt = " + indx);
380 out.append("; continue; }");
385 int indx = i + readIntArg(byteCodes, i);
386 out.append("if (stack.pop()) { gt = " + indx);
387 out.append("; continue; }");
392 int indx = i + readIntArg(byteCodes, i);
393 out.append("if (!stack.pop()) { gt = " + indx);
394 out.append("; continue; }");
399 i = generateIf(byteCodes, i, "!=");
402 i = generateIf(byteCodes, i, ">");
405 i = generateIf(byteCodes, i, ">=");
408 i = generateIf(byteCodes, i, "<");
411 i = generateIf(byteCodes, i, "<=");
414 int indx = i + readIntArg(byteCodes, i);
415 out.append("gt = " + indx).append("; continue;");
419 case bc_invokeinterface:
420 case bc_invokevirtual:
421 i = invokeVirtualMethod(byteCodes, i);
423 case bc_invokespecial:
424 i = invokeStaticMethod(byteCodes, i, false);
426 case bc_invokestatic:
427 i = invokeStaticMethod(byteCodes, i, true);
430 int indx = readIntArg(byteCodes, i);
431 CPClassInfo ci = jc.getConstantPool().getClass(indx);
432 out.append("stack.push(");
433 out.append("new ").append(ci.getClassName().getInternalName().replace('/','_'));
435 addReference(ci.getClassName().getInternalName());
440 out.append("stack.push(stack[stack.length - 1]);");
443 out.append("stack.push(" + byteCodes[++i] + ");");
446 int indx = readIntArg(byteCodes, i);
447 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
448 out.append(" stack.push(stack.pop().").append(fi.getFieldName()).append(");");
453 int indx = readIntArg(byteCodes, i);
454 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
455 final String in = fi.getClassName().getInternalName();
456 out.append("stack.push(").append(in.replace('/', '_'));
457 out.append('_').append(fi.getFieldName()).append(");");
463 int indx = readIntArg(byteCodes, i);
464 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
465 final String in = fi.getClassName().getInternalName();
466 out.append(in.replace('/', '_'));
467 out.append('_').append(fi.getFieldName()).append(" = stack.pop();");
473 int indx = readIntArg(byteCodes, i);
474 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
475 out.append("{ var v = stack.pop(); stack.pop().")
476 .append(fi.getFieldName()).append(" = v; }");
480 case bc_instanceof: {
481 int indx = readIntArg(byteCodes, i);
482 CPClassInfo ci = jc.getConstantPool().getClass(indx);
483 out.append("stack.push(stack.pop().$instOf_")
484 .append(ci.getClassName().getInternalName().replace('/', '_'))
485 .append(" ? 1 : 0);");
491 for (int j = prev; j <= i; j++) {
493 final int cc = (byteCodes[j] + 256) % 256;
494 out.append(Integer.toString(cc));
501 private int generateIf(byte[] byteCodes, int i, final String test) throws IOException {
502 int indx = i + readIntArg(byteCodes, i);
503 out.append("if (stack.pop() ").append(test).append(" stack.pop()) { gt = " + indx);
504 out.append("; continue; }");
508 private int readIntArg(byte[] byteCodes, int offsetInstruction) {
509 final int indxHi = byteCodes[offsetInstruction + 1] << 8;
510 final int indxLo = byteCodes[offsetInstruction + 2];
511 return (indxHi & 0xffffff00) | (indxLo & 0xff);
514 private static int countArgs(String descriptor, boolean[] hasReturnType, StringBuilder sig) {
517 Boolean count = null;
518 int firstPos = sig.length();
519 while (i < descriptor.length()) {
520 char ch = descriptor.charAt(i++);
540 hasReturnType[0] = true;
541 sig.insert(firstPos, ch);
546 hasReturnType[0] = false;
547 sig.insert(firstPos, 'V');
550 int next = descriptor.indexOf(';', i);
554 sig.append(descriptor.substring(i, next).replace('/', '_'));
556 sig.insert(firstPos, descriptor.substring(i, next).replace('/', '_'));
557 sig.insert(firstPos, ch);
558 hasReturnType[0] = true;
566 break; // invalid character
572 private void generateStaticField(Variable v) throws IOException {
574 .append(jc.getName().getInternalName().replace('/', '_'))
575 .append('_').append(v.getName()).append(" = 0;");
578 private String findMethodName(Method m) {
579 StringBuilder out = new StringBuilder();
580 if ("<init>".equals(m.getName())) { // NOI18N
581 out.append("consV"); // NOI18N
583 out.append(m.getName());
584 outType(m.getReturnType(), out);
586 List<Parameter> args = m.getParameters();
587 for (Parameter t : args) {
588 outType(t.getDescriptor(), out);
590 return out.toString();
593 private String findMethodName(CPMethodInfo mi, int[] cnt, boolean[] hasReturn) {
594 StringBuilder name = new StringBuilder();
595 if ("<init>".equals(mi.getName())) { // NOI18N
596 name.append("cons"); // NOI18N
598 name.append(mi.getName());
600 cnt[0] = countArgs(mi.getDescriptor(), hasReturn, name);
601 return name.toString();
604 private int invokeStaticMethod(byte[] byteCodes, int i, boolean isStatic)
606 int methodIndex = readIntArg(byteCodes, i);
607 CPMethodInfo mi = (CPMethodInfo) jc.getConstantPool().get(methodIndex);
608 boolean[] hasReturn = { false };
610 String mn = findMethodName(mi, cnt, hasReturn);
612 for (int j = cnt[0] - 1; j >= 0; j--) {
613 out.append("var v" + j).append(" = stack.pop(); ");
617 out.append("stack.push(");
619 final String in = mi.getClassName().getInternalName();
620 out.append(in.replace('/', '_'));
626 out.append("stack.pop()");
629 for (int j = 0; j < cnt[0]; j++) {
643 private int invokeVirtualMethod(byte[] byteCodes, int i)
645 int methodIndex = readIntArg(byteCodes, i);
646 CPMethodInfo mi = (CPMethodInfo) jc.getConstantPool().get(methodIndex);
647 boolean[] hasReturn = { false };
649 String mn = findMethodName(mi, cnt, hasReturn);
651 for (int j = cnt[0] - 1; j >= 0; j--) {
652 out.append("var v" + j).append(" = stack.pop(); ");
654 out.append("var self = stack.pop(); ");
656 out.append("stack.push(");
662 for (int j = 0; j < cnt[0]; j++) {
675 private void addReference(String cn) {
676 if (references != null) {
681 private void outType(final String d, StringBuilder out) {
682 if (d.charAt(0) == 'L') {
683 assert d.charAt(d.length() - 1) == ';';
684 out.append(d.replace('/', '_').substring(0, d.length() - 1));