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