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