src/main/java/org/apidesign/java4browser/ByteCodeToJavaScript.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Mon, 27 Aug 2012 13:16:29 +0200
changeset 4 f352a33fb71b
parent 3 e44f0155d946
child 5 d3193a7086e7
permissions -rw-r--r--
Can compile recursive factorial
     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.CPMethodInfo;
    25 import org.netbeans.modules.classfile.ClassFile;
    26 import org.netbeans.modules.classfile.Code;
    27 import org.netbeans.modules.classfile.Method;
    28 import org.netbeans.modules.classfile.Parameter;
    29 
    30 /** Translator of the code inside class files to JavaScript.
    31  *
    32  * @author Jaroslav Tulach <jtulach@netbeans.org>
    33  */
    34 public final class ByteCodeToJavaScript {
    35     private final ClassFile jc;
    36     private final Appendable out;
    37 
    38     private ByteCodeToJavaScript(ClassFile jc, Appendable out) {
    39         this.jc = jc;
    40         this.out = out;
    41     }
    42     
    43     /** Converts a given class file to a JavaScript version.
    44      * @param fileName the name of the file we are reading
    45      * @param classFile input stream with code of the .class file
    46      * @param out a {@link StringBuilder} or similar to generate the output to
    47      * @throws IOException if something goes wrong during read or write or translating
    48      */
    49     public static void compile(String fileName, InputStream classFile, Appendable out) throws IOException {
    50         ClassFile jc = new ClassFile(classFile, true);
    51         ByteCodeToJavaScript compiler = new ByteCodeToJavaScript(jc, out);
    52         for (Method m : jc.getMethods()) {
    53             if (m.isStatic()) {
    54                 compiler.generateStaticMethod(m);
    55             }
    56         }
    57     }
    58     private void generateStaticMethod(Method m) throws IOException {
    59         out.append("\nfunction ").append(
    60             jc.getName().getExternalName().replace('.', '_')
    61         ).append('_').append(
    62             m.getName()
    63         );
    64         out.append(m.getReturnType());
    65         List<Parameter> args = m.getParameters();
    66         for (Parameter t : args) {
    67             out.append(t.getDescriptor());
    68         }
    69         out.append('(');
    70         String space = "";
    71         for (int index = 0, i = 0; i < args.size(); i++) {
    72             out.append(space);
    73             out.append("arg").append(String.valueOf(index));
    74             space = ",";
    75             final String desc = args.get(i).getDescriptor();
    76             if ("D".equals(desc) || "J".equals(desc)) {
    77                 index += 2;
    78             } else {
    79                 index++;
    80             }
    81         }
    82         out.append(") {").append("\n  var ");
    83         final Code code = m.getCode();
    84         int len = code.getMaxLocals();
    85         space = "";
    86         for (int i = 0; i < len; i++) {
    87             out.append(space);
    88             out.append("var").append(String.valueOf(i));
    89             space = ",";
    90         }
    91         out.append(";\n  var stack = new Array(");
    92         out.append(Integer.toString(code.getMaxStack()));
    93         out.append(");\n");
    94         produceCode(code.getByteCodes());
    95         out.append("}");
    96     }
    97 
    98     private void produceCode(byte[] byteCodes) throws IOException {
    99         out.append("\nvar gt = 0;\nfor(;;) switch(gt) {\n");
   100         for (int i = 0; i < byteCodes.length; i++) {
   101             int prev = i;
   102             out.append("  case " + i).append(": ");
   103             final int c = (byteCodes[i] + 256) % 256;
   104             switch (c) {
   105                 case bc_aload_0:
   106                 case bc_iload_0:
   107                 case bc_lload_0:
   108                 case bc_fload_0:
   109                 case bc_dload_0:
   110                     out.append("stack.push(arg0);");
   111                     break;
   112                 case bc_aload_1:
   113                 case bc_iload_1:
   114                 case bc_lload_1:
   115                 case bc_fload_1:
   116                 case bc_dload_1:
   117                     out.append("stack.push(arg1);");
   118                     break;
   119                 case bc_aload_2:
   120                 case bc_iload_2:
   121                 case bc_lload_2:
   122                 case bc_fload_2:
   123                 case bc_dload_2:
   124                     out.append("stack.push(arg2);");
   125                     break;
   126                 case bc_aload_3:
   127                 case bc_iload_3:
   128                 case bc_lload_3:
   129                 case bc_fload_3:
   130                 case bc_dload_3:
   131                     out.append("stack.push(arg3);");
   132                     break;
   133                 case bc_iload:
   134                 case bc_lload:
   135                 case bc_fload:
   136                 case bc_dload:
   137                 case bc_aload: {
   138                     final int indx = (byteCodes[++i] + 256) % 256;
   139                     out.append("stack.push(arg").append(indx + ");");
   140                     break;
   141                 }
   142                 case bc_iadd:
   143                 case bc_ladd:
   144                 case bc_fadd:
   145                 case bc_dadd:
   146                     out.append("stack.push(stack.pop() + stack.pop());");
   147                     break;
   148                 case bc_isub:
   149                 case bc_lsub:
   150                 case bc_fsub:
   151                 case bc_dsub:
   152                     out.append("{ var tmp = stack.pop(); stack.push(stack.pop() - tmp); }");
   153                     break;
   154                 case bc_imul:
   155                 case bc_lmul:
   156                 case bc_fmul:
   157                 case bc_dmul:
   158                     out.append("stack.push(stack.pop() * stack.pop());");
   159                     break;
   160                 case bc_idiv:
   161                 case bc_ldiv:
   162                     out.append("{ var tmp = stack.pop(); stack.push(Math.floor(stack.pop() / tmp)); }");
   163                     break;
   164                 case bc_fdiv:
   165                 case bc_ddiv:
   166                     out.append("{ var tmp = stack.pop(); stack.push(stack.pop() / tmp); }");
   167                     break;
   168                 case bc_ireturn:
   169                 case bc_lreturn:
   170                 case bc_freturn:
   171                 case bc_dreturn:
   172                     out.append("return stack.pop();");
   173                     break;
   174                 case bc_i2l:
   175                 case bc_i2f:
   176                 case bc_i2d:
   177                 case bc_l2i:
   178                     // max int check?
   179                 case bc_l2f:
   180                 case bc_l2d:
   181                 case bc_f2d:
   182                 case bc_d2f:
   183                     out.append("/* number conversion */");
   184                     break;
   185                 case bc_f2i:
   186                 case bc_f2l:
   187                 case bc_d2i:
   188                 case bc_d2l:
   189                     out.append("stack.push(Math.floor(stack.pop()));");
   190                     break;
   191                 case bc_i2b:
   192                 case bc_i2c:
   193                 case bc_i2s:
   194                     out.append("/* number conversion */");
   195                     break;
   196                 case bc_iconst_0:
   197                 case bc_dconst_0:
   198                 case bc_lconst_0:
   199                 case bc_fconst_0:
   200                     out.append("stack.push(0);");
   201                     break;
   202                 case bc_iconst_1:
   203                 case bc_lconst_1:
   204                 case bc_fconst_1:
   205                 case bc_dconst_1:
   206                     out.append("stack.push(1);");
   207                     break;
   208                 case bc_iconst_2:
   209                 case bc_fconst_2:
   210                     out.append("stack.push(2);");
   211                     break;
   212                 case bc_iconst_3:
   213                     out.append("stack.push(3);");
   214                     break;
   215                 case bc_iconst_4:
   216                     out.append("stack.push(4);");
   217                     break;
   218                 case bc_iconst_5:
   219                     out.append("stack.push(5);");
   220                     break;
   221                 case bc_if_icmpeq: {
   222                     i = generateIf(byteCodes, i, "==");
   223                     break;
   224                 }
   225                 case bc_if_icmpne:
   226                     i = generateIf(byteCodes, i, "!=");
   227                     break;
   228                 case bc_if_icmplt:
   229                     i = generateIf(byteCodes, i, ">");
   230                     break;
   231                 case bc_if_icmple:
   232                     i = generateIf(byteCodes, i, ">=");
   233                     break;
   234                 case bc_if_icmpgt:
   235                     i = generateIf(byteCodes, i, "<");
   236                     break;
   237                 case bc_if_icmpge:
   238                     i = generateIf(byteCodes, i, "<=");
   239                     break;
   240                 case bc_invokestatic: {
   241                     int methodIndex = readIntArg(byteCodes, i);
   242                     CPMethodInfo mi = (CPMethodInfo) jc.getConstantPool().get(methodIndex);
   243                     boolean[] hasReturn = { false };
   244                     StringBuilder signature = new StringBuilder();
   245                     int cnt = countArgs(mi.getDescriptor(), hasReturn, signature);
   246                     
   247                     if (hasReturn[0]) {
   248                         out.append("stack.push(");
   249                     }
   250                     out.append(mi.getClassName().getInternalName().replace('/', '_'));
   251                     out.append('_');
   252                     out.append(mi.getName());
   253                     out.append(signature.toString());
   254                     out.append('(');
   255                     String sep = "";
   256                     for (int j = 0; j < cnt; j++) {
   257                         out.append(sep);
   258                         out.append("stack.pop()");
   259                         sep = ", ";
   260                     }
   261                     out.append(")");
   262                     if (hasReturn[0]) {
   263                         out.append(")");
   264                     }
   265                     out.append(";");
   266                     i += 2;
   267                     break;
   268                 }
   269             }
   270             out.append(" /*");
   271             for (int j = prev; j <= i; j++) {
   272                 out.append(" ");
   273                 final int cc = (byteCodes[j] + 256) % 256;
   274                 out.append(Integer.toString(cc));
   275             }
   276             out.append("*/\n");
   277         }
   278         out.append("}\n");
   279     }
   280 
   281     private int generateIf(byte[] byteCodes, int i, final String test) throws IOException {
   282         int indx = i + readIntArg(byteCodes, i);
   283         out.append("if (stack.pop() ").append(test).append(" stack.pop()) { gt = " + indx);
   284         out.append("; continue; }");
   285         return i + 2;
   286     }
   287 
   288     private int readIntArg(byte[] byteCodes, int offsetInstruction) {
   289         final int indxHi = (byteCodes[offsetInstruction + 1] + 256) % 256;
   290         final int indxLo = (byteCodes[offsetInstruction + 2] + 256) % 256;
   291         return (indxHi << 16) + indxLo;
   292     }
   293     
   294     private static int countArgs(String descriptor, boolean[] hasReturnType, StringBuilder sig) {
   295         int cnt = 0;
   296         int i = 0;
   297         Boolean count = null;
   298         while (i < descriptor.length()) {
   299             char ch = descriptor.charAt(i++);
   300             switch (ch) {
   301                 case '(':
   302                     count = true;
   303                     continue;
   304                 case ')':
   305                     count = false;
   306                     continue;
   307                 case 'B': 
   308                 case 'C': 
   309                 case 'D': 
   310                 case 'F': 
   311                 case 'I': 
   312                 case 'J': 
   313                 case 'S': 
   314                 case 'Z': 
   315                     if (count) {
   316                         cnt++;
   317                         sig.append(ch);
   318                     } else {
   319                         hasReturnType[0] = true;
   320                         sig.insert(0, ch);
   321                     }
   322                     continue;
   323                 case 'V': 
   324                     assert !count;
   325                     hasReturnType[0] = false;
   326                     sig.insert(0, 'V');
   327                     continue;
   328                 case 'L':
   329                     i = descriptor.indexOf(';', i);
   330                     if (count) {
   331                         cnt++;
   332                     } else {
   333                         hasReturnType[0] = true;
   334                     }
   335                     continue;
   336                 case '[':
   337                     //arrays++;
   338                     continue;
   339                 default:
   340                     break; // invalid character
   341             }
   342         }
   343         return cnt;
   344     }
   345 }