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.vm4brwsr;
20 import java.io.IOException;
21 import java.io.InputStream;
22 import java.util.ArrayList;
23 import java.util.Collection;
24 import java.util.List;
25 import org.apidesign.bck2brwsr.core.ExtraJavaScript;
26 import org.netbeans.modules.classfile.Annotation;
27 import org.netbeans.modules.classfile.AnnotationComponent;
28 import static org.netbeans.modules.classfile.ByteCodes.*;
29 import org.netbeans.modules.classfile.CPClassInfo;
30 import org.netbeans.modules.classfile.CPEntry;
31 import org.netbeans.modules.classfile.CPFieldInfo;
32 import org.netbeans.modules.classfile.CPMethodInfo;
33 import org.netbeans.modules.classfile.CPStringInfo;
34 import org.netbeans.modules.classfile.ClassFile;
35 import org.netbeans.modules.classfile.ClassName;
36 import org.netbeans.modules.classfile.Code;
37 import org.netbeans.modules.classfile.ElementValue;
38 import org.netbeans.modules.classfile.Method;
39 import org.netbeans.modules.classfile.Parameter;
40 import org.netbeans.modules.classfile.PrimitiveElementValue;
41 import org.netbeans.modules.classfile.Variable;
43 /** Translator of the code inside class files to JavaScript.
45 * @author Jaroslav Tulach <jtulach@netbeans.org>
47 public final class ByteCodeToJavaScript {
48 private final ClassFile jc;
49 private final Appendable out;
50 private final Collection<? super String> references;
52 private ByteCodeToJavaScript(
53 ClassFile jc, Appendable out, Collection<? super String> references
57 this.references = references;
61 * Converts a given class file to a JavaScript version.
63 * @param classFile input stream with code of the .class file
64 * @param out a {@link StringBuilder} or similar to generate the output to
65 * @param references a write only collection where the system adds list of
66 * other classes that were referenced and should be loaded in order the
67 * generated JavaScript code works properly. The names are in internal
68 * JVM form so String is <code>java/lang/String</code>. Can be <code>null</code>
69 * if one is not interested in knowing references
70 * @param scripts write only collection with names of resources to read
72 * @throws IOException if something goes wrong during read or write or translating
75 public static void compile(
76 InputStream classFile, Appendable out,
77 Collection<? super String> references,
78 Collection<? super String> scripts
79 ) throws IOException {
80 ClassFile jc = new ClassFile(classFile, true);
81 final ClassName extraAnn = ClassName.getClassName(ExtraJavaScript.class.getName().replace('.', '/'));
82 Annotation a = jc.getAnnotation(extraAnn);
84 final ElementValue annVal = a.getComponent("resource").getValue();
85 String res = ((PrimitiveElementValue)annVal).getValue().getValue().toString();
87 final AnnotationComponent process = a.getComponent("processByteCode");
88 if (process != null && "false".equals(process.getValue().toString())) {
93 ByteCodeToJavaScript compiler = new ByteCodeToJavaScript(
96 List<String> toInitilize = new ArrayList<String>();
97 for (Method m : jc.getMethods()) {
99 compiler.generateStaticMethod(m, toInitilize);
101 compiler.generateInstanceMethod(m);
104 for (Variable v : jc.getVariables()) {
106 compiler.generateStaticField(v);
110 final String className = jc.getName().getInternalName().replace('/', '_');
111 out.append("\nfunction ").append(className);
113 for (Variable v : jc.getVariables()) {
115 out.append("\n this." + v.getName() + " = 0;");
119 ClassName sc = jc.getSuperClass();
121 out.append("\n").append(className)
122 .append(".prototype = new ").append(sc.getInternalName().replace('/', '_')).append(';');
124 for (Method m : jc.getMethods()) {
125 if (!m.isStatic() && !m.isPrivate() && !m.getName().contains("<init>")) {
126 compiler.generateMethodReference("\n" + className + ".prototype.", m);
129 out.append("\n" + className + ".prototype.$instOf_").append(className).append(" = true;");
130 for (ClassName superInterface : jc.getInterfaces()) {
131 out.append("\n" + className + ".prototype.$instOf_").append(superInterface.getInternalName().replace('/', '_')).append(" = true;");
133 for (String init : toInitilize) {
134 out.append("\n").append(init).append("();");
137 private void generateStaticMethod(Method m, List<String> toInitilize) throws IOException {
138 final String mn = findMethodName(m);
139 out.append("\nfunction ").append(
140 jc.getName().getInternalName().replace('/', '_')
141 ).append('_').append(mn);
142 if (mn.equals("classV")) {
143 toInitilize.add(jc.getName().getInternalName().replace('/', '_') + '_' + mn);
147 List<Parameter> args = m.getParameters();
148 for (int index = 0, i = 0; i < args.size(); i++) {
150 out.append("arg").append(String.valueOf(index));
152 final String desc = findDescriptor(args.get(i).getDescriptor());
153 if ("D".equals(desc) || "J".equals(desc)) {
159 out.append(") {").append("\n");
160 final Code code = m.getCode();
162 int len = code.getMaxLocals();
163 for (int index = args.size(), i = args.size(); i < len; i++) {
165 out.append("arg").append(String.valueOf(i)).append(";\n");
167 out.append(" var stack = new Array();\n");
168 produceCode(code.getByteCodes());
170 out.append(" /* no code found for ").append(m.getTypeSignature()).append(" */\n");
175 private void generateMethodReference(String prefix, Method m) throws IOException {
176 final String name = findMethodName(m);
177 out.append(prefix).append(name).append(" = ")
178 .append(jc.getName().getInternalName().replace('/', '_'))
179 .append('_').append(name).append(";");
182 private void generateInstanceMethod(Method m) throws IOException {
183 out.append("\nfunction ").append(
184 jc.getName().getInternalName().replace('/', '_')
185 ).append('_').append(findMethodName(m));
188 List<Parameter> args = m.getParameters();
189 for (int index = 1, i = 0; i < args.size(); i++) {
191 out.append("arg").append(String.valueOf(index));
192 final String desc = findDescriptor(args.get(i).getDescriptor());
193 if ("D".equals(desc) || "J".equals(desc)) {
199 out.append(") {").append("\n");
200 final Code code = m.getCode();
202 int len = code.getMaxLocals();
203 for (int index = args.size(), i = args.size(); i < len; i++) {
205 out.append("arg").append(String.valueOf(i + 1)).append(";\n");
207 out.append(";\n var stack = new Array(");
208 out.append(Integer.toString(code.getMaxStack()));
210 produceCode(code.getByteCodes());
212 out.append(" /* no code found for ").append(m.getTypeSignature()).append(" */\n");
217 private void produceCode(byte[] byteCodes) throws IOException {
218 out.append("\n var gt = 0;\n for(;;) switch(gt) {\n");
219 for (int i = 0; i < byteCodes.length; i++) {
221 out.append(" case " + i).append(": ");
222 final int c = (byteCodes[i] + 256) % 256;
229 out.append("stack.push(arg0);");
236 out.append("stack.push(arg1);");
243 out.append("stack.push(arg2);");
250 out.append("stack.push(arg3);");
257 final int indx = (byteCodes[++i] + 256) % 256;
258 out.append("stack.push(arg").append(indx + ");");
266 final int indx = (byteCodes[++i] + 256) % 256;
267 out.append("arg" + indx).append(" = stack.pop()");
275 out.append("arg0 = stack.pop();");
282 out.append("arg1 = stack.pop();");
289 out.append("arg2 = stack.pop();");
296 out.append("arg3 = stack.pop();");
302 out.append("stack.push(stack.pop() + stack.pop());");
308 out.append("{ var tmp = stack.pop(); stack.push(stack.pop() - tmp); }");
314 out.append("stack.push(stack.pop() * stack.pop());");
318 out.append("{ var tmp = stack.pop(); stack.push(Math.floor(stack.pop() / tmp)); }");
322 out.append("{ var tmp = stack.pop(); stack.push(stack.pop() / tmp); }");
326 out.append("stack.push(stack.pop() & stack.pop());");
330 out.append("stack.push(stack.pop() | stack.pop());");
334 out.append("stack.push(stack.pop() ^ stack.pop());");
337 final int varIndx = (byteCodes[++i] + 256) % 256;
338 final int incrBy = (byteCodes[++i] + 256) % 256;
340 out.append("arg" + varIndx).append("++;");
342 out.append("arg" + varIndx).append(" += " + incrBy).append(";");
347 out.append("return;");
354 out.append("return stack.pop();");
365 out.append("/* number conversion */");
371 out.append("stack.push(Math.floor(stack.pop()));");
376 out.append("/* number conversion */");
379 out.append("stack.push(null);");
385 out.append("stack.push(0);");
391 out.append("stack.push(1);");
395 out.append("stack.push(2);");
398 out.append("stack.push(3);");
401 out.append("stack.push(4);");
404 out.append("stack.push(5);");
407 int indx = byteCodes[++i];
408 CPEntry entry = jc.getConstantPool().get(indx);
409 String v = encodeConstant(entry);
410 out.append("stack.push(").append(v).append(");");
415 int indx = readIntArg(byteCodes, i);
416 CPEntry entry = jc.getConstantPool().get(indx);
418 String v = encodeConstant(entry);
419 out.append("stack.push(").append(v).append(");");
427 out.append("{ var delta = stack.pop() - stack.pop(); stack.push(delta < 0 ?-1 : (delta == 0 ? 0 : 1)); }");
431 i = generateIf(byteCodes, i, "==");
435 int indx = i + readIntArg(byteCodes, i);
436 out.append("if (stack.pop() == 0) { gt = " + indx);
437 out.append("; continue; }");
442 int indx = i + readIntArg(byteCodes, i);
443 out.append("if (stack.pop() != 0) { gt = " + indx);
444 out.append("; continue; }");
449 int indx = i + readIntArg(byteCodes, i);
450 out.append("if (stack.pop() < 0) { gt = " + indx);
451 out.append("; continue; }");
456 int indx = i + readIntArg(byteCodes, i);
457 out.append("if (stack.pop() <= 0) { gt = " + indx);
458 out.append("; continue; }");
463 int indx = i + readIntArg(byteCodes, i);
464 out.append("if (stack.pop() > 0) { gt = " + indx);
465 out.append("; continue; }");
470 int indx = i + readIntArg(byteCodes, i);
471 out.append("if (stack.pop() >= 0) { gt = " + indx);
472 out.append("; continue; }");
477 int indx = i + readIntArg(byteCodes, i);
478 out.append("if (stack.pop()) { gt = " + indx);
479 out.append("; continue; }");
484 int indx = i + readIntArg(byteCodes, i);
485 out.append("if (!stack.pop()) { gt = " + indx);
486 out.append("; continue; }");
491 i = generateIf(byteCodes, i, "!=");
494 i = generateIf(byteCodes, i, ">");
497 i = generateIf(byteCodes, i, ">=");
500 i = generateIf(byteCodes, i, "<");
503 i = generateIf(byteCodes, i, "<=");
506 int indx = i + readIntArg(byteCodes, i);
507 out.append("gt = " + indx).append("; continue;");
511 case bc_invokeinterface: {
512 i = invokeVirtualMethod(byteCodes, i) + 2;
515 case bc_invokevirtual:
516 i = invokeVirtualMethod(byteCodes, i);
518 case bc_invokespecial:
519 i = invokeStaticMethod(byteCodes, i, false);
521 case bc_invokestatic:
522 i = invokeStaticMethod(byteCodes, i, true);
525 int indx = readIntArg(byteCodes, i);
526 CPClassInfo ci = jc.getConstantPool().getClass(indx);
527 out.append("stack.push(");
528 out.append("new ").append(ci.getClassName().getInternalName().replace('/','_'));
530 addReference(ci.getClassName().getInternalName());
535 int type = byteCodes[i++];
536 out.append("stack.push(new Array(stack.pop()));");
540 i += 2; // skip type of array
541 out.append("stack.push(new Array(stack.pop()));");
545 out.append("stack.push(stack.pop().length);");
555 out.append("{ var value = stack.pop(); var indx = stack.pop(); stack.pop()[indx] = value; }");
566 out.append("{ var indx = stack.pop(); stack.push(stack.pop()[indx]); }");
570 out.append("stack.push(stack[stack.length - 1]);");
573 out.append("stack.push(" + byteCodes[++i] + ");");
576 out.append("stack.push(" + readIntArg(byteCodes, i) + ");");
580 int indx = readIntArg(byteCodes, i);
581 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
582 out.append("stack.push(stack.pop().").append(fi.getFieldName()).append(");");
587 int indx = readIntArg(byteCodes, i);
588 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
589 final String in = fi.getClassName().getInternalName();
590 out.append("stack.push(").append(in.replace('/', '_'));
591 out.append('_').append(fi.getFieldName()).append(");");
597 int indx = readIntArg(byteCodes, i);
598 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
599 final String in = fi.getClassName().getInternalName();
600 out.append(in.replace('/', '_'));
601 out.append('_').append(fi.getFieldName()).append(" = stack.pop();");
607 int indx = readIntArg(byteCodes, i);
608 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
609 out.append("{ var v = stack.pop(); stack.pop().")
610 .append(fi.getFieldName()).append(" = v; }");
615 int indx = readIntArg(byteCodes, i);
616 CPClassInfo ci = jc.getConstantPool().getClass(indx);
617 final String type = ci.getClassName().getType();
618 if (!type.startsWith("[")) {
619 // no way to check arrays right now
620 out.append("if(stack[stack.length - 1].$instOf_")
621 .append(type.replace('/', '_'))
622 .append(" != 1) throw {};"); // XXX proper exception
627 case bc_instanceof: {
628 int indx = readIntArg(byteCodes, i);
629 CPClassInfo ci = jc.getConstantPool().getClass(indx);
630 out.append("stack.push(stack.pop().$instOf_")
631 .append(ci.getClassName().getInternalName().replace('/', '_'))
632 .append(" ? 1 : 0);");
639 for (int j = prev; j <= i; j++) {
641 final int cc = (byteCodes[j] + 256) % 256;
642 out.append(Integer.toString(cc));
649 private int generateIf(byte[] byteCodes, int i, final String test) throws IOException {
650 int indx = i + readIntArg(byteCodes, i);
651 out.append("if (stack.pop() ").append(test).append(" stack.pop()) { gt = " + indx);
652 out.append("; continue; }");
656 private int readIntArg(byte[] byteCodes, int offsetInstruction) {
657 final int indxHi = byteCodes[offsetInstruction + 1] << 8;
658 final int indxLo = byteCodes[offsetInstruction + 2];
659 return (indxHi & 0xffffff00) | (indxLo & 0xff);
662 private static int countArgs(String descriptor, boolean[] hasReturnType, StringBuilder sig) {
665 Boolean count = null;
666 boolean array = false;
667 int firstPos = sig.length();
668 while (i < descriptor.length()) {
669 char ch = descriptor.charAt(i++);
695 hasReturnType[0] = true;
696 sig.insert(firstPos, ch);
698 sig.insert(firstPos, 'A');
704 hasReturnType[0] = false;
705 sig.insert(firstPos, 'V');
708 int next = descriptor.indexOf(';', i);
715 sig.append(descriptor.substring(i, next).replace('/', '_'));
717 sig.insert(firstPos, descriptor.substring(i, next).replace('/', '_'));
718 sig.insert(firstPos, ch);
720 sig.insert(firstPos, 'A');
722 hasReturnType[0] = true;
730 break; // invalid character
736 private void generateStaticField(Variable v) throws IOException {
738 .append(jc.getName().getInternalName().replace('/', '_'))
739 .append('_').append(v.getName()).append(" = 0;");
742 private String findMethodName(Method m) {
743 StringBuilder name = new StringBuilder();
744 String descr = m.getDescriptor();
745 if ("<init>".equals(m.getName())) { // NOI18N
746 name.append("cons"); // NOI18N
747 } else if ("<clinit>".equals(m.getName())) { // NOI18N
748 name.append("class"); // NOI18N
750 name.append(m.getName());
753 boolean hasReturn[] = { false };
754 countArgs(findDescriptor(m.getDescriptor()), hasReturn, name);
755 return name.toString();
758 private String findMethodName(CPMethodInfo mi, int[] cnt, boolean[] hasReturn) {
759 StringBuilder name = new StringBuilder();
760 String descr = mi.getDescriptor();
761 if ("<init>".equals(mi.getName())) { // NOI18N
762 name.append("cons"); // NOI18N
764 name.append(mi.getName());
766 cnt[0] = countArgs(findDescriptor(mi.getDescriptor()), hasReturn, name);
767 return name.toString();
770 private int invokeStaticMethod(byte[] byteCodes, int i, boolean isStatic)
772 int methodIndex = readIntArg(byteCodes, i);
773 CPMethodInfo mi = (CPMethodInfo) jc.getConstantPool().get(methodIndex);
774 boolean[] hasReturn = { false };
776 String mn = findMethodName(mi, cnt, hasReturn);
778 for (int j = cnt[0] - 1; j >= 0; j--) {
779 out.append("var v" + j).append(" = stack.pop(); ");
783 out.append("stack.push(");
785 final String in = mi.getClassName().getInternalName();
786 out.append(in.replace('/', '_'));
792 out.append("stack.pop()");
795 for (int j = 0; j < cnt[0]; j++) {
809 private int invokeVirtualMethod(byte[] byteCodes, int i)
811 int methodIndex = readIntArg(byteCodes, i);
812 CPMethodInfo mi = (CPMethodInfo) jc.getConstantPool().get(methodIndex);
813 boolean[] hasReturn = { false };
815 String mn = findMethodName(mi, cnt, hasReturn);
817 for (int j = cnt[0] - 1; j >= 0; j--) {
818 out.append("var v" + j).append(" = stack.pop(); ");
820 out.append("var self = stack.pop(); ");
822 out.append("stack.push(");
828 for (int j = 0; j < cnt[0]; j++) {
841 private void addReference(String cn) {
842 if (references != null) {
847 private void outType(String d, StringBuilder out) {
849 while (d.charAt(0) == '[') {
853 if (d.charAt(0) == 'L') {
854 assert d.charAt(d.length() - 1) == ';';
855 out.append(d.replace('/', '_').substring(0, d.length() - 1));
861 private String encodeConstant(CPEntry entry) {
863 if (entry instanceof CPStringInfo) {
864 v = "\"" + entry.getValue().toString().replace("\"", "\\\"") + "\"";
866 v = entry.getValue().toString();
871 private String findDescriptor(String d) {
872 return d.replace('[', 'A');