src/main/java/org/apidesign/java4browser/ByteCodeToJavaScript.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Mon, 27 Aug 2012 14:36:48 +0200
changeset 6 6e4682985907
parent 5 d3193a7086e7
child 7 5b135a2f2de3
permissions -rw-r--r--
Support for xor
     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");
    83         final Code code = m.getCode();
    84         int len = code.getMaxLocals();
    85         for (int index = args.size(), i = args.size(); i < len; i++) {
    86             out.append("  var ");
    87             out.append("arg").append(String.valueOf(i)).append(";\n");
    88         }
    89         out.append(";\n  var stack = new Array(");
    90         out.append(Integer.toString(code.getMaxStack()));
    91         out.append(");\n");
    92         produceCode(code.getByteCodes());
    93         out.append("}");
    94     }
    95 
    96     private void produceCode(byte[] byteCodes) throws IOException {
    97         out.append("\nvar gt = 0;\nfor(;;) switch(gt) {\n");
    98         for (int i = 0; i < byteCodes.length; i++) {
    99             int prev = i;
   100             out.append("  case " + i).append(": ");
   101             final int c = (byteCodes[i] + 256) % 256;
   102             switch (c) {
   103                 case bc_aload_0:
   104                 case bc_iload_0:
   105                 case bc_lload_0:
   106                 case bc_fload_0:
   107                 case bc_dload_0:
   108                     out.append("stack.push(arg0);");
   109                     break;
   110                 case bc_aload_1:
   111                 case bc_iload_1:
   112                 case bc_lload_1:
   113                 case bc_fload_1:
   114                 case bc_dload_1:
   115                     out.append("stack.push(arg1);");
   116                     break;
   117                 case bc_aload_2:
   118                 case bc_iload_2:
   119                 case bc_lload_2:
   120                 case bc_fload_2:
   121                 case bc_dload_2:
   122                     out.append("stack.push(arg2);");
   123                     break;
   124                 case bc_aload_3:
   125                 case bc_iload_3:
   126                 case bc_lload_3:
   127                 case bc_fload_3:
   128                 case bc_dload_3:
   129                     out.append("stack.push(arg3);");
   130                     break;
   131                 case bc_iload:
   132                 case bc_lload:
   133                 case bc_fload:
   134                 case bc_dload:
   135                 case bc_aload: {
   136                     final int indx = (byteCodes[++i] + 256) % 256;
   137                     out.append("stack.push(arg").append(indx + ");");
   138                     break;
   139                 }
   140                 case bc_istore_0:
   141                 case bc_lstore_0:
   142                 case bc_fstore_0:
   143                 case bc_dstore_0:
   144                     out.append("arg0 = stack.pop();");
   145                     break;
   146                 case bc_istore_1:
   147                 case bc_lstore_1:
   148                 case bc_fstore_1:
   149                 case bc_dstore_1:
   150                     out.append("arg1 = stack.pop();");
   151                     break;
   152                 case bc_istore_2:
   153                 case bc_lstore_2:
   154                 case bc_fstore_2:
   155                 case bc_dstore_2:
   156                     out.append("arg2 = stack.pop();");
   157                     break;
   158                 case bc_istore_3:
   159                 case bc_lstore_3:
   160                 case bc_fstore_3:
   161                 case bc_dstore_3:
   162                     out.append("arg3 = stack.pop();");
   163                     break;
   164                 case bc_iadd:
   165                 case bc_ladd:
   166                 case bc_fadd:
   167                 case bc_dadd:
   168                     out.append("stack.push(stack.pop() + stack.pop());");
   169                     break;
   170                 case bc_isub:
   171                 case bc_lsub:
   172                 case bc_fsub:
   173                 case bc_dsub:
   174                     out.append("{ var tmp = stack.pop(); stack.push(stack.pop() - tmp); }");
   175                     break;
   176                 case bc_imul:
   177                 case bc_lmul:
   178                 case bc_fmul:
   179                 case bc_dmul:
   180                     out.append("stack.push(stack.pop() * stack.pop());");
   181                     break;
   182                 case bc_idiv:
   183                 case bc_ldiv:
   184                     out.append("{ var tmp = stack.pop(); stack.push(Math.floor(stack.pop() / tmp)); }");
   185                     break;
   186                 case bc_fdiv:
   187                 case bc_ddiv:
   188                     out.append("{ var tmp = stack.pop(); stack.push(stack.pop() / tmp); }");
   189                     break;
   190                 case bc_ixor:
   191                 case bc_lxor:
   192                     out.append("stack.push(stack.pop() ^ stack.pop());");
   193                     break;
   194                 case bc_iinc: {
   195                     final int varIndx = (byteCodes[++i] + 256) % 256;
   196                     final int incrBy = (byteCodes[++i] + 256) % 256;
   197                     if (incrBy == 1) {
   198                         out.append("arg" + varIndx).append("++;");
   199                     } else {
   200                         out.append("arg" + varIndx).append(" += " + incrBy).append(";");
   201                     }
   202                     break;
   203                 }
   204                 case bc_ireturn:
   205                 case bc_lreturn:
   206                 case bc_freturn:
   207                 case bc_dreturn:
   208                     out.append("return stack.pop();");
   209                     break;
   210                 case bc_i2l:
   211                 case bc_i2f:
   212                 case bc_i2d:
   213                 case bc_l2i:
   214                     // max int check?
   215                 case bc_l2f:
   216                 case bc_l2d:
   217                 case bc_f2d:
   218                 case bc_d2f:
   219                     out.append("/* number conversion */");
   220                     break;
   221                 case bc_f2i:
   222                 case bc_f2l:
   223                 case bc_d2i:
   224                 case bc_d2l:
   225                     out.append("stack.push(Math.floor(stack.pop()));");
   226                     break;
   227                 case bc_i2b:
   228                 case bc_i2c:
   229                 case bc_i2s:
   230                     out.append("/* number conversion */");
   231                     break;
   232                 case bc_iconst_0:
   233                 case bc_dconst_0:
   234                 case bc_lconst_0:
   235                 case bc_fconst_0:
   236                     out.append("stack.push(0);");
   237                     break;
   238                 case bc_iconst_1:
   239                 case bc_lconst_1:
   240                 case bc_fconst_1:
   241                 case bc_dconst_1:
   242                     out.append("stack.push(1);");
   243                     break;
   244                 case bc_iconst_2:
   245                 case bc_fconst_2:
   246                     out.append("stack.push(2);");
   247                     break;
   248                 case bc_iconst_3:
   249                     out.append("stack.push(3);");
   250                     break;
   251                 case bc_iconst_4:
   252                     out.append("stack.push(4);");
   253                     break;
   254                 case bc_iconst_5:
   255                     out.append("stack.push(5);");
   256                     break;
   257                 case bc_if_icmpeq: {
   258                     i = generateIf(byteCodes, i, "==");
   259                     break;
   260                 }
   261                 case bc_if_icmpne:
   262                     i = generateIf(byteCodes, i, "!=");
   263                     break;
   264                 case bc_if_icmplt:
   265                     i = generateIf(byteCodes, i, ">");
   266                     break;
   267                 case bc_if_icmple:
   268                     i = generateIf(byteCodes, i, ">=");
   269                     break;
   270                 case bc_if_icmpgt:
   271                     i = generateIf(byteCodes, i, "<");
   272                     break;
   273                 case bc_if_icmpge:
   274                     i = generateIf(byteCodes, i, "<=");
   275                     break;
   276                 case bc_goto: {
   277                     int indx = i + readIntArg(byteCodes, i);
   278                     out.append("gt = " + indx).append("; continue;");
   279                     i += 2;
   280                     break;
   281                 }
   282                 case bc_invokestatic: {
   283                     int methodIndex = readIntArg(byteCodes, i);
   284                     CPMethodInfo mi = (CPMethodInfo) jc.getConstantPool().get(methodIndex);
   285                     boolean[] hasReturn = { false };
   286                     StringBuilder signature = new StringBuilder();
   287                     int cnt = countArgs(mi.getDescriptor(), hasReturn, signature);
   288                     
   289                     if (hasReturn[0]) {
   290                         out.append("stack.push(");
   291                     }
   292                     out.append(mi.getClassName().getInternalName().replace('/', '_'));
   293                     out.append('_');
   294                     out.append(mi.getName());
   295                     out.append(signature.toString());
   296                     out.append('(');
   297                     String sep = "";
   298                     for (int j = 0; j < cnt; j++) {
   299                         out.append(sep);
   300                         out.append("stack.pop()");
   301                         sep = ", ";
   302                     }
   303                     out.append(")");
   304                     if (hasReturn[0]) {
   305                         out.append(")");
   306                     }
   307                     out.append(";");
   308                     i += 2;
   309                     break;
   310                 }
   311             }
   312             out.append(" /*");
   313             for (int j = prev; j <= i; j++) {
   314                 out.append(" ");
   315                 final int cc = (byteCodes[j] + 256) % 256;
   316                 out.append(Integer.toString(cc));
   317             }
   318             out.append("*/\n");
   319         }
   320         out.append("}\n");
   321     }
   322 
   323     private int generateIf(byte[] byteCodes, int i, final String test) throws IOException {
   324         int indx = i + readIntArg(byteCodes, i);
   325         out.append("if (stack.pop() ").append(test).append(" stack.pop()) { gt = " + indx);
   326         out.append("; continue; }");
   327         return i + 2;
   328     }
   329 
   330     private int readIntArg(byte[] byteCodes, int offsetInstruction) {
   331         final int indxHi = byteCodes[offsetInstruction + 1] << 8;
   332         final int indxLo = byteCodes[offsetInstruction + 2];
   333         return (indxHi & 0xffffff00) | (indxLo & 0xff);
   334     }
   335     
   336     private static int countArgs(String descriptor, boolean[] hasReturnType, StringBuilder sig) {
   337         int cnt = 0;
   338         int i = 0;
   339         Boolean count = null;
   340         while (i < descriptor.length()) {
   341             char ch = descriptor.charAt(i++);
   342             switch (ch) {
   343                 case '(':
   344                     count = true;
   345                     continue;
   346                 case ')':
   347                     count = false;
   348                     continue;
   349                 case 'B': 
   350                 case 'C': 
   351                 case 'D': 
   352                 case 'F': 
   353                 case 'I': 
   354                 case 'J': 
   355                 case 'S': 
   356                 case 'Z': 
   357                     if (count) {
   358                         cnt++;
   359                         sig.append(ch);
   360                     } else {
   361                         hasReturnType[0] = true;
   362                         sig.insert(0, ch);
   363                     }
   364                     continue;
   365                 case 'V': 
   366                     assert !count;
   367                     hasReturnType[0] = false;
   368                     sig.insert(0, 'V');
   369                     continue;
   370                 case 'L':
   371                     i = descriptor.indexOf(';', i);
   372                     if (count) {
   373                         cnt++;
   374                     } else {
   375                         hasReturnType[0] = true;
   376                     }
   377                     continue;
   378                 case '[':
   379                     //arrays++;
   380                     continue;
   381                 default:
   382                     break; // invalid character
   383             }
   384         }
   385         return cnt;
   386     }
   387 }