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