Fixing unit test.
2 * Back 2 Browser Bytecode Translator
3 * Copyright (C) 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.
19 Java 4 Browser Bytecode Translator
20 Copyright (C) 2012-2012 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
22 This program is free software: you can redistribute it and/or modify
23 it under the terms of the GNU General Public License as published by
24 the Free Software Foundation, version 2 of the License.
26 This program is distributed in the hope that it will be useful,
27 but WITHOUT ANY WARRANTY; without even the implied warranty of
28 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
29 GNU General Public License for more details.
31 You should have received a copy of the GNU General Public License
32 along with this program. Look for COPYING file in the top folder.
33 If not, see http://opensource.org/licenses/GPL-2.0.
35 package org.apidesign.vm4brwsr;
37 import java.io.IOException;
38 import java.io.InputStream;
39 import java.util.ArrayDeque;
40 import java.util.ArrayList;
41 import java.util.Collection;
42 import java.util.Deque;
43 import java.util.HashMap;
44 import java.util.List;
46 import org.apidesign.bck2brwsr.core.ExtraJavaScript;
47 import org.apidesign.bck2brwsr.core.JavaScriptBody;
48 import org.netbeans.modules.classfile.Annotation;
49 import org.netbeans.modules.classfile.AnnotationComponent;
50 import org.netbeans.modules.classfile.ArrayElementValue;
51 import static org.netbeans.modules.classfile.ByteCodes.*;
52 import org.netbeans.modules.classfile.CPClassInfo;
53 import org.netbeans.modules.classfile.CPEntry;
54 import org.netbeans.modules.classfile.CPFieldInfo;
55 import org.netbeans.modules.classfile.CPMethodInfo;
56 import org.netbeans.modules.classfile.CPStringInfo;
57 import org.netbeans.modules.classfile.ClassFile;
58 import org.netbeans.modules.classfile.ClassName;
59 import org.netbeans.modules.classfile.Code;
60 import org.netbeans.modules.classfile.ElementValue;
61 import org.netbeans.modules.classfile.ExceptionTableEntry;
62 import org.netbeans.modules.classfile.Method;
63 import org.netbeans.modules.classfile.Parameter;
64 import org.netbeans.modules.classfile.PrimitiveElementValue;
65 import org.netbeans.modules.classfile.Variable;
67 /** Translator of the code inside class files to JavaScript.
69 * @author Jaroslav Tulach <jtulach@netbeans.org>
71 public final class ByteCodeToJavaScript {
72 private final ClassFile jc;
73 private final Appendable out;
74 private final Collection<? super String> references;
76 private ByteCodeToJavaScript(
77 ClassFile jc, Appendable out, Collection<? super String> references
81 this.references = references;
85 * Converts a given class file to a JavaScript version.
87 * @param classFile input stream with code of the .class file
88 * @param out a {@link StringBuilder} or similar to generate the output to
89 * @param references a write only collection where the system adds list of
90 * other classes that were referenced and should be loaded in order the
91 * generated JavaScript code works properly. The names are in internal
92 * JVM form so String is <code>java/lang/String</code>. Can be <code>null</code>
93 * if one is not interested in knowing references
94 * @param scripts write only collection with names of resources to read
95 * @return the initialization code for this class, if any. Otherwise <code>null</code>
97 * @throws IOException if something goes wrong during read or write or translating
100 public static String compile(
101 InputStream classFile, Appendable out,
102 Collection<? super String> references,
103 Collection<? super String> scripts
104 ) throws IOException {
105 ClassFile jc = new ClassFile(classFile, true);
106 final ClassName extraAnn = ClassName.getClassName(ExtraJavaScript.class.getName().replace('.', '/'));
107 Annotation a = jc.getAnnotation(extraAnn);
109 final ElementValue annVal = a.getComponent("resource").getValue();
110 String res = ((PrimitiveElementValue)annVal).getValue().getValue().toString();
112 final AnnotationComponent process = a.getComponent("processByteCode");
113 if (process != null && "const=0".equals(process.getValue().toString())) {
118 ByteCodeToJavaScript compiler = new ByteCodeToJavaScript(
121 List<String> toInitilize = new ArrayList<String>();
122 for (Method m : jc.getMethods()) {
124 compiler.generateStaticMethod(m, toInitilize);
126 compiler.generateInstanceMethod(m);
129 for (Variable v : jc.getVariables()) {
131 compiler.generateStaticField(v);
135 final String className = jc.getName().getInternalName().replace('/', '_');
136 out.append("\nfunction ").append(className);
138 for (Variable v : jc.getVariables()) {
140 out.append("\n this." + v.getName() + " = 0;");
143 out.append("\n}\n\nfunction ").append(className).append("_proto() {");
144 out.append("\n if (").append(className).
145 append(".prototype.$instOf_").append(className).append(") {");
146 out.append("\n return ").append(className).append(".prototype;");
148 ClassName sc = jc.getSuperClass();
150 out.append("\n ").append(sc.getInternalName().replace('/', '_')).append("_proto();");
151 out.append("\n ").append(className)
152 .append(".prototype = new ").append(sc.getInternalName().replace('/', '_')).append(';');
154 for (Method m : jc.getMethods()) {
155 if (!m.getName().contains("<init>") && !m.getName().contains("<cinit>")) {
156 compiler.generateMethodReference("\n " + className + ".prototype.", m);
159 out.append("\n " + className + ".prototype.$instOf_").append(className).append(" = true;");
160 for (ClassName superInterface : jc.getInterfaces()) {
161 out.append("\n " + className + ".prototype.$instOf_").append(superInterface.getInternalName().replace('/', '_')).append(" = true;");
163 out.append("\n return ").append(className).append(".prototype;");
165 out.append("\n").append(className).append("_proto();");
166 StringBuilder sb = new StringBuilder();
167 for (String init : toInitilize) {
168 sb.append("\n").append(init).append("();");
170 return sb.toString();
172 private void generateStaticMethod(Method m, List<String> toInitilize) throws IOException {
173 if (javaScriptBody(m, true)) {
176 final String mn = findMethodName(m);
177 out.append("\nfunction ").append(
178 jc.getName().getInternalName().replace('/', '_')
179 ).append('_').append(mn);
180 if (mn.equals("classV")) {
181 toInitilize.add(jc.getName().getInternalName().replace('/', '_') + '_' + mn);
185 List<Parameter> args = m.getParameters();
186 for (int index = 0, i = 0; i < args.size(); i++) {
188 out.append("arg").append(String.valueOf(index));
190 final String desc = findDescriptor(args.get(i).getDescriptor());
191 if ("D".equals(desc) || "J".equals(desc)) {
197 out.append(") {").append("\n");
198 final Code code = m.getCode();
200 int len = code.getMaxLocals();
201 for (int index = args.size(), i = args.size(); i < len; i++) {
203 out.append("arg").append(String.valueOf(i)).append(";\n");
205 out.append(" var stack = new Array();\n");
206 produceCode(code.getByteCodes(), code.getExceptionTable());
208 out.append(" /* no code found for ").append(m.getTypeSignature()).append(" */\n");
213 private void generateMethodReference(String prefix, Method m) throws IOException {
214 final String name = findMethodName(m);
215 out.append(prefix).append(name).append(" = ")
216 .append(jc.getName().getInternalName().replace('/', '_'))
217 .append('_').append(name).append(";");
220 private void generateInstanceMethod(Method m) throws IOException {
221 if (javaScriptBody(m, false)) {
224 out.append("\nfunction ").append(
225 jc.getName().getInternalName().replace('/', '_')
226 ).append('_').append(findMethodName(m));
229 List<Parameter> args = m.getParameters();
230 for (int index = 1, i = 0; i < args.size(); i++) {
232 out.append("arg").append(String.valueOf(index));
233 final String desc = findDescriptor(args.get(i).getDescriptor());
234 if ("D".equals(desc) || "J".equals(desc)) {
240 out.append(") {").append("\n");
241 final Code code = m.getCode();
243 int len = code.getMaxLocals();
244 for (int index = args.size(), i = args.size(); i < len; i++) {
246 out.append("arg").append(String.valueOf(i + 1)).append(";\n");
248 out.append(";\n var stack = new Array();\n");
249 produceCode(code.getByteCodes(), code.getExceptionTable());
251 out.append(" /* no code found for ").append(m.getTypeSignature()).append(" */\n");
256 private void produceCode(byte[] byteCodes, ExceptionTableEntry[] exceptionTable) throws IOException {
257 final Map<Integer, ExceptionTableEntry> exStart = new HashMap<Integer, ExceptionTableEntry>();
258 final Map<Integer, ExceptionTableEntry> exStop = new HashMap<Integer, ExceptionTableEntry>();
259 for (ExceptionTableEntry e : exceptionTable) {
260 exStart.put(e.getStartPC(), e);
261 exStop.put(e.getEndPC(), e);
263 final Deque<ExceptionTableEntry> current = new ArrayDeque<ExceptionTableEntry>();
264 out.append("\n var gt = 0;\n for(;;) switch(gt) {\n");
265 for (int i = 0; i < byteCodes.length; i++) {
267 ExceptionTableEntry e = exStart.get(i);
277 out.append(" case " + i).append(": ");
278 if (!current.isEmpty()) {
281 final int c = (byteCodes[i] + 256) % 256;
288 out.append("stack.push(arg0);");
295 out.append("stack.push(arg1);");
302 out.append("stack.push(arg2);");
309 out.append("stack.push(arg3);");
316 final int indx = (byteCodes[++i] + 256) % 256;
317 out.append("stack.push(arg").append(indx + ");");
325 final int indx = (byteCodes[++i] + 256) % 256;
326 out.append("arg" + indx).append(" = stack.pop()");
334 out.append("arg0 = stack.pop();");
341 out.append("arg1 = stack.pop();");
348 out.append("arg2 = stack.pop();");
355 out.append("arg3 = stack.pop();");
361 out.append("stack.push(stack.pop() + stack.pop());");
367 out.append("{ var tmp = stack.pop(); stack.push(stack.pop() - tmp); }");
373 out.append("stack.push(stack.pop() * stack.pop());");
377 out.append("{ var tmp = stack.pop(); stack.push(Math.floor(stack.pop() / tmp)); }");
381 out.append("{ var tmp = stack.pop(); stack.push(stack.pop() / tmp); }");
385 out.append("stack.push(stack.pop() & stack.pop());");
389 out.append("stack.push(stack.pop() | stack.pop());");
393 out.append("stack.push(stack.pop() ^ stack.pop());");
399 out.append("stack.push(- stack.pop());");
403 out.append("{ var v = stack.pop(); stack.push(stack.pop() << v); }");
407 out.append("{ var v = stack.pop(); stack.push(stack.pop() >> v); }");
411 out.append("{ var v = stack.pop(); stack.push(stack.pop() >>> v); }");
414 final int varIndx = (byteCodes[++i] + 256) % 256;
415 final int incrBy = byteCodes[++i];
417 out.append("arg" + varIndx).append("++;");
419 out.append("arg" + varIndx).append(" += " + incrBy).append(";");
424 out.append("return;");
431 out.append("return stack.pop();");
442 out.append("/* number conversion */");
448 out.append("stack.push(Math.floor(stack.pop()));");
453 out.append("/* number conversion */");
456 out.append("stack.push(null);");
459 out.append("stack.push(-1);");
465 out.append("stack.push(0);");
471 out.append("stack.push(1);");
475 out.append("stack.push(2);");
478 out.append("stack.push(3);");
481 out.append("stack.push(4);");
484 out.append("stack.push(5);");
487 int indx = byteCodes[++i];
488 CPEntry entry = jc.getConstantPool().get(indx);
489 String v = encodeConstant(entry);
490 out.append("stack.push(").append(v).append(");");
495 int indx = readIntArg(byteCodes, i);
496 CPEntry entry = jc.getConstantPool().get(indx);
498 String v = encodeConstant(entry);
499 out.append("stack.push(").append(v).append(");");
507 out.append("{ var delta = stack.pop() - stack.pop(); stack.push(delta < 0 ?-1 : (delta == 0 ? 0 : 1)); }");
511 i = generateIf(byteCodes, i, "===");
514 i = generateIf(byteCodes, i, "!=");
517 i = generateIf(byteCodes, i, "==");
521 int indx = i + readIntArg(byteCodes, i);
522 out.append("if (stack.pop() == 0) { gt = " + indx);
523 out.append("; continue; }");
528 int indx = i + readIntArg(byteCodes, i);
529 out.append("if (stack.pop() != 0) { gt = " + indx);
530 out.append("; continue; }");
535 int indx = i + readIntArg(byteCodes, i);
536 out.append("if (stack.pop() < 0) { gt = " + indx);
537 out.append("; continue; }");
542 int indx = i + readIntArg(byteCodes, i);
543 out.append("if (stack.pop() <= 0) { gt = " + indx);
544 out.append("; continue; }");
549 int indx = i + readIntArg(byteCodes, i);
550 out.append("if (stack.pop() > 0) { gt = " + indx);
551 out.append("; continue; }");
556 int indx = i + readIntArg(byteCodes, i);
557 out.append("if (stack.pop() >= 0) { gt = " + indx);
558 out.append("; continue; }");
563 int indx = i + readIntArg(byteCodes, i);
564 out.append("if (stack.pop()) { gt = " + indx);
565 out.append("; continue; }");
570 int indx = i + readIntArg(byteCodes, i);
571 out.append("if (!stack.pop()) { gt = " + indx);
572 out.append("; continue; }");
577 i = generateIf(byteCodes, i, "!=");
580 i = generateIf(byteCodes, i, ">");
583 i = generateIf(byteCodes, i, ">=");
586 i = generateIf(byteCodes, i, "<");
589 i = generateIf(byteCodes, i, "<=");
592 int indx = i + readIntArg(byteCodes, i);
593 out.append("gt = " + indx).append("; continue;");
597 case bc_invokeinterface: {
598 i = invokeVirtualMethod(byteCodes, i) + 2;
601 case bc_invokevirtual:
602 i = invokeVirtualMethod(byteCodes, i);
604 case bc_invokespecial:
605 i = invokeStaticMethod(byteCodes, i, false);
607 case bc_invokestatic:
608 i = invokeStaticMethod(byteCodes, i, true);
611 int indx = readIntArg(byteCodes, i);
612 CPClassInfo ci = jc.getConstantPool().getClass(indx);
613 out.append("stack.push(");
614 out.append("new ").append(ci.getClassName().getInternalName().replace('/','_'));
616 addReference(ci.getClassName().getInternalName());
621 int type = byteCodes[i++];
622 out.append("stack.push(new Array(stack.pop()));");
626 i += 2; // skip type of array
627 out.append("stack.push(new Array(stack.pop()));");
631 out.append("stack.push(stack.pop().length);");
641 out.append("{ var value = stack.pop(); var indx = stack.pop(); stack.pop()[indx] = value; }");
652 out.append("{ var indx = stack.pop(); stack.push(stack.pop()[indx]); }");
656 out.append("stack.pop();");
658 out.append("stack.pop();");
661 out.append("stack.push(stack[stack.length - 1]);");
664 out.append("stack.push(" + byteCodes[++i] + ");");
667 out.append("stack.push(" + readIntArg(byteCodes, i) + ");");
671 int indx = readIntArg(byteCodes, i);
672 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
673 out.append("stack.push(stack.pop().").append(fi.getFieldName()).append(");");
678 int indx = readIntArg(byteCodes, i);
679 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
680 final String in = fi.getClassName().getInternalName();
681 out.append("stack.push(").append(in.replace('/', '_'));
682 out.append('_').append(fi.getFieldName()).append(");");
688 int indx = readIntArg(byteCodes, i);
689 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
690 final String in = fi.getClassName().getInternalName();
691 out.append(in.replace('/', '_'));
692 out.append('_').append(fi.getFieldName()).append(" = stack.pop();");
698 int indx = readIntArg(byteCodes, i);
699 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
700 out.append("{ var v = stack.pop(); stack.pop().")
701 .append(fi.getFieldName()).append(" = v; }");
706 int indx = readIntArg(byteCodes, i);
707 CPClassInfo ci = jc.getConstantPool().getClass(indx);
708 final String type = ci.getClassName().getType();
709 if (!type.startsWith("[")) {
710 // no way to check arrays right now
711 out.append("if(stack[stack.length - 1].$instOf_")
712 .append(type.replace('/', '_'))
713 .append(" != 1) throw {};"); // XXX proper exception
718 case bc_instanceof: {
719 int indx = readIntArg(byteCodes, i);
720 CPClassInfo ci = jc.getConstantPool().getClass(indx);
721 out.append("stack.push(stack.pop().$instOf_")
722 .append(ci.getClassName().getInternalName().replace('/', '_'))
723 .append(" ? 1 : 0);");
728 out.append("{ var t = stack.pop(); stack = new Array(1); stack[0] = t; throw t; }");
732 out.append("throw 'unknown bytecode " + c + "';");
736 if (!current.isEmpty()) {
737 out.append("} catch (e) {");
738 for (ExceptionTableEntry e : current) {
739 if (e.getCatchType() != null) {
740 final String classInternalName = e.getCatchType().getClassName().getInternalName();
741 addReference(classInternalName);
742 out.append("if (e.$instOf_"+classInternalName.replace('/', '_')+") {");
743 out.append("gt="+e.getHandlerPC()+"; continue;");
749 out.append("throw e;");
753 for (int j = prev; j <= i; j++) {
755 final int cc = (byteCodes[j] + 256) % 256;
756 out.append(Integer.toString(cc));
763 private int generateIf(byte[] byteCodes, int i, final String test) throws IOException {
764 int indx = i + readIntArg(byteCodes, i);
765 out.append("if (stack.pop() ").append(test).append(" stack.pop()) { gt = " + indx);
766 out.append("; continue; }");
770 private int readIntArg(byte[] byteCodes, int offsetInstruction) {
771 final int indxHi = byteCodes[offsetInstruction + 1] << 8;
772 final int indxLo = byteCodes[offsetInstruction + 2];
773 return (indxHi & 0xffffff00) | (indxLo & 0xff);
776 private static int countArgs(String descriptor, boolean[] hasReturnType, StringBuilder sig) {
779 Boolean count = null;
780 boolean array = false;
781 int firstPos = sig.length();
782 while (i < descriptor.length()) {
783 char ch = descriptor.charAt(i++);
809 hasReturnType[0] = true;
810 sig.insert(firstPos, ch);
812 sig.insert(firstPos, 'A');
819 hasReturnType[0] = false;
820 sig.insert(firstPos, 'V');
823 int next = descriptor.indexOf(';', i);
830 sig.append(descriptor.substring(i, next).replace('/', '_'));
832 sig.insert(firstPos, descriptor.substring(i, next).replace('/', '_'));
833 sig.insert(firstPos, ch);
835 sig.insert(firstPos, 'A');
837 hasReturnType[0] = true;
845 break; // invalid character
851 private void generateStaticField(Variable v) throws IOException {
853 .append(jc.getName().getInternalName().replace('/', '_'))
854 .append('_').append(v.getName()).append(" = 0;");
857 private String findMethodName(Method m) {
858 StringBuilder name = new StringBuilder();
859 String descr = m.getDescriptor();
860 if ("<init>".equals(m.getName())) { // NOI18N
861 name.append("cons"); // NOI18N
862 } else if ("<clinit>".equals(m.getName())) { // NOI18N
863 name.append("class"); // NOI18N
865 name.append(m.getName());
868 boolean hasReturn[] = { false };
869 countArgs(findDescriptor(m.getDescriptor()), hasReturn, name);
870 return name.toString();
873 private String findMethodName(CPMethodInfo mi, int[] cnt, boolean[] hasReturn) {
874 StringBuilder name = new StringBuilder();
875 String descr = mi.getDescriptor();
876 if ("<init>".equals(mi.getName())) { // NOI18N
877 name.append("cons"); // NOI18N
879 name.append(mi.getName());
881 cnt[0] = countArgs(findDescriptor(mi.getDescriptor()), hasReturn, name);
882 return name.toString();
885 private int invokeStaticMethod(byte[] byteCodes, int i, boolean isStatic)
887 int methodIndex = readIntArg(byteCodes, i);
888 CPMethodInfo mi = (CPMethodInfo) jc.getConstantPool().get(methodIndex);
889 boolean[] hasReturn = { false };
891 String mn = findMethodName(mi, cnt, hasReturn);
893 for (int j = cnt[0] - 1; j >= 0; j--) {
894 out.append("var v" + j).append(" = stack.pop(); ");
898 out.append("stack.push(");
900 final String in = mi.getClassName().getInternalName();
901 out.append(in.replace('/', '_'));
903 out.append(".prototype.");
911 out.append("stack.pop()");
914 for (int j = 0; j < cnt[0]; j++) {
928 private int invokeVirtualMethod(byte[] byteCodes, int i)
930 int methodIndex = readIntArg(byteCodes, i);
931 CPMethodInfo mi = (CPMethodInfo) jc.getConstantPool().get(methodIndex);
932 boolean[] hasReturn = { false };
934 String mn = findMethodName(mi, cnt, hasReturn);
936 for (int j = cnt[0] - 1; j >= 0; j--) {
937 out.append("var v" + j).append(" = stack.pop(); ");
939 out.append("var self = stack.pop(); ");
941 out.append("stack.push(");
947 for (int j = 0; j < cnt[0]; j++) {
960 private void addReference(String cn) throws IOException {
961 out.append(" /* needs ").append(cn).append(" */");
962 if (references != null) {
967 private void outType(String d, StringBuilder out) {
969 while (d.charAt(0) == '[') {
973 if (d.charAt(0) == 'L') {
974 assert d.charAt(d.length() - 1) == ';';
975 out.append(d.replace('/', '_').substring(0, d.length() - 1));
981 private String encodeConstant(CPEntry entry) {
983 if (entry instanceof CPClassInfo) {
984 v = "new java_lang_Class";
985 } else if (entry instanceof CPStringInfo) {
986 v = "\"" + entry.getValue().toString().replace("\"", "\\\"") + "\"";
988 v = entry.getValue().toString();
993 private String findDescriptor(String d) {
994 return d.replace('[', 'A');
997 private boolean javaScriptBody(Method m, boolean isStatic) throws IOException {
998 final ClassName extraAnn = ClassName.getClassName(JavaScriptBody.class.getName().replace('.', '/'));
999 Annotation a = m.getAnnotation(extraAnn);
1001 final ElementValue annVal = a.getComponent("body").getValue();
1002 String body = ((PrimitiveElementValue) annVal).getValue().getValue().toString();
1004 final ArrayElementValue arrVal = (ArrayElementValue) a.getComponent("args").getValue();
1005 final int len = arrVal.getValues().length;
1006 String[] names = new String[len];
1007 for (int i = 0; i < len; i++) {
1008 names[i] = ((PrimitiveElementValue) arrVal.getValues()[i]).getValue().getValue().toString();
1010 out.append("\nfunction ").append(
1011 jc.getName().getInternalName().replace('/', '_')).append('_').append(findMethodName(m));
1016 out.append(names[0]);
1023 List<Parameter> args = m.getParameters();
1024 for (int i = 0; i < args.size(); i++) {
1026 out.append(names[index]);
1027 final String desc = findDescriptor(args.get(i).getDescriptor());
1031 out.append(") {").append("\n");
1033 out.append("\n}\n");