We can read definition of Object from the JDK. No need to provide default dummy implementation. InstanceSub is discovered automatically.
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);
87 final String className = jc.getName().getInternalName().replace('/', '_');
88 out.append("\nfunction ").append(className);
90 for (Method m : jc.getMethods()) {
92 compiler.generateMethodReference(m);
95 for (Variable v : jc.getVariables()) {
97 out.append("\n this." + v.getName() + " = 0;");
100 out.append("\n this.$instOf_").append(className).append(" = true;");
102 ClassName sc = jc.getSuperClass();
104 out.append("\n ").append(className)
105 .append(".prototype = new ").append(sc.getInternalName().replace('/', '_'));
108 private void generateStaticMethod(Method m) throws IOException {
109 out.append("\nfunction ").append(
110 jc.getName().getInternalName().replace('/', '_')
111 ).append('_').append(findMethodName(m));
114 List<Parameter> args = m.getParameters();
115 for (int index = 0, i = 0; i < args.size(); i++) {
117 out.append("arg").append(String.valueOf(index));
119 final String desc = args.get(i).getDescriptor();
120 if ("D".equals(desc) || "J".equals(desc)) {
126 out.append(") {").append("\n");
127 final Code code = m.getCode();
129 int len = code.getMaxLocals();
130 for (int index = args.size(), i = args.size(); i < len; i++) {
132 out.append("arg").append(String.valueOf(i)).append(";\n");
134 out.append(" var stack = new Array(");
135 out.append(Integer.toString(code.getMaxStack()));
137 produceCode(code.getByteCodes());
139 out.append(" /* no code found for ").append(m.getTypeSignature()).append(" */\n");
144 private void generateMethodReference(Method m) throws IOException {
145 final String name = findMethodName(m);
146 out.append("\n this.").append(name).append(" = ")
147 .append(jc.getName().getInternalName().replace('/', '_'))
148 .append('_').append(name).append(";");
151 private void generateInstanceMethod(Method m) throws IOException {
152 out.append("\nfunction ").append(
153 jc.getName().getInternalName().replace('/', '_')
154 ).append('_').append(findMethodName(m));
157 List<Parameter> args = m.getParameters();
158 for (int index = 1, i = 0; i < args.size(); i++) {
160 out.append("arg").append(String.valueOf(index));
161 final String desc = args.get(i).getDescriptor();
162 if ("D".equals(desc) || "J".equals(desc)) {
168 out.append(") {").append("\n");
169 final Code code = m.getCode();
171 int len = code.getMaxLocals();
172 for (int index = args.size(), i = args.size(); i < len; i++) {
174 out.append("arg").append(String.valueOf(i + 1)).append(";\n");
176 out.append(";\n var stack = new Array(");
177 out.append(Integer.toString(code.getMaxStack()));
179 produceCode(code.getByteCodes());
181 out.append(" /* no code found for ").append(m.getTypeSignature()).append(" */\n");
186 private void produceCode(byte[] byteCodes) throws IOException {
187 out.append("\n var gt = 0;\n for(;;) switch(gt) {\n");
188 for (int i = 0; i < byteCodes.length; i++) {
190 out.append(" case " + i).append(": ");
191 final int c = (byteCodes[i] + 256) % 256;
198 out.append("stack.push(arg0);");
205 out.append("stack.push(arg1);");
212 out.append("stack.push(arg2);");
219 out.append("stack.push(arg3);");
226 final int indx = (byteCodes[++i] + 256) % 256;
227 out.append("stack.push(arg").append(indx + ");");
235 out.append("arg0 = stack.pop();");
242 out.append("arg1 = stack.pop();");
249 out.append("arg2 = stack.pop();");
256 out.append("arg3 = stack.pop();");
262 out.append("stack.push(stack.pop() + stack.pop());");
268 out.append("{ var tmp = stack.pop(); stack.push(stack.pop() - tmp); }");
274 out.append("stack.push(stack.pop() * stack.pop());");
278 out.append("{ var tmp = stack.pop(); stack.push(Math.floor(stack.pop() / tmp)); }");
282 out.append("{ var tmp = stack.pop(); stack.push(stack.pop() / tmp); }");
286 out.append("stack.push(stack.pop() & stack.pop());");
290 out.append("stack.push(stack.pop() | stack.pop());");
294 out.append("stack.push(stack.pop() ^ stack.pop());");
297 final int varIndx = (byteCodes[++i] + 256) % 256;
298 final int incrBy = (byteCodes[++i] + 256) % 256;
300 out.append("arg" + varIndx).append("++;");
302 out.append("arg" + varIndx).append(" += " + incrBy).append(";");
307 out.append("return;");
314 out.append("return stack.pop();");
325 out.append("/* number conversion */");
331 out.append("stack.push(Math.floor(stack.pop()));");
336 out.append("/* number conversion */");
342 out.append("stack.push(0);");
348 out.append("stack.push(1);");
352 out.append("stack.push(2);");
355 out.append("stack.push(3);");
358 out.append("stack.push(4);");
361 out.append("stack.push(5);");
365 int indx = readIntArg(byteCodes, i);
366 CPEntry entry = jc.getConstantPool().get(indx);
368 out.append("stack.push(" + entry.getValue() + ");");
372 i = generateIf(byteCodes, i, "==");
376 int indx = i + readIntArg(byteCodes, i);
377 out.append("if (stack.pop() == 0) { gt = " + indx);
378 out.append("; continue; }");
383 int indx = i + readIntArg(byteCodes, i);
384 out.append("if (stack.pop()) { gt = " + indx);
385 out.append("; continue; }");
390 int indx = i + readIntArg(byteCodes, i);
391 out.append("if (!stack.pop()) { gt = " + indx);
392 out.append("; continue; }");
397 i = generateIf(byteCodes, i, "!=");
400 i = generateIf(byteCodes, i, ">");
403 i = generateIf(byteCodes, i, ">=");
406 i = generateIf(byteCodes, i, "<");
409 i = generateIf(byteCodes, i, "<=");
412 int indx = i + readIntArg(byteCodes, i);
413 out.append("gt = " + indx).append("; continue;");
417 case bc_invokeinterface:
418 case bc_invokevirtual:
419 i = invokeVirtualMethod(byteCodes, i);
421 case bc_invokespecial:
422 i = invokeStaticMethod(byteCodes, i, false);
424 case bc_invokestatic:
425 i = invokeStaticMethod(byteCodes, i, true);
428 int indx = readIntArg(byteCodes, i);
429 CPClassInfo ci = jc.getConstantPool().getClass(indx);
430 out.append("stack.push(");
431 out.append("new ").append(ci.getClassName().getInternalName().replace('/','_'));
433 addReference(ci.getClassName().getInternalName());
438 out.append("stack.push(stack[stack.length - 1]);");
441 out.append("stack.push(" + byteCodes[++i] + ");");
444 int indx = readIntArg(byteCodes, i);
445 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
446 out.append(" stack.push(stack.pop().").append(fi.getFieldName()).append(");");
451 int indx = readIntArg(byteCodes, i);
452 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
453 final String in = fi.getClassName().getInternalName();
454 out.append("stack.push(").append(in.replace('/', '_'));
455 out.append('_').append(fi.getFieldName()).append(");");
461 int indx = readIntArg(byteCodes, i);
462 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
463 final String in = fi.getClassName().getInternalName();
464 out.append(in.replace('/', '_'));
465 out.append('_').append(fi.getFieldName()).append(" = stack.pop();");
471 int indx = readIntArg(byteCodes, i);
472 CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
473 out.append("{ var v = stack.pop(); stack.pop().")
474 .append(fi.getFieldName()).append(" = v; }");
478 case bc_instanceof: {
479 int indx = readIntArg(byteCodes, i);
480 CPClassInfo ci = jc.getConstantPool().getClass(indx);
481 out.append("stack.push(stack.pop().$instOf_")
482 .append(ci.getClassName().getInternalName().replace('/', '_'))
483 .append(" ? 1 : 0);");
489 for (int j = prev; j <= i; j++) {
491 final int cc = (byteCodes[j] + 256) % 256;
492 out.append(Integer.toString(cc));
499 private int generateIf(byte[] byteCodes, int i, final String test) throws IOException {
500 int indx = i + readIntArg(byteCodes, i);
501 out.append("if (stack.pop() ").append(test).append(" stack.pop()) { gt = " + indx);
502 out.append("; continue; }");
506 private int readIntArg(byte[] byteCodes, int offsetInstruction) {
507 final int indxHi = byteCodes[offsetInstruction + 1] << 8;
508 final int indxLo = byteCodes[offsetInstruction + 2];
509 return (indxHi & 0xffffff00) | (indxLo & 0xff);
512 private static int countArgs(String descriptor, boolean[] hasReturnType, StringBuilder sig) {
515 Boolean count = null;
516 int firstPos = sig.length();
517 while (i < descriptor.length()) {
518 char ch = descriptor.charAt(i++);
538 hasReturnType[0] = true;
539 sig.insert(firstPos, ch);
544 hasReturnType[0] = false;
545 sig.insert(firstPos, 'V');
548 int next = descriptor.indexOf(';', i);
552 sig.append(descriptor.substring(i, next).replace('/', '_'));
554 sig.insert(firstPos, descriptor.substring(i, next).replace('/', '_'));
555 sig.insert(firstPos, ch);
556 hasReturnType[0] = true;
564 break; // invalid character
570 private void generateStaticField(Variable v) throws IOException {
572 .append(jc.getName().getInternalName().replace('/', '_'))
573 .append('_').append(v.getName()).append(" = 0;");
576 private String findMethodName(Method m) {
577 StringBuilder tmp = new StringBuilder();
578 if ("<init>".equals(m.getName())) { // NOI18N
579 tmp.append("consV"); // NOI18N
580 } else if ("<clinit>".equals(m.getName())) { // NOI18N
581 tmp.append("classV"); // NOI18N
583 tmp.append(m.getName());
584 outType(m.getReturnType(), tmp);
586 List<Parameter> args = m.getParameters();
587 for (Parameter t : args) {
588 outType(t.getDescriptor(), tmp);
590 return tmp.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));