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