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);");
382 out.append("stack.push(-1);");
388 out.append("stack.push(0);");
394 out.append("stack.push(1);");
398 out.append("stack.push(2);");
401 out.append("stack.push(3);");
404 out.append("stack.push(4);");
407 out.append("stack.push(5);");
410 int indx = byteCodes[++i];
411 CPEntry entry = jc.getConstantPool().get(indx);
412 String v = encodeConstant(entry);
413 out.append("stack.push(").append(v).append(");");
418 int indx = readIntArg(byteCodes, i);
419 CPEntry entry = jc.getConstantPool().get(indx);
421 String v = encodeConstant(entry);
422 out.append("stack.push(").append(v).append(");");
430 out.append("{ var delta = stack.pop() - stack.pop(); stack.push(delta < 0 ?-1 : (delta == 0 ? 0 : 1)); }");
434 i = generateIf(byteCodes, i, "==");
438 int indx = i + readIntArg(byteCodes, i);
439 out.append("if (stack.pop() == 0) { gt = " + indx);
440 out.append("; continue; }");
445 int indx = i + readIntArg(byteCodes, i);
446 out.append("if (stack.pop() != 0) { gt = " + indx);
447 out.append("; continue; }");
452 int indx = i + readIntArg(byteCodes, i);
453 out.append("if (stack.pop() < 0) { gt = " + indx);
454 out.append("; continue; }");
459 int indx = i + readIntArg(byteCodes, i);
460 out.append("if (stack.pop() <= 0) { gt = " + indx);
461 out.append("; continue; }");
466 int indx = i + readIntArg(byteCodes, i);
467 out.append("if (stack.pop() > 0) { gt = " + indx);
468 out.append("; continue; }");
473 int indx = i + readIntArg(byteCodes, i);
474 out.append("if (stack.pop() >= 0) { gt = " + indx);
475 out.append("; continue; }");
480 int indx = i + readIntArg(byteCodes, i);
481 out.append("if (stack.pop()) { gt = " + indx);
482 out.append("; continue; }");
487 int indx = i + readIntArg(byteCodes, i);
488 out.append("if (!stack.pop()) { gt = " + indx);
489 out.append("; continue; }");
494 i = generateIf(byteCodes, i, "!=");
497 i = generateIf(byteCodes, i, ">");
500 i = generateIf(byteCodes, i, ">=");
503 i = generateIf(byteCodes, i, "<");
506 i = generateIf(byteCodes, i, "<=");
509 int indx = i + readIntArg(byteCodes, i);
510 out.append("gt = " + indx).append("; continue;");
514 case bc_invokeinterface: {
515 i = invokeVirtualMethod(byteCodes, i) + 2;
518 case bc_invokevirtual:
519 i = invokeVirtualMethod(byteCodes, i);
521 case bc_invokespecial:
522 i = invokeStaticMethod(byteCodes, i, false);
524 case bc_invokestatic:
525 i = invokeStaticMethod(byteCodes, i, true);
528 int indx = readIntArg(byteCodes, i);
529 CPClassInfo ci = jc.getConstantPool().getClass(indx);
530 out.append("stack.push(");
531 out.append("new ").append(ci.getClassName().getInternalName().replace('/','_'));
533 addReference(ci.getClassName().getInternalName());
538 int type = byteCodes[i++];
539 out.append("stack.push(new Array(stack.pop()));");
543 i += 2; // skip type of array
544 out.append("stack.push(new Array(stack.pop()));");
548 out.append("stack.push(stack.pop().length);");
558 out.append("{ var value = stack.pop(); var indx = stack.pop(); stack.pop()[indx] = value; }");
569 out.append("{ var indx = stack.pop(); stack.push(stack.pop()[indx]); }");
573 out.append("stack.push(stack[stack.length - 1]);");
576 out.append("stack.push(" + byteCodes[++i] + ");");
579 out.append("stack.push(" + readIntArg(byteCodes, i) + ");");
583 int indx = readIntArg(byteCodes, i);
584 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
585 out.append("stack.push(stack.pop().").append(fi.getFieldName()).append(");");
590 int indx = readIntArg(byteCodes, i);
591 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
592 final String in = fi.getClassName().getInternalName();
593 out.append("stack.push(").append(in.replace('/', '_'));
594 out.append('_').append(fi.getFieldName()).append(");");
600 int indx = readIntArg(byteCodes, i);
601 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
602 final String in = fi.getClassName().getInternalName();
603 out.append(in.replace('/', '_'));
604 out.append('_').append(fi.getFieldName()).append(" = stack.pop();");
610 int indx = readIntArg(byteCodes, i);
611 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
612 out.append("{ var v = stack.pop(); stack.pop().")
613 .append(fi.getFieldName()).append(" = v; }");
618 int indx = readIntArg(byteCodes, i);
619 CPClassInfo ci = jc.getConstantPool().getClass(indx);
620 final String type = ci.getClassName().getType();
621 if (!type.startsWith("[")) {
622 // no way to check arrays right now
623 out.append("if(stack[stack.length - 1].$instOf_")
624 .append(type.replace('/', '_'))
625 .append(" != 1) throw {};"); // XXX proper exception
630 case bc_instanceof: {
631 int indx = readIntArg(byteCodes, i);
632 CPClassInfo ci = jc.getConstantPool().getClass(indx);
633 out.append("stack.push(stack.pop().$instOf_")
634 .append(ci.getClassName().getInternalName().replace('/', '_'))
635 .append(" ? 1 : 0);");
642 for (int j = prev; j <= i; j++) {
644 final int cc = (byteCodes[j] + 256) % 256;
645 out.append(Integer.toString(cc));
652 private int generateIf(byte[] byteCodes, int i, final String test) throws IOException {
653 int indx = i + readIntArg(byteCodes, i);
654 out.append("if (stack.pop() ").append(test).append(" stack.pop()) { gt = " + indx);
655 out.append("; continue; }");
659 private int readIntArg(byte[] byteCodes, int offsetInstruction) {
660 final int indxHi = byteCodes[offsetInstruction + 1] << 8;
661 final int indxLo = byteCodes[offsetInstruction + 2];
662 return (indxHi & 0xffffff00) | (indxLo & 0xff);
665 private static int countArgs(String descriptor, boolean[] hasReturnType, StringBuilder sig) {
668 Boolean count = null;
669 boolean array = false;
670 int firstPos = sig.length();
671 while (i < descriptor.length()) {
672 char ch = descriptor.charAt(i++);
698 hasReturnType[0] = true;
699 sig.insert(firstPos, ch);
701 sig.insert(firstPos, 'A');
707 hasReturnType[0] = false;
708 sig.insert(firstPos, 'V');
711 int next = descriptor.indexOf(';', i);
718 sig.append(descriptor.substring(i, next).replace('/', '_'));
720 sig.insert(firstPos, descriptor.substring(i, next).replace('/', '_'));
721 sig.insert(firstPos, ch);
723 sig.insert(firstPos, 'A');
725 hasReturnType[0] = true;
733 break; // invalid character
739 private void generateStaticField(Variable v) throws IOException {
741 .append(jc.getName().getInternalName().replace('/', '_'))
742 .append('_').append(v.getName()).append(" = 0;");
745 private String findMethodName(Method m) {
746 StringBuilder name = new StringBuilder();
747 String descr = m.getDescriptor();
748 if ("<init>".equals(m.getName())) { // NOI18N
749 name.append("cons"); // NOI18N
750 } else if ("<clinit>".equals(m.getName())) { // NOI18N
751 name.append("class"); // NOI18N
753 name.append(m.getName());
756 boolean hasReturn[] = { false };
757 countArgs(findDescriptor(m.getDescriptor()), hasReturn, name);
758 return name.toString();
761 private String findMethodName(CPMethodInfo mi, int[] cnt, boolean[] hasReturn) {
762 StringBuilder name = new StringBuilder();
763 String descr = mi.getDescriptor();
764 if ("<init>".equals(mi.getName())) { // NOI18N
765 name.append("cons"); // NOI18N
767 name.append(mi.getName());
769 cnt[0] = countArgs(findDescriptor(mi.getDescriptor()), hasReturn, name);
770 return name.toString();
773 private int invokeStaticMethod(byte[] byteCodes, int i, boolean isStatic)
775 int methodIndex = readIntArg(byteCodes, i);
776 CPMethodInfo mi = (CPMethodInfo) jc.getConstantPool().get(methodIndex);
777 boolean[] hasReturn = { false };
779 String mn = findMethodName(mi, cnt, hasReturn);
781 for (int j = cnt[0] - 1; j >= 0; j--) {
782 out.append("var v" + j).append(" = stack.pop(); ");
786 out.append("stack.push(");
788 final String in = mi.getClassName().getInternalName();
789 out.append(in.replace('/', '_'));
795 out.append("stack.pop()");
798 for (int j = 0; j < cnt[0]; j++) {
812 private int invokeVirtualMethod(byte[] byteCodes, int i)
814 int methodIndex = readIntArg(byteCodes, i);
815 CPMethodInfo mi = (CPMethodInfo) jc.getConstantPool().get(methodIndex);
816 boolean[] hasReturn = { false };
818 String mn = findMethodName(mi, cnt, hasReturn);
820 for (int j = cnt[0] - 1; j >= 0; j--) {
821 out.append("var v" + j).append(" = stack.pop(); ");
823 out.append("var self = stack.pop(); ");
825 out.append("stack.push(");
831 for (int j = 0; j < cnt[0]; j++) {
844 private void addReference(String cn) {
845 if (references != null) {
850 private void outType(String d, StringBuilder out) {
852 while (d.charAt(0) == '[') {
856 if (d.charAt(0) == 'L') {
857 assert d.charAt(d.length() - 1) == ';';
858 out.append(d.replace('/', '_').substring(0, d.length() - 1));
864 private String encodeConstant(CPEntry entry) {
866 if (entry instanceof CPStringInfo) {
867 v = "\"" + entry.getValue().toString().replace("\"", "\\\"") + "\"";
869 v = entry.getValue().toString();
874 private String findDescriptor(String d) {
875 return d.replace('[', 'A');