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