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 && "const=0".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());");
340 out.append("stack.push(- stack.pop());");
344 out.append("{ var v = stack.pop(); stack.push(stack.pop() << v); }");
348 out.append("{ var v = stack.pop(); stack.push(stack.pop() >> v); }");
352 out.append("{ var v = stack.pop(); stack.push(stack.pop() >>> v); }");
355 final int varIndx = (byteCodes[++i] + 256) % 256;
356 final int incrBy = (byteCodes[++i] + 256) % 256;
358 out.append("arg" + varIndx).append("++;");
360 out.append("arg" + varIndx).append(" += " + incrBy).append(";");
365 out.append("return;");
372 out.append("return stack.pop();");
383 out.append("/* number conversion */");
389 out.append("stack.push(Math.floor(stack.pop()));");
394 out.append("/* number conversion */");
397 out.append("stack.push(null);");
400 out.append("stack.push(-1);");
406 out.append("stack.push(0);");
412 out.append("stack.push(1);");
416 out.append("stack.push(2);");
419 out.append("stack.push(3);");
422 out.append("stack.push(4);");
425 out.append("stack.push(5);");
428 int indx = byteCodes[++i];
429 CPEntry entry = jc.getConstantPool().get(indx);
430 String v = encodeConstant(entry);
431 out.append("stack.push(").append(v).append(");");
436 int indx = readIntArg(byteCodes, i);
437 CPEntry entry = jc.getConstantPool().get(indx);
439 String v = encodeConstant(entry);
440 out.append("stack.push(").append(v).append(");");
448 out.append("{ var delta = stack.pop() - stack.pop(); stack.push(delta < 0 ?-1 : (delta == 0 ? 0 : 1)); }");
452 i = generateIf(byteCodes, i, "==");
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() <= 0) { gt = " + indx);
479 out.append("; continue; }");
484 int indx = i + readIntArg(byteCodes, i);
485 out.append("if (stack.pop() > 0) { gt = " + indx);
486 out.append("; continue; }");
491 int indx = i + readIntArg(byteCodes, i);
492 out.append("if (stack.pop() >= 0) { gt = " + indx);
493 out.append("; continue; }");
498 int indx = i + readIntArg(byteCodes, i);
499 out.append("if (stack.pop()) { gt = " + indx);
500 out.append("; continue; }");
505 int indx = i + readIntArg(byteCodes, i);
506 out.append("if (!stack.pop()) { gt = " + indx);
507 out.append("; continue; }");
512 i = generateIf(byteCodes, i, "!=");
515 i = generateIf(byteCodes, i, ">");
518 i = generateIf(byteCodes, i, ">=");
521 i = generateIf(byteCodes, i, "<");
524 i = generateIf(byteCodes, i, "<=");
527 int indx = i + readIntArg(byteCodes, i);
528 out.append("gt = " + indx).append("; continue;");
532 case bc_invokeinterface: {
533 i = invokeVirtualMethod(byteCodes, i) + 2;
536 case bc_invokevirtual:
537 i = invokeVirtualMethod(byteCodes, i);
539 case bc_invokespecial:
540 i = invokeStaticMethod(byteCodes, i, false);
542 case bc_invokestatic:
543 i = invokeStaticMethod(byteCodes, i, true);
546 int indx = readIntArg(byteCodes, i);
547 CPClassInfo ci = jc.getConstantPool().getClass(indx);
548 out.append("stack.push(");
549 out.append("new ").append(ci.getClassName().getInternalName().replace('/','_'));
551 addReference(ci.getClassName().getInternalName());
556 int type = byteCodes[i++];
557 out.append("stack.push(new Array(stack.pop()));");
561 i += 2; // skip type of array
562 out.append("stack.push(new Array(stack.pop()));");
566 out.append("stack.push(stack.pop().length);");
576 out.append("{ var value = stack.pop(); var indx = stack.pop(); stack.pop()[indx] = value; }");
587 out.append("{ var indx = stack.pop(); stack.push(stack.pop()[indx]); }");
591 out.append("stack.pop();");
593 out.append("stack.pop();");
596 out.append("stack.push(stack[stack.length - 1]);");
599 out.append("stack.push(" + byteCodes[++i] + ");");
602 out.append("stack.push(" + readIntArg(byteCodes, i) + ");");
606 int indx = readIntArg(byteCodes, i);
607 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
608 out.append("stack.push(stack.pop().").append(fi.getFieldName()).append(");");
613 int indx = readIntArg(byteCodes, i);
614 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
615 final String in = fi.getClassName().getInternalName();
616 out.append("stack.push(").append(in.replace('/', '_'));
617 out.append('_').append(fi.getFieldName()).append(");");
623 int indx = readIntArg(byteCodes, i);
624 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
625 final String in = fi.getClassName().getInternalName();
626 out.append(in.replace('/', '_'));
627 out.append('_').append(fi.getFieldName()).append(" = stack.pop();");
633 int indx = readIntArg(byteCodes, i);
634 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
635 out.append("{ var v = stack.pop(); stack.pop().")
636 .append(fi.getFieldName()).append(" = v; }");
641 int indx = readIntArg(byteCodes, i);
642 CPClassInfo ci = jc.getConstantPool().getClass(indx);
643 final String type = ci.getClassName().getType();
644 if (!type.startsWith("[")) {
645 // no way to check arrays right now
646 out.append("if(stack[stack.length - 1].$instOf_")
647 .append(type.replace('/', '_'))
648 .append(" != 1) throw {};"); // XXX proper exception
653 case bc_instanceof: {
654 int indx = readIntArg(byteCodes, i);
655 CPClassInfo ci = jc.getConstantPool().getClass(indx);
656 out.append("stack.push(stack.pop().$instOf_")
657 .append(ci.getClassName().getInternalName().replace('/', '_'))
658 .append(" ? 1 : 0);");
665 for (int j = prev; j <= i; j++) {
667 final int cc = (byteCodes[j] + 256) % 256;
668 out.append(Integer.toString(cc));
675 private int generateIf(byte[] byteCodes, int i, final String test) throws IOException {
676 int indx = i + readIntArg(byteCodes, i);
677 out.append("if (stack.pop() ").append(test).append(" stack.pop()) { gt = " + indx);
678 out.append("; continue; }");
682 private int readIntArg(byte[] byteCodes, int offsetInstruction) {
683 final int indxHi = byteCodes[offsetInstruction + 1] << 8;
684 final int indxLo = byteCodes[offsetInstruction + 2];
685 return (indxHi & 0xffffff00) | (indxLo & 0xff);
688 private static int countArgs(String descriptor, boolean[] hasReturnType, StringBuilder sig) {
691 Boolean count = null;
692 boolean array = false;
693 int firstPos = sig.length();
694 while (i < descriptor.length()) {
695 char ch = descriptor.charAt(i++);
721 hasReturnType[0] = true;
722 sig.insert(firstPos, ch);
724 sig.insert(firstPos, 'A');
731 hasReturnType[0] = false;
732 sig.insert(firstPos, 'V');
735 int next = descriptor.indexOf(';', i);
742 sig.append(descriptor.substring(i, next).replace('/', '_'));
744 sig.insert(firstPos, descriptor.substring(i, next).replace('/', '_'));
745 sig.insert(firstPos, ch);
747 sig.insert(firstPos, 'A');
749 hasReturnType[0] = true;
757 break; // invalid character
763 private void generateStaticField(Variable v) throws IOException {
765 .append(jc.getName().getInternalName().replace('/', '_'))
766 .append('_').append(v.getName()).append(" = 0;");
769 private String findMethodName(Method m) {
770 StringBuilder name = new StringBuilder();
771 String descr = m.getDescriptor();
772 if ("<init>".equals(m.getName())) { // NOI18N
773 name.append("cons"); // NOI18N
774 } else if ("<clinit>".equals(m.getName())) { // NOI18N
775 name.append("class"); // NOI18N
777 name.append(m.getName());
780 boolean hasReturn[] = { false };
781 countArgs(findDescriptor(m.getDescriptor()), hasReturn, name);
782 return name.toString();
785 private String findMethodName(CPMethodInfo mi, int[] cnt, boolean[] hasReturn) {
786 StringBuilder name = new StringBuilder();
787 String descr = mi.getDescriptor();
788 if ("<init>".equals(mi.getName())) { // NOI18N
789 name.append("cons"); // NOI18N
791 name.append(mi.getName());
793 cnt[0] = countArgs(findDescriptor(mi.getDescriptor()), hasReturn, name);
794 return name.toString();
797 private int invokeStaticMethod(byte[] byteCodes, int i, boolean isStatic)
799 int methodIndex = readIntArg(byteCodes, i);
800 CPMethodInfo mi = (CPMethodInfo) jc.getConstantPool().get(methodIndex);
801 boolean[] hasReturn = { false };
803 String mn = findMethodName(mi, cnt, hasReturn);
805 for (int j = cnt[0] - 1; j >= 0; j--) {
806 out.append("var v" + j).append(" = stack.pop(); ");
810 out.append("stack.push(");
812 final String in = mi.getClassName().getInternalName();
813 out.append(in.replace('/', '_'));
819 out.append("stack.pop()");
822 for (int j = 0; j < cnt[0]; j++) {
836 private int invokeVirtualMethod(byte[] byteCodes, int i)
838 int methodIndex = readIntArg(byteCodes, i);
839 CPMethodInfo mi = (CPMethodInfo) jc.getConstantPool().get(methodIndex);
840 boolean[] hasReturn = { false };
842 String mn = findMethodName(mi, cnt, hasReturn);
844 for (int j = cnt[0] - 1; j >= 0; j--) {
845 out.append("var v" + j).append(" = stack.pop(); ");
847 out.append("var self = stack.pop(); ");
849 out.append("stack.push(");
855 for (int j = 0; j < cnt[0]; j++) {
868 private void addReference(String cn) {
869 if (references != null) {
874 private void outType(String d, StringBuilder out) {
876 while (d.charAt(0) == '[') {
880 if (d.charAt(0) == 'L') {
881 assert d.charAt(d.length() - 1) == ';';
882 out.append(d.replace('/', '_').substring(0, d.length() - 1));
888 private String encodeConstant(CPEntry entry) {
890 if (entry instanceof CPClassInfo) {
891 v = "new java_lang_Class";
892 } else if (entry instanceof CPStringInfo) {
893 v = "\"" + entry.getValue().toString().replace("\"", "\\\"") + "\"";
895 v = entry.getValue().toString();
900 private String findDescriptor(String d) {
901 return d.replace('[', 'A');