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