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