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