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