src/main/java/org/apidesign/java4browser/ByteCodeToJavaScript.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Wed, 19 Sep 2012 19:29:05 +0200
changeset 12 282828609b86
parent 11 eca88b77b986
child 13 99f832e5765f
permissions -rw-r--r--
Support for invoking virtual methods
     1 /*
     2 Java 4 Browser Bytecode Translator
     3 Copyright (C) 2012-2012 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
     4 
     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.
     8 
     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.
    13 
    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.
    17 */
    18 package org.apidesign.java4browser;
    19 
    20 import java.io.IOException;
    21 import java.io.InputStream;
    22 import java.util.List;
    23 import static org.netbeans.modules.classfile.ByteCodes.*;
    24 import org.netbeans.modules.classfile.CPClassInfo;
    25 import org.netbeans.modules.classfile.CPEntry;
    26 import org.netbeans.modules.classfile.CPFieldInfo;
    27 import org.netbeans.modules.classfile.CPMethodInfo;
    28 import org.netbeans.modules.classfile.ClassFile;
    29 import org.netbeans.modules.classfile.Code;
    30 import org.netbeans.modules.classfile.Method;
    31 import org.netbeans.modules.classfile.Parameter;
    32 import org.netbeans.modules.classfile.Variable;
    33 
    34 /** Translator of the code inside class files to JavaScript.
    35  *
    36  * @author Jaroslav Tulach <jtulach@netbeans.org>
    37  */
    38 public final class ByteCodeToJavaScript {
    39     private final ClassFile jc;
    40     private final Appendable out;
    41 
    42     private ByteCodeToJavaScript(ClassFile jc, Appendable out) {
    43         this.jc = jc;
    44         this.out = out;
    45     }
    46     
    47     /** Converts a given class file to a JavaScript version.
    48      * @param fileName the name of the file we are reading
    49      * @param classFile input stream with code of the .class file
    50      * @param out a {@link StringBuilder} or similar to generate the output to
    51      * @throws IOException if something goes wrong during read or write or translating
    52      */
    53     public static void compile(String fileName, InputStream classFile, Appendable out) throws IOException {
    54         ClassFile jc = new ClassFile(classFile, true);
    55         ByteCodeToJavaScript compiler = new ByteCodeToJavaScript(jc, out);
    56         for (Method m : jc.getMethods()) {
    57             if (m.isStatic()) {
    58                 compiler.generateStaticMethod(m);
    59             } else {
    60                 compiler.generateInstanceMethod(m);
    61             }
    62         }
    63         for (Variable v : jc.getVariables()) {
    64             if (v.isStatic()) {
    65                 compiler.generateStaticField(v);
    66             }
    67         }
    68         out.append("function java_lang_Object_consV(self){}\n"); // XXX temporary
    69         
    70         out.append("\nfunction ").append(jc.getName().getExternalName().replace('.', '_'));
    71         out.append("() {");
    72         for (Method m : jc.getMethods()) {
    73             if (!m.isStatic()) {
    74                 compiler.generateMethodReference(m);
    75             }
    76         }
    77         for (Variable v : jc.getVariables()) {
    78             if (!v.isStatic()) {
    79                 out.append("\n  this." + v.getName() + " = 0;");
    80             }
    81         }
    82         out.append("\n}");
    83     }
    84     private void generateStaticMethod(Method m) throws IOException {
    85         out.append("\nfunction ").append(
    86             jc.getName().getExternalName().replace('.', '_')
    87         ).append('_').append(findMethodName(m));
    88         out.append('(');
    89         String space = "";
    90         List<Parameter> args = m.getParameters();
    91         for (int index = 0, i = 0; i < args.size(); i++) {
    92             out.append(space);
    93             out.append("arg").append(String.valueOf(index));
    94             space = ",";
    95             final String desc = args.get(i).getDescriptor();
    96             if ("D".equals(desc) || "J".equals(desc)) {
    97                 index += 2;
    98             } else {
    99                 index++;
   100             }
   101         }
   102         out.append(") {").append("\n");
   103         final Code code = m.getCode();
   104         int len = code.getMaxLocals();
   105         for (int index = args.size(), i = args.size(); i < len; i++) {
   106             out.append("  var ");
   107             out.append("arg").append(String.valueOf(i)).append(";\n");
   108         }
   109         out.append("  var stack = new Array(");
   110         out.append(Integer.toString(code.getMaxStack()));
   111         out.append(");\n");
   112         produceCode(code.getByteCodes());
   113         out.append("}");
   114     }
   115     
   116     private void generateMethodReference(Method m) throws IOException {
   117         final String name = findMethodName(m);
   118         out.append("\n  this.").append(name).append(" = ")
   119            .append(jc.getName().getExternalName().replace('.', '_'))
   120            .append('_').append(name).append(";");
   121     }
   122     
   123     private void generateInstanceMethod(Method m) throws IOException {
   124         out.append("\nfunction ").append(
   125             jc.getName().getExternalName().replace('.', '_')
   126         ).append('_').append(findMethodName(m));
   127         out.append("(arg0");
   128         String space = ",";
   129         List<Parameter> args = m.getParameters();
   130         for (int index = 1, i = 0; i < args.size(); i++) {
   131             out.append(space);
   132             out.append("arg").append(String.valueOf(index));
   133             final String desc = args.get(i).getDescriptor();
   134             if ("D".equals(desc) || "J".equals(desc)) {
   135                 index += 2;
   136             } else {
   137                 index++;
   138             }
   139         }
   140         out.append(") {").append("\n");
   141         final Code code = m.getCode();
   142         int len = code.getMaxLocals();
   143         for (int index = args.size(), i = args.size(); i < len; i++) {
   144             out.append("  var ");
   145             out.append("arg").append(String.valueOf(i + 1)).append(";\n");
   146         }
   147         out.append(";\n  var stack = new Array(");
   148         out.append(Integer.toString(code.getMaxStack()));
   149         out.append(");\n");
   150         produceCode(code.getByteCodes());
   151         out.append("}");
   152     }
   153 
   154     private void produceCode(byte[] byteCodes) throws IOException {
   155         out.append("\n  var gt = 0;\n  for(;;) switch(gt) {\n");
   156         for (int i = 0; i < byteCodes.length; i++) {
   157             int prev = i;
   158             out.append("    case " + i).append(": ");
   159             final int c = (byteCodes[i] + 256) % 256;
   160             switch (c) {
   161                 case bc_aload_0:
   162                 case bc_iload_0:
   163                 case bc_lload_0:
   164                 case bc_fload_0:
   165                 case bc_dload_0:
   166                     out.append("stack.push(arg0);");
   167                     break;
   168                 case bc_aload_1:
   169                 case bc_iload_1:
   170                 case bc_lload_1:
   171                 case bc_fload_1:
   172                 case bc_dload_1:
   173                     out.append("stack.push(arg1);");
   174                     break;
   175                 case bc_aload_2:
   176                 case bc_iload_2:
   177                 case bc_lload_2:
   178                 case bc_fload_2:
   179                 case bc_dload_2:
   180                     out.append("stack.push(arg2);");
   181                     break;
   182                 case bc_aload_3:
   183                 case bc_iload_3:
   184                 case bc_lload_3:
   185                 case bc_fload_3:
   186                 case bc_dload_3:
   187                     out.append("stack.push(arg3);");
   188                     break;
   189                 case bc_iload:
   190                 case bc_lload:
   191                 case bc_fload:
   192                 case bc_dload:
   193                 case bc_aload: {
   194                     final int indx = (byteCodes[++i] + 256) % 256;
   195                     out.append("stack.push(arg").append(indx + ");");
   196                     break;
   197                 }
   198                 case bc_astore_0:
   199                 case bc_istore_0:
   200                 case bc_lstore_0:
   201                 case bc_fstore_0:
   202                 case bc_dstore_0:
   203                     out.append("arg0 = stack.pop();");
   204                     break;
   205                 case bc_astore_1:
   206                 case bc_istore_1:
   207                 case bc_lstore_1:
   208                 case bc_fstore_1:
   209                 case bc_dstore_1:
   210                     out.append("arg1 = stack.pop();");
   211                     break;
   212                 case bc_astore_2:
   213                 case bc_istore_2:
   214                 case bc_lstore_2:
   215                 case bc_fstore_2:
   216                 case bc_dstore_2:
   217                     out.append("arg2 = stack.pop();");
   218                     break;
   219                 case bc_astore_3:
   220                 case bc_istore_3:
   221                 case bc_lstore_3:
   222                 case bc_fstore_3:
   223                 case bc_dstore_3:
   224                     out.append("arg3 = stack.pop();");
   225                     break;
   226                 case bc_iadd:
   227                 case bc_ladd:
   228                 case bc_fadd:
   229                 case bc_dadd:
   230                     out.append("stack.push(stack.pop() + stack.pop());");
   231                     break;
   232                 case bc_isub:
   233                 case bc_lsub:
   234                 case bc_fsub:
   235                 case bc_dsub:
   236                     out.append("{ var tmp = stack.pop(); stack.push(stack.pop() - tmp); }");
   237                     break;
   238                 case bc_imul:
   239                 case bc_lmul:
   240                 case bc_fmul:
   241                 case bc_dmul:
   242                     out.append("stack.push(stack.pop() * stack.pop());");
   243                     break;
   244                 case bc_idiv:
   245                 case bc_ldiv:
   246                     out.append("{ var tmp = stack.pop(); stack.push(Math.floor(stack.pop() / tmp)); }");
   247                     break;
   248                 case bc_fdiv:
   249                 case bc_ddiv:
   250                     out.append("{ var tmp = stack.pop(); stack.push(stack.pop() / tmp); }");
   251                     break;
   252                 case bc_iand:
   253                 case bc_land:
   254                     out.append("stack.push(stack.pop() & stack.pop());");
   255                     break;
   256                 case bc_ior:
   257                 case bc_lor:
   258                     out.append("stack.push(stack.pop() | stack.pop());");
   259                     break;
   260                 case bc_ixor:
   261                 case bc_lxor:
   262                     out.append("stack.push(stack.pop() ^ stack.pop());");
   263                     break;
   264                 case bc_iinc: {
   265                     final int varIndx = (byteCodes[++i] + 256) % 256;
   266                     final int incrBy = (byteCodes[++i] + 256) % 256;
   267                     if (incrBy == 1) {
   268                         out.append("arg" + varIndx).append("++;");
   269                     } else {
   270                         out.append("arg" + varIndx).append(" += " + incrBy).append(";");
   271                     }
   272                     break;
   273                 }
   274                 case bc_return:
   275                     out.append("return;");
   276                     break;
   277                 case bc_ireturn:
   278                 case bc_lreturn:
   279                 case bc_freturn:
   280                 case bc_dreturn:
   281                 case bc_areturn:
   282                     out.append("return stack.pop();");
   283                     break;
   284                 case bc_i2l:
   285                 case bc_i2f:
   286                 case bc_i2d:
   287                 case bc_l2i:
   288                     // max int check?
   289                 case bc_l2f:
   290                 case bc_l2d:
   291                 case bc_f2d:
   292                 case bc_d2f:
   293                     out.append("/* number conversion */");
   294                     break;
   295                 case bc_f2i:
   296                 case bc_f2l:
   297                 case bc_d2i:
   298                 case bc_d2l:
   299                     out.append("stack.push(Math.floor(stack.pop()));");
   300                     break;
   301                 case bc_i2b:
   302                 case bc_i2c:
   303                 case bc_i2s:
   304                     out.append("/* number conversion */");
   305                     break;
   306                 case bc_iconst_0:
   307                 case bc_dconst_0:
   308                 case bc_lconst_0:
   309                 case bc_fconst_0:
   310                     out.append("stack.push(0);");
   311                     break;
   312                 case bc_iconst_1:
   313                 case bc_lconst_1:
   314                 case bc_fconst_1:
   315                 case bc_dconst_1:
   316                     out.append("stack.push(1);");
   317                     break;
   318                 case bc_iconst_2:
   319                 case bc_fconst_2:
   320                     out.append("stack.push(2);");
   321                     break;
   322                 case bc_iconst_3:
   323                     out.append("stack.push(3);");
   324                     break;
   325                 case bc_iconst_4:
   326                     out.append("stack.push(4);");
   327                     break;
   328                 case bc_iconst_5:
   329                     out.append("stack.push(5);");
   330                     break;
   331                 case bc_ldc_w:
   332                 case bc_ldc2_w: {
   333                     int indx = readIntArg(byteCodes, i);
   334                     CPEntry entry = jc.getConstantPool().get(indx);
   335                     i += 2;
   336                     out.append("stack.push(" + entry.getValue() + ");");
   337                     break;
   338                 }
   339                 case bc_if_icmpeq: {
   340                     i = generateIf(byteCodes, i, "==");
   341                     break;
   342                 }
   343                 case bc_ifeq: {
   344                     int indx = i + readIntArg(byteCodes, i);
   345                     out.append("if (stack.pop() == 0) { gt = " + indx);
   346                     out.append("; continue; }");
   347                     i += 2;
   348                     break;
   349                 }
   350                 case bc_if_icmpne:
   351                     i = generateIf(byteCodes, i, "!=");
   352                     break;
   353                 case bc_if_icmplt:
   354                     i = generateIf(byteCodes, i, ">");
   355                     break;
   356                 case bc_if_icmple:
   357                     i = generateIf(byteCodes, i, ">=");
   358                     break;
   359                 case bc_if_icmpgt:
   360                     i = generateIf(byteCodes, i, "<");
   361                     break;
   362                 case bc_if_icmpge:
   363                     i = generateIf(byteCodes, i, "<=");
   364                     break;
   365                 case bc_goto: {
   366                     int indx = i + readIntArg(byteCodes, i);
   367                     out.append("gt = " + indx).append("; continue;");
   368                     i += 2;
   369                     break;
   370                 }
   371                 case bc_invokevirtual:
   372                     i = invokeVirtualMethod(byteCodes, i);
   373                     break;
   374                 case bc_invokespecial:
   375                     i = invokeStaticMethod(byteCodes, i, false);
   376                     break;
   377                 case bc_invokestatic:
   378                     i = invokeStaticMethod(byteCodes, i, true);
   379                     break;
   380                 case bc_new: {
   381                     int indx = readIntArg(byteCodes, i);
   382                     CPClassInfo ci = jc.getConstantPool().getClass(indx);
   383                     out.append("stack.push(");
   384                     out.append("new ").append(ci.getClassName().getExternalName().replace('.','_'));
   385                     out.append(");");
   386                     i += 2;
   387                     break;
   388                 }
   389                 case bc_dup:
   390                     out.append("stack.push(stack[stack.length - 1]);");
   391                     break;
   392                 case bc_bipush:
   393                     out.append("stack.push(" + byteCodes[++i] + ");");
   394                     break;
   395                 case bc_getfield: {
   396                     int indx = readIntArg(byteCodes, i);
   397                     CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
   398                     out.append(" stack.push(stack.pop().").append(fi.getFieldName()).append(");");
   399                     i += 2;
   400                     break;
   401                 }
   402                 case bc_getstatic: {
   403                     int indx = readIntArg(byteCodes, i);
   404                     CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
   405                     out.append("stack.push(").append(fi.getClassName().getExternalName().replace('.', '_'));
   406                     out.append('_').append(fi.getFieldName()).append(");");
   407                     i += 2;
   408                     break;
   409                 }
   410                 case bc_putstatic: {
   411                     int indx = readIntArg(byteCodes, i);
   412                     CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
   413                     out.append(fi.getClassName().getExternalName().replace('.', '_'));
   414                     out.append('_').append(fi.getFieldName()).append(" = stack.pop();");
   415                     i += 2;
   416                     break;
   417                 }
   418                 case bc_putfield: {
   419                     int indx = readIntArg(byteCodes, i);
   420                     CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
   421                     out.append("{ var v = stack.pop(); stack.pop().")
   422                        .append(fi.getFieldName()).append(" = v; }");
   423                     i += 2;
   424                     break;
   425                 }
   426                     
   427             }
   428             out.append(" /*");
   429             for (int j = prev; j <= i; j++) {
   430                 out.append(" ");
   431                 final int cc = (byteCodes[j] + 256) % 256;
   432                 out.append(Integer.toString(cc));
   433             }
   434             out.append("*/\n");
   435         }
   436         out.append("  }\n");
   437     }
   438 
   439     private int generateIf(byte[] byteCodes, int i, final String test) throws IOException {
   440         int indx = i + readIntArg(byteCodes, i);
   441         out.append("if (stack.pop() ").append(test).append(" stack.pop()) { gt = " + indx);
   442         out.append("; continue; }");
   443         return i + 2;
   444     }
   445 
   446     private int readIntArg(byte[] byteCodes, int offsetInstruction) {
   447         final int indxHi = byteCodes[offsetInstruction + 1] << 8;
   448         final int indxLo = byteCodes[offsetInstruction + 2];
   449         return (indxHi & 0xffffff00) | (indxLo & 0xff);
   450     }
   451     
   452     private static int countArgs(String descriptor, boolean[] hasReturnType, StringBuilder sig) {
   453         int cnt = 0;
   454         int i = 0;
   455         Boolean count = null;
   456         int firstPos = sig.length();
   457         while (i < descriptor.length()) {
   458             char ch = descriptor.charAt(i++);
   459             switch (ch) {
   460                 case '(':
   461                     count = true;
   462                     continue;
   463                 case ')':
   464                     count = false;
   465                     continue;
   466                 case 'B': 
   467                 case 'C': 
   468                 case 'D': 
   469                 case 'F': 
   470                 case 'I': 
   471                 case 'J': 
   472                 case 'S': 
   473                 case 'Z': 
   474                     if (count) {
   475                         cnt++;
   476                         sig.append(ch);
   477                     } else {
   478                         hasReturnType[0] = true;
   479                         sig.insert(firstPos, ch);
   480                     }
   481                     continue;
   482                 case 'V': 
   483                     assert !count;
   484                     hasReturnType[0] = false;
   485                     sig.insert(firstPos, 'V');
   486                     continue;
   487                 case 'L':
   488                     i = descriptor.indexOf(';', i);
   489                     if (count) {
   490                         cnt++;
   491                     } else {
   492                         hasReturnType[0] = true;
   493                     }
   494                     continue;
   495                 case '[':
   496                     //arrays++;
   497                     continue;
   498                 default:
   499                     break; // invalid character
   500             }
   501         }
   502         return cnt;
   503     }
   504 
   505     private void generateStaticField(Variable v) throws IOException {
   506         out.append("\nvar ")
   507            .append(jc.getName().getExternalName().replace('.', '_'))
   508            .append('_').append(v.getName()).append(" = 0;");
   509     }
   510 
   511     private String findMethodName(Method m) {
   512         StringBuilder out = new StringBuilder();
   513         if ("<init>".equals(m.getName())) { // NOI18N
   514             out.append("consV"); // NOI18N
   515         } else {
   516             out.append(m.getName());
   517             out.append(m.getReturnType());
   518         } 
   519         List<Parameter> args = m.getParameters();
   520         for (Parameter t : args) {
   521             out.append(t.getDescriptor());
   522         }
   523         return out.toString();
   524     }
   525 
   526     private String findMethodName(CPMethodInfo mi, int[] cnt, boolean[] hasReturn) {
   527         StringBuilder name = new StringBuilder();
   528         if ("<init>".equals(mi.getName())) { // NOI18N
   529             name.append("cons"); // NOI18N
   530         } else {
   531             name.append(mi.getName());
   532         }
   533         cnt[0] = countArgs(mi.getDescriptor(), hasReturn, name);
   534         return name.toString();
   535     }
   536 
   537     private int invokeStaticMethod(byte[] byteCodes, int i, boolean isStatic)
   538     throws IOException {
   539         int methodIndex = readIntArg(byteCodes, i);
   540         CPMethodInfo mi = (CPMethodInfo) jc.getConstantPool().get(methodIndex);
   541         boolean[] hasReturn = { false };
   542         int[] cnt = { 0 };
   543         String mn = findMethodName(mi, cnt, hasReturn);
   544         out.append("{ ");
   545         for (int j = cnt[0] - 1; j >= 0; j--) {
   546             out.append("var v" + j).append(" = stack.pop(); ");
   547         }
   548         
   549         if (hasReturn[0]) {
   550             out.append("stack.push(");
   551         }
   552         out.append(mi.getClassName().getInternalName().replace('/', '_'));
   553         out.append('_');
   554         out.append(mn);
   555         out.append('(');
   556         String sep = "";
   557         if (!isStatic) {
   558             out.append("stack.pop()");
   559             sep = ", ";
   560         }
   561         for (int j = 0; j < cnt[0]; j++) {
   562             out.append(sep);
   563             out.append("v" + j);
   564             sep = ", ";
   565         }
   566         out.append(")");
   567         if (hasReturn[0]) {
   568             out.append(")");
   569         }
   570         out.append("; }");
   571         i += 2;
   572         return i;
   573     }
   574     private int invokeVirtualMethod(byte[] byteCodes, int i)
   575     throws IOException {
   576         int methodIndex = readIntArg(byteCodes, i);
   577         CPMethodInfo mi = (CPMethodInfo) jc.getConstantPool().get(methodIndex);
   578         boolean[] hasReturn = { false };
   579         int[] cnt = { 0 };
   580         String mn = findMethodName(mi, cnt, hasReturn);
   581         out.append("{ ");
   582         for (int j = cnt[0] - 1; j >= 0; j--) {
   583             out.append("var v" + j).append(" = stack.pop(); ");
   584         }
   585         out.append("var self = stack.pop(); ");
   586         if (hasReturn[0]) {
   587             out.append("stack.push(");
   588         }
   589         out.append("self.");
   590         out.append(mn);
   591         out.append('(');
   592         out.append("self");
   593         for (int j = 0; j < cnt[0]; j++) {
   594             out.append(", ");
   595             out.append("v" + j);
   596         }
   597         out.append(")");
   598         if (hasReturn[0]) {
   599             out.append(")");
   600         }
   601         out.append("; }");
   602         i += 2;
   603         return i;
   604     }
   605 }