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