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