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