vm/src/main/java/org/apidesign/vm4brwsr/ByteCodeToJavaScript.java
author Jaroslav Tulach <jtulach@netbeans.org>
Mon, 12 Nov 2012 21:05:23 +0100
branchjavap
changeset 156 3bb1a148a795
parent 152 2cda429aeb49
child 162 70e7710a65dc
permissions -rw-r--r--
Double and long invocation conventions fixed
     1 /**
     2  * Back 2 Browser Bytecode Translator
     3  * Copyright (C) 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.vm4brwsr;
    19 
    20 import java.io.IOException;
    21 import java.io.InputStream;
    22 import java.util.ArrayList;
    23 import java.util.Collection;
    24 import java.util.List;
    25 import org.apidesign.bck2brwsr.core.ExtraJavaScript;
    26 import org.apidesign.bck2brwsr.core.JavaScriptBody;
    27 import sun.tools.javap.AnnotationParser;
    28 import sun.tools.javap.ClassData;
    29 import sun.tools.javap.FieldData;
    30 import sun.tools.javap.MethodData;
    31 import static sun.tools.javap.RuntimeConstants.*;
    32 
    33 /** Translator of the code inside class files to JavaScript.
    34  *
    35  * @author Jaroslav Tulach <jtulach@netbeans.org>
    36  */
    37 public final class ByteCodeToJavaScript {
    38     private final ClassData jc;
    39     private final Appendable out;
    40     private final Collection<? super String> references;
    41 
    42     private ByteCodeToJavaScript(
    43         ClassData jc, Appendable out, Collection<? super String> references
    44     ) {
    45         this.jc = jc;
    46         this.out = out;
    47         this.references = references;
    48     }
    49 
    50     /**
    51      * Converts a given class file to a JavaScript version.
    52      *
    53      * @param classFile input stream with code of the .class file
    54      * @param out a {@link StringBuilder} or similar to generate the output to
    55      * @param references a write only collection where the system adds list of
    56      *   other classes that were referenced and should be loaded in order the
    57      *   generated JavaScript code works properly. The names are in internal 
    58      *   JVM form so String is <code>java/lang/String</code>. Can be <code>null</code>
    59      *   if one is not interested in knowing references
    60      * @param scripts write only collection with names of resources to read
    61      * @return the initialization code for this class, if any. Otherwise <code>null</code>
    62      * 
    63      * @throws IOException if something goes wrong during read or write or translating
    64      */
    65     
    66     public static String compile(
    67         InputStream classFile, Appendable out,
    68         Collection<? super String> references,
    69         Collection<? super String> scripts
    70     ) throws IOException {
    71         ClassData jc = new ClassData(classFile);
    72         byte[] arrData = jc.findAnnotationData(true);
    73         String[] arr = findAnnotation(arrData, jc, ExtraJavaScript.class.getName(), "resource", "processByteCode");
    74         if (arr != null) {
    75             scripts.add(arr[0]);
    76             if ("0".equals(arr[1])) {
    77                 return null;
    78             }
    79         }
    80         ByteCodeToJavaScript compiler = new ByteCodeToJavaScript(
    81             jc, out, references
    82         );
    83         List<String> toInitilize = new ArrayList<String>();
    84         for (MethodData m : jc.getMethods()) {
    85             if (m.isStatic()) {
    86                 compiler.generateStaticMethod(m, toInitilize);
    87             } else {
    88                 compiler.generateInstanceMethod(m);
    89             }
    90         }
    91         for (FieldData v : jc.getFields()) {
    92             if (v.isStatic()) {
    93                 compiler.generateStaticField(v);
    94             }
    95         }
    96         
    97         final String className = className(jc);
    98         out.append("\nfunction ").append(className);
    99         out.append("() {");
   100         for (FieldData v : jc.getFields()) {
   101             if (!v.isStatic()) {
   102                 out.append("\n  this.fld_").
   103                     append(v.getName()).append(" = 0;");
   104             }
   105         }
   106         out.append("\n}\n\nfunction ").append(className).append("_proto() {");
   107         out.append("\n  if (").append(className).
   108             append(".prototype.$instOf_").append(className).append(") {");
   109         out.append("\n    return new ").append(className).append(";");
   110         out.append("\n  }");
   111         // ClassName sc = jc.getSuperClass();
   112         String sc = jc.getSuperClassName(); // with _
   113         if (sc != null) {
   114             out.append("\n  var p = ").append(className)
   115                .append(".prototype = ").
   116                 append(sc.replace('/', '_')).append("_proto();");
   117         } else {
   118             out.append("\n  var p = ").append(className).append(".prototype;");
   119         }
   120         for (MethodData m : jc.getMethods()) {
   121             if (!m.getName().contains("<init>") && !m.getName().contains("<cinit>")) {
   122                 compiler.generateMethodReference("\n  p.", m);
   123             }
   124         }
   125         out.append("\n  p.$instOf_").append(className).append(" = true;");
   126         for (String superInterface : jc.getSuperInterfaces()) {
   127             out.append("\n  p.$instOf_").append(superInterface.replace('/', '_')).append(" = true;");
   128         }
   129         out.append("\n  return new ").append(className).append(";");
   130         out.append("\n}");
   131         out.append("\n").append(className).append("_proto();");
   132         StringBuilder sb = new StringBuilder();
   133         for (String init : toInitilize) {
   134             sb.append("\n").append(init).append("();");
   135         }
   136         return sb.toString();
   137     }
   138     private void generateStaticMethod(MethodData m, List<String> toInitilize) throws IOException {
   139         if (javaScriptBody(m, true)) {
   140             return;
   141         }
   142         StringBuilder argsCnt = new StringBuilder();
   143         final String mn = findMethodName(m, argsCnt);
   144         out.append("\nfunction ").append(
   145             className(jc)
   146         ).append('_').append(mn);
   147         if (mn.equals("classV")) {
   148             toInitilize.add(className(jc) + '_' + mn);
   149         }
   150         out.append('(');
   151         String space = "";
   152         for (int index = 0, i = 0; i < argsCnt.length(); i++) {
   153             out.append(space);
   154             out.append("arg").append(String.valueOf(index));
   155             space = ",";
   156             final String desc = null;// XXX findDescriptor(args.get(i).getDescriptor());
   157             if (argsCnt.charAt(i) == '1') {
   158                 index += 2;
   159             } else {
   160                 index++;
   161             }
   162         }
   163         out.append(") {").append("\n");
   164         final byte[] code = m.getCode();
   165         if (code != null) {
   166             int len = m.getMaxLocals();
   167             for (int index = argsCnt.length(), i = argsCnt.length(); i < len; i++) {
   168                 out.append("  var ");
   169                 out.append("arg").append(String.valueOf(i)).append(";\n");
   170             }
   171             out.append("  var stack = new Array();\n");
   172             produceCode(code);
   173         } else {
   174             out.append("  /* no code found for ").append(m.getInternalSig()).append(" */\n");
   175         }
   176         out.append("}");
   177     }
   178     
   179     private void generateMethodReference(String prefix, MethodData m) throws IOException {
   180         final String name = findMethodName(m, new StringBuilder());
   181         out.append(prefix).append(name).append(" = ")
   182            .append(className(jc))
   183            .append('_').append(name).append(";");
   184     }
   185     
   186     private void generateInstanceMethod(MethodData m) throws IOException {
   187         if (javaScriptBody(m, false)) {
   188             return;
   189         }
   190         StringBuilder argsCnt = new StringBuilder();
   191         out.append("\nfunction ").append(
   192             className(jc)
   193         ).append('_').append(findMethodName(m, argsCnt));
   194         out.append("(arg0");
   195         String space = ",";
   196         for (int index = 1, i = 0; i < argsCnt.length(); i++) {
   197             out.append(space);
   198             out.append("arg").append(String.valueOf(index));
   199             if (argsCnt.charAt(i) == '1') {
   200                 index += 2;
   201             } else {
   202                 index++;
   203             }
   204         }
   205         out.append(") {").append("\n");
   206         final byte[] code = m.getCode();
   207         if (code != null) {
   208             int len = m.getMaxLocals();
   209             for (int index = argsCnt.length(), i = argsCnt.length(); i < len; i++) {
   210                 out.append("  var ");
   211                 out.append("arg").append(String.valueOf(i + 1)).append(";\n");
   212             }
   213             out.append(";\n  var stack = new Array();\n");
   214             produceCode(code);
   215         } else {
   216             out.append("  /* no code found for ").append(m.getInternalSig()).append(" */\n");
   217         }
   218         out.append("}");
   219     }
   220 
   221     private void produceCode(byte[] byteCodes) throws IOException {
   222         out.append("\n  var gt = 0;\n  for(;;) switch(gt) {\n");
   223         for (int i = 0; i < byteCodes.length; i++) {
   224             int prev = i;
   225             out.append("    case " + i).append(": ");
   226             final int c = readByte(byteCodes, i);
   227             switch (c) {
   228                 case opc_aload_0:
   229                 case opc_iload_0:
   230                 case opc_lload_0:
   231                 case opc_fload_0:
   232                 case opc_dload_0:
   233                     out.append("stack.push(arg0);");
   234                     break;
   235                 case opc_aload_1:
   236                 case opc_iload_1:
   237                 case opc_lload_1:
   238                 case opc_fload_1:
   239                 case opc_dload_1:
   240                     out.append("stack.push(arg1);");
   241                     break;
   242                 case opc_aload_2:
   243                 case opc_iload_2:
   244                 case opc_lload_2:
   245                 case opc_fload_2:
   246                 case opc_dload_2:
   247                     out.append("stack.push(arg2);");
   248                     break;
   249                 case opc_aload_3:
   250                 case opc_iload_3:
   251                 case opc_lload_3:
   252                 case opc_fload_3:
   253                 case opc_dload_3:
   254                     out.append("stack.push(arg3);");
   255                     break;
   256                 case opc_iload:
   257                 case opc_lload:
   258                 case opc_fload:
   259                 case opc_dload:
   260                 case opc_aload: {
   261                     final int indx = readByte(byteCodes, ++i);
   262                     out.append("stack.push(arg").append(indx + ");");
   263                     break;
   264                 }
   265                 case opc_istore:
   266                 case opc_lstore:
   267                 case opc_fstore:
   268                 case opc_dstore:
   269                 case opc_astore: {
   270                     final int indx = readByte(byteCodes, ++i);
   271                     out.append("arg" + indx).append(" = stack.pop();");
   272                     break;
   273                 }
   274                 case opc_astore_0:
   275                 case opc_istore_0:
   276                 case opc_lstore_0:
   277                 case opc_fstore_0:
   278                 case opc_dstore_0:
   279                     out.append("arg0 = stack.pop();");
   280                     break;
   281                 case opc_astore_1:
   282                 case opc_istore_1:
   283                 case opc_lstore_1:
   284                 case opc_fstore_1:
   285                 case opc_dstore_1:
   286                     out.append("arg1 = stack.pop();");
   287                     break;
   288                 case opc_astore_2:
   289                 case opc_istore_2:
   290                 case opc_lstore_2:
   291                 case opc_fstore_2:
   292                 case opc_dstore_2:
   293                     out.append("arg2 = stack.pop();");
   294                     break;
   295                 case opc_astore_3:
   296                 case opc_istore_3:
   297                 case opc_lstore_3:
   298                 case opc_fstore_3:
   299                 case opc_dstore_3:
   300                     out.append("arg3 = stack.pop();");
   301                     break;
   302                 case opc_iadd:
   303                 case opc_ladd:
   304                 case opc_fadd:
   305                 case opc_dadd:
   306                     out.append("stack.push(stack.pop() + stack.pop());");
   307                     break;
   308                 case opc_isub:
   309                 case opc_lsub:
   310                 case opc_fsub:
   311                 case opc_dsub:
   312                     out.append("{ var tmp = stack.pop(); stack.push(stack.pop() - tmp); }");
   313                     break;
   314                 case opc_imul:
   315                 case opc_lmul:
   316                 case opc_fmul:
   317                 case opc_dmul:
   318                     out.append("stack.push(stack.pop() * stack.pop());");
   319                     break;
   320                 case opc_idiv:
   321                 case opc_ldiv:
   322                     out.append("{ var tmp = stack.pop(); stack.push(Math.floor(stack.pop() / tmp)); }");
   323                     break;
   324                 case opc_fdiv:
   325                 case opc_ddiv:
   326                     out.append("{ var tmp = stack.pop(); stack.push(stack.pop() / tmp); }");
   327                     break;
   328                 case opc_iand:
   329                 case opc_land:
   330                     out.append("stack.push(stack.pop() & stack.pop());");
   331                     break;
   332                 case opc_ior:
   333                 case opc_lor:
   334                     out.append("stack.push(stack.pop() | stack.pop());");
   335                     break;
   336                 case opc_ixor:
   337                 case opc_lxor:
   338                     out.append("stack.push(stack.pop() ^ stack.pop());");
   339                     break;
   340                 case opc_ineg:
   341                 case opc_lneg:
   342                 case opc_fneg:
   343                 case opc_dneg:
   344                     out.append("stack.push(- stack.pop());");
   345                     break;
   346                 case opc_ishl:
   347                 case opc_lshl:
   348                     out.append("{ var v = stack.pop(); stack.push(stack.pop() << v); }");
   349                     break;
   350                 case opc_ishr:
   351                 case opc_lshr:
   352                     out.append("{ var v = stack.pop(); stack.push(stack.pop() >> v); }");
   353                     break;
   354                 case opc_iushr:
   355                 case opc_lushr:
   356                     out.append("{ var v = stack.pop(); stack.push(stack.pop() >>> v); }");
   357                     break;
   358                 case opc_iinc: {
   359                     final int varIndx = readByte(byteCodes, ++i);
   360                     final int incrBy = byteCodes[++i];
   361                     if (incrBy == 1) {
   362                         out.append("arg" + varIndx).append("++;");
   363                     } else {
   364                         out.append("arg" + varIndx).append(" += " + incrBy).append(";");
   365                     }
   366                     break;
   367                 }
   368                 case opc_return:
   369                     out.append("return;");
   370                     break;
   371                 case opc_ireturn:
   372                 case opc_lreturn:
   373                 case opc_freturn:
   374                 case opc_dreturn:
   375                 case opc_areturn:
   376                     out.append("return stack.pop();");
   377                     break;
   378                 case opc_i2l:
   379                 case opc_i2f:
   380                 case opc_i2d:
   381                 case opc_l2i:
   382                     // max int check?
   383                 case opc_l2f:
   384                 case opc_l2d:
   385                 case opc_f2d:
   386                 case opc_d2f:
   387                     out.append("/* number conversion */");
   388                     break;
   389                 case opc_f2i:
   390                 case opc_f2l:
   391                 case opc_d2i:
   392                 case opc_d2l:
   393                     out.append("stack.push(Math.floor(stack.pop()));");
   394                     break;
   395                 case opc_i2b:
   396                 case opc_i2c:
   397                 case opc_i2s:
   398                     out.append("/* number conversion */");
   399                     break;
   400                 case opc_aconst_null:
   401                     out.append("stack.push(null);");
   402                     break;
   403                 case opc_iconst_m1:
   404                     out.append("stack.push(-1);");
   405                     break;
   406                 case opc_iconst_0:
   407                 case opc_dconst_0:
   408                 case opc_lconst_0:
   409                 case opc_fconst_0:
   410                     out.append("stack.push(0);");
   411                     break;
   412                 case opc_iconst_1:
   413                 case opc_lconst_1:
   414                 case opc_fconst_1:
   415                 case opc_dconst_1:
   416                     out.append("stack.push(1);");
   417                     break;
   418                 case opc_iconst_2:
   419                 case opc_fconst_2:
   420                     out.append("stack.push(2);");
   421                     break;
   422                 case opc_iconst_3:
   423                     out.append("stack.push(3);");
   424                     break;
   425                 case opc_iconst_4:
   426                     out.append("stack.push(4);");
   427                     break;
   428                 case opc_iconst_5:
   429                     out.append("stack.push(5);");
   430                     break;
   431                 case opc_ldc: {
   432                     int indx = readByte(byteCodes, ++i);
   433                     String v = encodeConstant(indx);
   434                     out.append("stack.push(").append(v).append(");");
   435                     break;
   436                 }
   437                 case opc_ldc_w:
   438                 case opc_ldc2_w: {
   439                     int indx = readIntArg(byteCodes, i);
   440                     i += 2;
   441                     String v = encodeConstant(indx);
   442                     out.append("stack.push(").append(v).append(");");
   443                     break;
   444                 }
   445                 case opc_lcmp:
   446                 case opc_fcmpl:
   447                 case opc_fcmpg:
   448                 case opc_dcmpl:
   449                 case opc_dcmpg: {
   450                     out.append("{ var delta = stack.pop() - stack.pop(); stack.push(delta < 0 ?-1 : (delta == 0 ? 0 : 1)); }");
   451                     break;
   452                 }
   453                 case opc_if_acmpeq:
   454                     i = generateIf(byteCodes, i, "===");
   455                     break;
   456                 case opc_if_acmpne:
   457                     i = generateIf(byteCodes, i, "!=");
   458                     break;
   459                 case opc_if_icmpeq: {
   460                     i = generateIf(byteCodes, i, "==");
   461                     break;
   462                 }
   463                 case opc_ifeq: {
   464                     int indx = i + readIntArg(byteCodes, i);
   465                     out.append("if (stack.pop() == 0) { gt = " + indx);
   466                     out.append("; continue; }");
   467                     i += 2;
   468                     break;
   469                 }
   470                 case opc_ifne: {
   471                     int indx = i + readIntArg(byteCodes, i);
   472                     out.append("if (stack.pop() != 0) { gt = " + indx);
   473                     out.append("; continue; }");
   474                     i += 2;
   475                     break;
   476                 }
   477                 case opc_iflt: {
   478                     int indx = i + readIntArg(byteCodes, i);
   479                     out.append("if (stack.pop() < 0) { gt = " + indx);
   480                     out.append("; continue; }");
   481                     i += 2;
   482                     break;
   483                 }
   484                 case opc_ifle: {
   485                     int indx = i + readIntArg(byteCodes, i);
   486                     out.append("if (stack.pop() <= 0) { gt = " + indx);
   487                     out.append("; continue; }");
   488                     i += 2;
   489                     break;
   490                 }
   491                 case opc_ifgt: {
   492                     int indx = i + readIntArg(byteCodes, i);
   493                     out.append("if (stack.pop() > 0) { gt = " + indx);
   494                     out.append("; continue; }");
   495                     i += 2;
   496                     break;
   497                 }
   498                 case opc_ifge: {
   499                     int indx = i + readIntArg(byteCodes, i);
   500                     out.append("if (stack.pop() >= 0) { gt = " + indx);
   501                     out.append("; continue; }");
   502                     i += 2;
   503                     break;
   504                 }
   505                 case opc_ifnonnull: {
   506                     int indx = i + readIntArg(byteCodes, i);
   507                     out.append("if (stack.pop()) { gt = " + indx);
   508                     out.append("; continue; }");
   509                     i += 2;
   510                     break;
   511                 }
   512                 case opc_ifnull: {
   513                     int indx = i + readIntArg(byteCodes, i);
   514                     out.append("if (!stack.pop()) { gt = " + indx);
   515                     out.append("; continue; }");
   516                     i += 2;
   517                     break;
   518                 }
   519                 case opc_if_icmpne:
   520                     i = generateIf(byteCodes, i, "!=");
   521                     break;
   522                 case opc_if_icmplt:
   523                     i = generateIf(byteCodes, i, ">");
   524                     break;
   525                 case opc_if_icmple:
   526                     i = generateIf(byteCodes, i, ">=");
   527                     break;
   528                 case opc_if_icmpgt:
   529                     i = generateIf(byteCodes, i, "<");
   530                     break;
   531                 case opc_if_icmpge:
   532                     i = generateIf(byteCodes, i, "<=");
   533                     break;
   534                 case opc_goto: {
   535                     int indx = i + readIntArg(byteCodes, i);
   536                     out.append("gt = " + indx).append("; continue;");
   537                     i += 2;
   538                     break;
   539                 }
   540                 case opc_lookupswitch: {
   541                     int table = i / 4 * 4 + 4;
   542                     int dflt = i + readInt4(byteCodes, table);
   543                     table += 4;
   544                     int n = readInt4(byteCodes, table);
   545                     table += 4;
   546                     out.append("switch (stack.pop()) {\n");
   547                     while (n-- > 0) {
   548                         int cnstnt = readInt4(byteCodes, table);
   549                         table += 4;
   550                         int offset = i + readInt4(byteCodes, table);
   551                         table += 4;
   552                         out.append("  case " + cnstnt).append(": gt = " + offset).append("; continue;\n");
   553                     }
   554                     out.append("  default: gt = " + dflt).append("; continue;\n}");
   555                     i = table - 1;
   556                     break;
   557                 }
   558                 case opc_tableswitch: {
   559                     int table = i / 4 * 4 + 4;
   560                     int dflt = i + readInt4(byteCodes, table);
   561                     table += 4;
   562                     int low = readInt4(byteCodes, table);
   563                     table += 4;
   564                     int high = readInt4(byteCodes, table);
   565                     table += 4;
   566                     out.append("switch (stack.pop()) {\n");
   567                     while (low <= high) {
   568                         int offset = i + readInt4(byteCodes, table);
   569                         table += 4;
   570                         out.append("  case " + low).append(": gt = " + offset).append("; continue;\n");
   571                         low++;
   572                     }
   573                     out.append("  default: gt = " + dflt).append("; continue;\n}");
   574                     i = table - 1;
   575                     break;
   576                 }
   577                 case opc_invokeinterface: {
   578                     i = invokeVirtualMethod(byteCodes, i) + 2;
   579                     break;
   580                 }
   581                 case opc_invokevirtual:
   582                     i = invokeVirtualMethod(byteCodes, i);
   583                     break;
   584                 case opc_invokespecial:
   585                     i = invokeStaticMethod(byteCodes, i, false);
   586                     break;
   587                 case opc_invokestatic:
   588                     i = invokeStaticMethod(byteCodes, i, true);
   589                     break;
   590                 case opc_new: {
   591                     int indx = readIntArg(byteCodes, i);
   592                     String ci = jc.getClassName(indx);
   593                     out.append("stack.push(");
   594                     out.append("new ").append(ci.replace('/','_'));
   595                     out.append(");");
   596                     addReference(ci);
   597                     i += 2;
   598                     break;
   599                 }
   600                 case opc_newarray: {
   601                     int type = byteCodes[i++];
   602                     out.append("stack.push(new Array(stack.pop()));");
   603                     break;
   604                 }
   605                 case opc_anewarray: {
   606                     i += 2; // skip type of array
   607                     out.append("stack.push(new Array(stack.pop()));");
   608                     break;
   609                 }
   610                 case opc_multianewarray: {
   611                     i += 2;
   612                     int dim = readByte(byteCodes, ++i);
   613                     out.append("{ var a0 = new Array(stack.pop());");
   614                     for (int d = 1; d < dim; d++) {
   615                         out.append("\n  var l" + d).append(" = stack.pop();");
   616                         out.append("\n  for (var i" + d).append (" = 0; i" + d).
   617                             append(" < a" + (d - 1)).
   618                             append(".length; i" + d).append("++) {");
   619                         out.append("\n    var a" + d).
   620                             append (" = new Array(l" + d).append(");");
   621                         out.append("\n    a" + (d - 1)).append("[i" + d).append("] = a" + d).
   622                             append(";");
   623                     }
   624                     for (int d = 1; d < dim; d++) {
   625                         out.append("\n  }");
   626                     }
   627                     out.append("\nstack.push(a0); }");
   628                     break;
   629                 }
   630                 case opc_arraylength:
   631                     out.append("stack.push(stack.pop().length);");
   632                     break;
   633                 case opc_iastore:
   634                 case opc_lastore:
   635                 case opc_fastore:
   636                 case opc_dastore:
   637                 case opc_aastore:
   638                 case opc_bastore:
   639                 case opc_castore:
   640                 case opc_sastore: {
   641                     out.append("{ var value = stack.pop(); var indx = stack.pop(); stack.pop()[indx] = value; }");
   642                     break;
   643                 }
   644                 case opc_iaload:
   645                 case opc_laload:
   646                 case opc_faload:
   647                 case opc_daload:
   648                 case opc_aaload:
   649                 case opc_baload:
   650                 case opc_caload:
   651                 case opc_saload: {
   652                     out.append("{ var indx = stack.pop(); stack.push(stack.pop()[indx]); }");
   653                     break;
   654                 }
   655                 case opc_pop2:
   656                     out.append("stack.pop();");
   657                 case opc_pop:
   658                     out.append("stack.pop();");
   659                     break;
   660                 case opc_dup:
   661                     out.append("stack.push(stack[stack.length - 1]);");
   662                     break;
   663                 case opc_bipush:
   664                     out.append("stack.push(" + byteCodes[++i] + ");");
   665                     break;
   666                 case opc_sipush:
   667                     out.append("stack.push(" + readIntArg(byteCodes, i) + ");");
   668                     i += 2;
   669                     break;
   670                 case opc_getfield: {
   671                     int indx = readIntArg(byteCodes, i);
   672                     String[] fi = jc.getFieldInfoName(indx);
   673                     out.append("stack.push(stack.pop().fld_").
   674                         append(fi[1]).append(");");
   675                     i += 2;
   676                     break;
   677                 }
   678                 case opc_getstatic: {
   679                     int indx = readIntArg(byteCodes, i);
   680                     String[] fi = jc.getFieldInfoName(indx);
   681                     out.append("stack.push(").append(fi[0].replace('/', '_'));
   682                     out.append('_').append(fi[1]).append(");");
   683                     i += 2;
   684                     addReference(fi[0]);
   685                     break;
   686                 }
   687                 case opc_putstatic: {
   688                     int indx = readIntArg(byteCodes, i);
   689                     String[] fi = jc.getFieldInfoName(indx);
   690                     out.append(fi[0].replace('/', '_'));
   691                     out.append('_').append(fi[1]).append(" = stack.pop();");
   692                     i += 2;
   693                     addReference(fi[0]);
   694                     break;
   695                 }
   696                 case opc_putfield: {
   697                     int indx = readIntArg(byteCodes, i);
   698                     String[] fi = jc.getFieldInfoName(indx);
   699                     out.append("{ var v = stack.pop(); stack.pop().fld_")
   700                        .append(fi[1]).append(" = v; }");
   701                     i += 2;
   702                     break;
   703                 }
   704                 case opc_checkcast: {
   705                     int indx = readIntArg(byteCodes, i);
   706                     final String type = jc.getClassName(indx);
   707                     if (!type.startsWith("[")) {
   708                         // no way to check arrays right now
   709                         out.append("if(stack[stack.length - 1].$instOf_")
   710                            .append(type.replace('/', '_'))
   711                            .append(" != 1) throw {};"); // XXX proper exception
   712                     }
   713                     i += 2;
   714                     break;
   715                 }
   716                 case opc_instanceof: {
   717                     int indx = readIntArg(byteCodes, i);
   718                     final String type = jc.getClassName(indx);
   719                     out.append("stack.push(stack.pop().$instOf_")
   720                        .append(type.replace('/', '_'))
   721                        .append(" ? 1 : 0);");
   722                     i += 2;
   723                     break;
   724                 }
   725                 case opc_athrow: {
   726                     out.append("{ var t = stack.pop(); stack = new Array(1); stack[0] = t; throw t; }");
   727                     break;
   728                 }
   729                 default: {
   730                     out.append("throw 'unknown bytecode " + c + "';");
   731                 }
   732                     
   733             }
   734             out.append(" //");
   735             for (int j = prev; j <= i; j++) {
   736                 out.append(" ");
   737                 final int cc = readByte(byteCodes, j);
   738                 out.append(Integer.toString(cc));
   739             }
   740             out.append("\n");
   741         }
   742         out.append("  }\n");
   743     }
   744 
   745     private int generateIf(byte[] byteCodes, int i, final String test) throws IOException {
   746         int indx = i + readIntArg(byteCodes, i);
   747         out.append("if (stack.pop() ").append(test).append(" stack.pop()) { gt = " + indx);
   748         out.append("; continue; }");
   749         return i + 2;
   750     }
   751 
   752     private int readIntArg(byte[] byteCodes, int offsetInstruction) {
   753         final int indxHi = byteCodes[offsetInstruction + 1] << 8;
   754         final int indxLo = byteCodes[offsetInstruction + 2];
   755         return (indxHi & 0xffffff00) | (indxLo & 0xff);
   756     }
   757     private int readInt4(byte[] byteCodes, int offsetInstruction) {
   758         final int d = byteCodes[offsetInstruction + 0] << 24;
   759         final int c = byteCodes[offsetInstruction + 1] << 16;
   760         final int b = byteCodes[offsetInstruction + 2] << 8;
   761         final int a = byteCodes[offsetInstruction + 3];
   762         return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
   763     }
   764     private int readByte(byte[] byteCodes, int offsetInstruction) {
   765         return (byteCodes[offsetInstruction] + 256) % 256;
   766     }
   767     
   768     private static void countArgs(String descriptor, boolean[] hasReturnType, StringBuilder sig, StringBuilder cnt) {
   769         int i = 0;
   770         Boolean count = null;
   771         boolean array = false;
   772         int firstPos = sig.length();
   773         while (i < descriptor.length()) {
   774             char ch = descriptor.charAt(i++);
   775             switch (ch) {
   776                 case '(':
   777                     count = true;
   778                     continue;
   779                 case ')':
   780                     count = false;
   781                     continue;
   782                 case 'A':
   783                     array = true;
   784                     break;
   785                 case 'B': 
   786                 case 'C': 
   787                 case 'D': 
   788                 case 'F': 
   789                 case 'I': 
   790                 case 'J': 
   791                 case 'S': 
   792                 case 'Z': 
   793                     if (count) {
   794                         if (array) {
   795                             sig.append('A');
   796                         }
   797                         sig.append(ch);
   798                         if (ch == 'J' || ch == 'D') {
   799                             cnt.append('1');
   800                         } else {
   801                             cnt.append('0');
   802                         }
   803                     } else {
   804                         hasReturnType[0] = true;
   805                         sig.insert(firstPos, ch);
   806                         if (array) {
   807                             sig.insert(firstPos, 'A');
   808                         }
   809                     }
   810                     array = false;
   811                     continue;
   812                 case 'V': 
   813                     assert !count;
   814                     hasReturnType[0] = false;
   815                     sig.insert(firstPos, 'V');
   816                     continue;
   817                 case 'L':
   818                     int next = descriptor.indexOf(';', i);
   819                     if (count) {
   820                         if (array) {
   821                             sig.append('A');
   822                         }
   823                         sig.append(ch);
   824                         sig.append(descriptor.substring(i, next).replace('/', '_'));
   825                         cnt.append('0');
   826                     } else {
   827                         sig.insert(firstPos, descriptor.substring(i, next).replace('/', '_'));
   828                         sig.insert(firstPos, ch);
   829                         if (array) {
   830                             sig.insert(firstPos, 'A');
   831                         }
   832                         hasReturnType[0] = true;
   833                     }
   834                     i = next + 1;
   835                     continue;
   836                 case '[':
   837                     //arrays++;
   838                     continue;
   839                 default:
   840                     break; // invalid character
   841             }
   842         }
   843     }
   844 
   845     private void generateStaticField(FieldData v) throws IOException {
   846         out.append("\nvar ")
   847            .append(className(jc))
   848            .append('_').append(v.getName()).append(" = 0;");
   849     }
   850 
   851     private String findMethodName(MethodData m, StringBuilder cnt) {
   852         StringBuilder name = new StringBuilder();
   853         if ("<init>".equals(m.getName())) { // NOI18N
   854             name.append("cons"); // NOI18N
   855         } else if ("<clinit>".equals(m.getName())) { // NOI18N
   856             name.append("class"); // NOI18N
   857         } else {
   858             name.append(m.getName());
   859         } 
   860         
   861         boolean hasReturn[] = { false };
   862         countArgs(findDescriptor(m.getInternalSig()), hasReturn, name, cnt);
   863         return name.toString();
   864     }
   865 
   866     private String findMethodName(String[] mi, StringBuilder cnt, boolean[] hasReturn) {
   867         StringBuilder name = new StringBuilder();
   868         String descr = mi[2];//mi.getDescriptor();
   869         String nm= mi[1];
   870         if ("<init>".equals(nm)) { // NOI18N
   871             name.append("cons"); // NOI18N
   872         } else {
   873             name.append(nm);
   874         }
   875         countArgs(findDescriptor(descr), hasReturn, name, cnt);
   876         return name.toString();
   877     }
   878 
   879     private int invokeStaticMethod(byte[] byteCodes, int i, boolean isStatic)
   880     throws IOException {
   881         int methodIndex = readIntArg(byteCodes, i);
   882         String[] mi = jc.getFieldInfoName(methodIndex);
   883         boolean[] hasReturn = { false };
   884         StringBuilder cnt = new StringBuilder();
   885         String mn = findMethodName(mi, cnt, hasReturn);
   886         out.append("{ ");
   887         for (int j = cnt.length() - 1; j >= 0; j--) {
   888             out.append("var v" + j).append(" = stack.pop(); ");
   889         }
   890         
   891         if (hasReturn[0]) {
   892             out.append("stack.push(");
   893         }
   894         final String in = mi[0];
   895         out.append(in.replace('/', '_'));
   896         if (isStatic) {
   897             out.append(".prototype.");
   898         } else {
   899             out.append('_');
   900         }
   901         out.append(mn);
   902         out.append('(');
   903         String sep = "";
   904         if (!isStatic) {
   905             out.append("stack.pop()");
   906             sep = ", ";
   907         }
   908         for (int j = 0; j < cnt.length(); j++) {
   909             out.append(sep);
   910             out.append("v" + j);
   911             sep = ", ";
   912         }
   913         out.append(")");
   914         if (hasReturn[0]) {
   915             out.append(")");
   916         }
   917         out.append("; }");
   918         i += 2;
   919         addReference(in);
   920         return i;
   921     }
   922     private int invokeVirtualMethod(byte[] byteCodes, int i)
   923     throws IOException {
   924         int methodIndex = readIntArg(byteCodes, i);
   925         String[] mi = jc.getFieldInfoName(methodIndex);
   926         boolean[] hasReturn = { false };
   927         StringBuilder cnt = new StringBuilder();
   928         String mn = findMethodName(mi, cnt, hasReturn);
   929         out.append("{ ");
   930         for (int j = cnt.length() - 1; j >= 0; j--) {
   931             out.append("var v" + j).append(" = stack.pop(); ");
   932         }
   933         out.append("var self = stack.pop(); ");
   934         if (hasReturn[0]) {
   935             out.append("stack.push(");
   936         }
   937         out.append("self.");
   938         out.append(mn);
   939         out.append('(');
   940         out.append("self");
   941         for (int j = 0; j < cnt.length(); j++) {
   942             out.append(", ");
   943             out.append("v" + j);
   944         }
   945         out.append(")");
   946         if (hasReturn[0]) {
   947             out.append(")");
   948         }
   949         out.append("; }");
   950         i += 2;
   951         return i;
   952     }
   953     
   954     private void addReference(String cn) throws IOException {
   955         if (references != null) {
   956             if (references.add(cn)) {
   957                 out.append(" /* needs ").append(cn).append(" */");
   958             }
   959         }
   960     }
   961 
   962     private void outType(String d, StringBuilder out) {
   963         int arr = 0;
   964         while (d.charAt(0) == '[') {
   965             out.append('A');
   966             d = d.substring(1);
   967         }
   968         if (d.charAt(0) == 'L') {
   969             assert d.charAt(d.length() - 1) == ';';
   970             out.append(d.replace('/', '_').substring(0, d.length() - 1));
   971         } else {
   972             out.append(d);
   973         }
   974     }
   975 
   976     private String encodeConstant(int entryIndex) {
   977         String s = jc.stringValue(entryIndex, true);
   978         return s;
   979     }
   980 
   981     private String findDescriptor(String d) {
   982         return d.replace('[', 'A');
   983     }
   984 
   985     private boolean javaScriptBody(MethodData m, boolean isStatic) throws IOException {
   986         byte[] arr = m.findAnnotationData(true);
   987         if (arr == null) {
   988             return false;
   989         }
   990         final String jvmType = "L" + JavaScriptBody.class.getName().replace('.', '/') + ";";
   991         class P extends AnnotationParser {
   992             int cnt;
   993             String[] args = new String[30];
   994             String body;
   995             
   996             @Override
   997             protected void visitAttr(String type, String attr, String value) {
   998                 if (type.equals(jvmType)) {
   999                     if ("body".equals(attr)) {
  1000                         body = value;
  1001                     } else if ("args".equals(attr)) {
  1002                         args[cnt++] = value;
  1003                     } else {
  1004                         throw new IllegalArgumentException(attr);
  1005                     }
  1006                 }
  1007             }
  1008         }
  1009         P p = new P();
  1010         p.parse(arr, jc);
  1011         if (p.body == null) {
  1012             return false;
  1013         }
  1014         StringBuilder cnt = new StringBuilder();
  1015         out.append("\nfunction ").append(className(jc)).append('_').
  1016             append(findMethodName(m, cnt));
  1017         out.append("(");
  1018         String space;
  1019         int index;
  1020         if (!isStatic) {                
  1021             out.append(p.args[0]);
  1022             space = ",";
  1023             index = 1;
  1024         } else {
  1025             space = "";
  1026             index = 0;
  1027         }
  1028         for (int i = 0; i < cnt.length(); i++) {
  1029             out.append(space);
  1030             out.append(p.args[index]);
  1031             index++;
  1032             space = ",";
  1033         }
  1034         out.append(") {").append("\n");
  1035         out.append(p.body);
  1036         out.append("\n}\n");
  1037         return true;
  1038     }
  1039     private static String className(ClassData jc) {
  1040         //return jc.getName().getInternalName().replace('/', '_');
  1041         return jc.getClassName().replace('/', '_');
  1042     }
  1043     
  1044     private static String[] findAnnotation(
  1045         byte[] arr, ClassData cd, final String className, 
  1046         final String... attrNames
  1047     ) throws IOException {
  1048         if (arr == null) {
  1049             return null;
  1050         }
  1051         final String[] values = new String[attrNames.length];
  1052         final boolean[] found = { false };
  1053         final String jvmType = "L" + className.replace('.', '/') + ";";
  1054         AnnotationParser ap = new AnnotationParser() {
  1055             @Override
  1056             protected void visitAttr(String type, String attr, String value) {
  1057                 if (type.equals(jvmType)) {
  1058                     found[0] = true;
  1059                     for (int i = 0; i < attrNames.length; i++) {
  1060                         if (attrNames[i].equals(attr)) {
  1061                             values[i] = value;
  1062                         }
  1063                     }
  1064                 }
  1065             }
  1066             
  1067         };
  1068         ap.parse(arr, cd);
  1069         return found[0] ? values : null;
  1070     }
  1071 }