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