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