vm/src/main/java/org/apidesign/vm4brwsr/ByteCodeToJavaScript.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Mon, 21 Jan 2013 15:56:54 +0100
branchmodel
changeset 509 ff9e65d1748b
parent 503 80a388c8c27b
child 567 62dd2c794431
permissions -rw-r--r--
Inclusion of knockout.js requires class definitions to end with ';'
     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 org.apidesign.javap.StackMapIterator;
    28 import static org.apidesign.javap.RuntimeConstants.*;
    29 import org.apidesign.javap.TrapData;
    30 import org.apidesign.javap.TrapDataIterator;
    31 
    32 /** Translator of the code inside class files to JavaScript.
    33  *
    34  * @author Jaroslav Tulach <jtulach@netbeans.org>
    35  */
    36 abstract class ByteCodeToJavaScript {
    37     private ClassData jc;
    38     final Appendable out;
    39 
    40     protected ByteCodeToJavaScript(Appendable out) {
    41         this.out = out;
    42     }
    43     
    44     /* Collects additional required resources.
    45      * 
    46      * @param internalClassName classes that were referenced and should be loaded in order the
    47      *   generated JavaScript code works properly. The names are in internal 
    48      *   JVM form so String is <code>java/lang/String</code>. 
    49      */
    50     protected abstract boolean requireReference(String internalClassName);
    51     
    52     /*
    53      * @param resourcePath name of resources to read
    54      */
    55     protected abstract void requireScript(String resourcePath) throws IOException;
    56     
    57     /** Allows subclasses to redefine what field a function representing a
    58      * class gets assigned. By default it returns the suggested name followed
    59      * by <code>" = "</code>;
    60      * 
    61      * @param className suggested name of the class
    62      */
    63     /* protected */ String assignClass(String className) {
    64         return className + " = ";
    65     }
    66     /* protected */ String accessClass(String classOperation) {
    67         return classOperation;
    68     }
    69     
    70     /** Prints out a debug message. 
    71      * 
    72      * @param msg the message
    73      * @return true if the message has been printed
    74      * @throws IOException 
    75      */
    76     boolean debug(String msg) throws IOException {
    77         out.append(msg);
    78         return true;
    79     }
    80 
    81     /**
    82      * Converts a given class file to a JavaScript version.
    83      *
    84      * @param classFile input stream with code of the .class file
    85      * @return the initialization code for this class, if any. Otherwise <code>null</code>
    86      * 
    87      * @throws IOException if something goes wrong during read or write or translating
    88      */
    89     
    90     public String compile(InputStream classFile) throws IOException {
    91         this.jc = new ClassData(classFile);
    92         if (jc.getMajor_version() < 50) {
    93             throw new IOException("Can't compile " + jc.getClassName() + ". Class file version " + jc.getMajor_version() + "."
    94                 + jc.getMinor_version() + " - recompile with -target 1.6 (at least)."
    95             );
    96         }
    97         byte[] arrData = jc.findAnnotationData(true);
    98         String[] arr = findAnnotation(arrData, jc, 
    99             "org.apidesign.bck2brwsr.core.ExtraJavaScript", 
   100             "resource", "processByteCode"
   101         );
   102         if (arr != null) {
   103             requireScript(arr[0]);
   104             if ("0".equals(arr[1])) {
   105                 return null;
   106             }
   107         }
   108         String[] proto = findAnnotation(arrData, jc, 
   109             "org.apidesign.bck2brwsr.core.JavaScriptPrototype", 
   110             "container", "prototype"
   111         );
   112         StringArray toInitilize = new StringArray();
   113         final String className = className(jc);
   114         out.append("\n\n").append(assignClass(className));
   115         out.append("function CLS() {");
   116         out.append("\n  if (!CLS.prototype.$instOf_").append(className).append(") {");
   117         for (FieldData v : jc.getFields()) {
   118             if (v.isStatic()) {
   119                 out.append("\n  CLS.").append(v.getName()).append(initField(v));
   120             }
   121         }
   122         if (proto == null) {
   123             String sc = jc.getSuperClassName(); // with _
   124             out.append("\n    var pp = ").
   125                 append(accessClass(sc.replace('/', '_'))).append("(true);");
   126             out.append("\n    var p = CLS.prototype = pp;");
   127             out.append("\n    var c = p;");
   128             out.append("\n    var sprcls = pp.constructor.$class;");
   129         } else {
   130             out.append("\n    var p = CLS.prototype = ").append(proto[1]).append(";");
   131             if (proto[0] == null) {
   132                 proto[0] = "p";
   133             }
   134             out.append("\n    var c = ").append(proto[0]).append(";");
   135             out.append("\n    var sprcls = null;");
   136         }
   137         for (MethodData m : jc.getMethods()) {
   138             byte[] onlyArr = m.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             String prefix;
   151             String mn;
   152             if (m.isStatic()) {
   153                 prefix = "\n    c.";
   154                 mn = generateStaticMethod(prefix, m, toInitilize);
   155             } else {
   156                 if (m.isConstructor()) {
   157                     prefix = "\n    CLS.";
   158                     mn = generateInstanceMethod(prefix, m);
   159                 } else {
   160                     prefix = "\n    c.";
   161                     mn = generateInstanceMethod(prefix, m);
   162                 }
   163             }
   164             byte[] runAnno = m.findAnnotationData(false);
   165             if (runAnno != null) {
   166                 out.append(prefix).append(mn).append(".anno = {");
   167                 generateAnno(jc, out, runAnno);
   168                 out.append("\n    };");
   169             }
   170             out.append(prefix).append(mn).append(".access = " + m.getAccess()).append(";");
   171         }
   172         out.append("\n    c.constructor = CLS;");
   173         out.append("\n    c.$instOf_").append(className).append(" = true;");
   174         for (String superInterface : jc.getSuperInterfaces()) {
   175             out.append("\n    c.$instOf_").append(superInterface.replace('/', '_')).append(" = true;");
   176         }
   177         out.append("\n    CLS.$class = ");
   178         out.append(accessClass("java_lang_Class(true);"));
   179         out.append("\n    CLS.$class.jvmName = '").append(jc.getClassName()).append("';");
   180         out.append("\n    CLS.$class.superclass = sprcls;");
   181         out.append("\n    CLS.$class.access = ").append(jc.getAccessFlags()+";");
   182         out.append("\n    CLS.$class.cnstr = CLS;");
   183         byte[] classAnno = jc.findAnnotationData(false);
   184         if (classAnno != null) {
   185             out.append("\n    CLS.$class.anno = {");
   186             generateAnno(jc, out, classAnno);
   187             out.append("\n    };");
   188         }
   189         out.append("\n  }");
   190         out.append("\n  if (arguments.length === 0) {");
   191         out.append("\n    if (!(this instanceof CLS)) {");
   192         out.append("\n      return new CLS();");
   193         out.append("\n    }");
   194         for (FieldData v : jc.getFields()) {
   195             byte[] onlyArr = v.findAnnotationData(true);
   196             String[] only = findAnnotation(onlyArr, jc, 
   197                 "org.apidesign.bck2brwsr.core.JavaScriptOnly", 
   198                 "name", "value"
   199             );
   200             if (only != null) {
   201                 if (only[0] != null && only[1] != null) {
   202                     out.append("\n    p.").append(only[0]).append(" = ")
   203                         .append(only[1]).append(";");
   204                 }
   205                 continue;
   206             }
   207             if (!v.isStatic()) {
   208                 out.append("\n    this.fld_").
   209                     append(v.getName()).append(initField(v));
   210             }
   211         }
   212         out.append("\n    return this;");
   213         out.append("\n  }");
   214         out.append("\n  return arguments[0] ? new CLS() : CLS.prototype;");
   215         out.append("\n};");
   216         StringBuilder sb = new StringBuilder();
   217         for (String init : toInitilize.toArray()) {
   218             sb.append("\n").append(init).append("();");
   219         }
   220         return sb.toString();
   221     }
   222     private String generateStaticMethod(String prefix, MethodData m, StringArray toInitilize) throws IOException {
   223         String jsb = javaScriptBody(prefix, m, true);
   224         if (jsb != null) {
   225             return jsb;
   226         }
   227         final String mn = findMethodName(m, new StringBuilder());
   228         if (mn.equals("class__V")) {
   229             toInitilize.add(accessClass(className(jc)) + "(false)." + mn);
   230         }
   231         generateMethod(prefix, mn, m);
   232         return mn;
   233     }
   234 
   235     private String generateInstanceMethod(String prefix, MethodData m) throws IOException {
   236         String jsb = javaScriptBody(prefix, m, false);
   237         if (jsb != null) {
   238             return jsb;
   239         }
   240         final String mn = findMethodName(m, new StringBuilder());
   241         generateMethod(prefix, mn, m);
   242         return mn;
   243     }
   244 
   245     private void generateMethod(String prefix, String name, MethodData m)
   246             throws IOException {
   247         final StackMapIterator stackMapIterator = m.createStackMapIterator();
   248         TrapDataIterator trap = m.getTrapDataIterator();
   249         final LocalsMapper lmapper =
   250                 new LocalsMapper(stackMapIterator.getArguments());
   251 
   252         out.append(prefix).append(name).append(" = function(");
   253         lmapper.outputArguments(out, m.isStatic());
   254         out.append(") {").append("\n");
   255 
   256         final byte[] byteCodes = m.getCode();
   257         if (byteCodes == null) {
   258             out.append("  throw 'no code found for ")
   259                .append(jc.getClassName()).append('.')
   260                .append(m.getName()).append("';\n");
   261             out.append("};");
   262             return;
   263         }
   264 
   265         final StackMapper smapper = new StackMapper();
   266 
   267         if (!m.isStatic()) {
   268             out.append("  var ").append(" lcA0 = this;\n");
   269         }
   270 
   271         int lastStackFrame = -1;
   272         TrapData[] previousTrap = null;
   273         
   274         out.append("\n  var gt = 0;\n  for(;;) switch(gt) {\n");
   275         for (int i = 0; i < byteCodes.length; i++) {
   276             int prev = i;
   277             stackMapIterator.advanceTo(i);
   278             boolean changeInCatch = trap.advanceTo(i);
   279             if (changeInCatch || lastStackFrame != stackMapIterator.getFrameIndex()) {
   280                 if (previousTrap != null) {
   281                     generateCatch(previousTrap);
   282                     previousTrap = null;
   283                 }
   284             }
   285             if (lastStackFrame != stackMapIterator.getFrameIndex()) {
   286                 lastStackFrame = stackMapIterator.getFrameIndex();
   287                 lmapper.syncWithFrameLocals(stackMapIterator.getFrameLocals());
   288                 smapper.syncWithFrameStack(stackMapIterator.getFrameStack());
   289                 out.append("    case " + i).append(": ");            
   290                 changeInCatch = true;
   291             } else {
   292                 debug("    /* " + i + " */ ");
   293             }
   294             if (changeInCatch && trap.useTry()) {
   295                 out.append("try {");
   296                 previousTrap = trap.current();
   297             }
   298             final int c = readByte(byteCodes, i);
   299             switch (c) {
   300                 case opc_aload_0:
   301                     emit(out, "var @1 = @2;", smapper.pushA(), lmapper.getA(0));
   302                     break;
   303                 case opc_iload_0:
   304                     emit(out, "var @1 = @2;", smapper.pushI(), lmapper.getI(0));
   305                     break;
   306                 case opc_lload_0:
   307                     emit(out, "var @1 = @2;", smapper.pushL(), lmapper.getL(0));
   308                     break;
   309                 case opc_fload_0:
   310                     emit(out, "var @1 = @2;", smapper.pushF(), lmapper.getF(0));
   311                     break;
   312                 case opc_dload_0:
   313                     emit(out, "var @1 = @2;", smapper.pushD(), lmapper.getD(0));
   314                     break;
   315                 case opc_aload_1:
   316                     emit(out, "var @1 = @2;", smapper.pushA(), lmapper.getA(1));
   317                     break;
   318                 case opc_iload_1:
   319                     emit(out, "var @1 = @2;", smapper.pushI(), lmapper.getI(1));
   320                     break;
   321                 case opc_lload_1:
   322                     emit(out, "var @1 = @2;", smapper.pushL(), lmapper.getL(1));
   323                     break;
   324                 case opc_fload_1:
   325                     emit(out, "var @1 = @2;", smapper.pushF(), lmapper.getF(1));
   326                     break;
   327                 case opc_dload_1:
   328                     emit(out, "var @1 = @2;", smapper.pushD(), lmapper.getD(1));
   329                     break;
   330                 case opc_aload_2:
   331                     emit(out, "var @1 = @2;", smapper.pushA(), lmapper.getA(2));
   332                     break;
   333                 case opc_iload_2:
   334                     emit(out, "var @1 = @2;", smapper.pushI(), lmapper.getI(2));
   335                     break;
   336                 case opc_lload_2:
   337                     emit(out, "var @1 = @2;", smapper.pushL(), lmapper.getL(2));
   338                     break;
   339                 case opc_fload_2:
   340                     emit(out, "var @1 = @2;", smapper.pushF(), lmapper.getF(2));
   341                     break;
   342                 case opc_dload_2:
   343                     emit(out, "var @1 = @2;", smapper.pushD(), lmapper.getD(2));
   344                     break;
   345                 case opc_aload_3:
   346                     emit(out, "var @1 = @2;", smapper.pushA(), lmapper.getA(3));
   347                     break;
   348                 case opc_iload_3:
   349                     emit(out, "var @1 = @2;", smapper.pushI(), lmapper.getI(3));
   350                     break;
   351                 case opc_lload_3:
   352                     emit(out, "var @1 = @2;", smapper.pushL(), lmapper.getL(3));
   353                     break;
   354                 case opc_fload_3:
   355                     emit(out, "var @1 = @2;", smapper.pushF(), lmapper.getF(3));
   356                     break;
   357                 case opc_dload_3:
   358                     emit(out, "var @1 = @2;", smapper.pushD(), lmapper.getD(3));
   359                     break;
   360                 case opc_iload: {
   361                     final int indx = readByte(byteCodes, ++i);
   362                     emit(out, "var @1 = @2;",
   363                          smapper.pushI(), lmapper.getI(indx));
   364                     break;
   365                 }
   366                 case opc_lload: {
   367                     final int indx = readByte(byteCodes, ++i);
   368                     emit(out, "var @1 = @2;",
   369                          smapper.pushL(), lmapper.getL(indx));
   370                     break;
   371                 }
   372                 case opc_fload: {
   373                     final int indx = readByte(byteCodes, ++i);
   374                     emit(out, "var @1 = @2;",
   375                          smapper.pushF(), lmapper.getF(indx));
   376                     break;
   377                 }
   378                 case opc_dload: {
   379                     final int indx = readByte(byteCodes, ++i);
   380                     emit(out, "var @1 = @2;",
   381                          smapper.pushD(), lmapper.getD(indx));
   382                     break;
   383                 }
   384                 case opc_aload: {
   385                     final int indx = readByte(byteCodes, ++i);
   386                     emit(out, "var @1 = @2;",
   387                          smapper.pushA(), lmapper.getA(indx));
   388                     break;
   389                 }
   390                 case opc_istore: {
   391                     final int indx = readByte(byteCodes, ++i);
   392                     emit(out, "var @1 = @2;",
   393                          lmapper.setI(indx), smapper.popI());
   394                     break;
   395                 }
   396                 case opc_lstore: {
   397                     final int indx = readByte(byteCodes, ++i);
   398                     emit(out, "var @1 = @2;",
   399                          lmapper.setL(indx), smapper.popL());
   400                     break;
   401                 }
   402                 case opc_fstore: {
   403                     final int indx = readByte(byteCodes, ++i);
   404                     emit(out, "var @1 = @2;",
   405                          lmapper.setF(indx), smapper.popF());
   406                     break;
   407                 }
   408                 case opc_dstore: {
   409                     final int indx = readByte(byteCodes, ++i);
   410                     emit(out, "var @1 = @2;",
   411                          lmapper.setD(indx), smapper.popD());
   412                     break;
   413                 }
   414                 case opc_astore: {
   415                     final int indx = readByte(byteCodes, ++i);
   416                     emit(out, "var @1 = @2;",
   417                          lmapper.setA(indx), smapper.popA());
   418                     break;
   419                 }
   420                 case opc_astore_0:
   421                     emit(out, "var @1 = @2;", lmapper.setA(0), smapper.popA());
   422                     break;
   423                 case opc_istore_0:
   424                     emit(out, "var @1 = @2;", lmapper.setI(0), smapper.popI());
   425                     break;
   426                 case opc_lstore_0:
   427                     emit(out, "var @1 = @2;", lmapper.setL(0), smapper.popL());
   428                     break;
   429                 case opc_fstore_0:
   430                     emit(out, "var @1 = @2;", lmapper.setF(0), smapper.popF());
   431                     break;
   432                 case opc_dstore_0:
   433                     emit(out, "var @1 = @2;", lmapper.setD(0), smapper.popD());
   434                     break;
   435                 case opc_astore_1:
   436                     emit(out, "var @1 = @2;", lmapper.setA(1), smapper.popA());
   437                     break;
   438                 case opc_istore_1:
   439                     emit(out, "var @1 = @2;", lmapper.setI(1), smapper.popI());
   440                     break;
   441                 case opc_lstore_1:
   442                     emit(out, "var @1 = @2;", lmapper.setL(1), smapper.popL());
   443                     break;
   444                 case opc_fstore_1:
   445                     emit(out, "var @1 = @2;", lmapper.setF(1), smapper.popF());
   446                     break;
   447                 case opc_dstore_1:
   448                     emit(out, "var @1 = @2;", lmapper.setD(1), smapper.popD());
   449                     break;
   450                 case opc_astore_2:
   451                     emit(out, "var @1 = @2;", lmapper.setA(2), smapper.popA());
   452                     break;
   453                 case opc_istore_2:
   454                     emit(out, "var @1 = @2;", lmapper.setI(2), smapper.popI());
   455                     break;
   456                 case opc_lstore_2:
   457                     emit(out, "var @1 = @2;", lmapper.setL(2), smapper.popL());
   458                     break;
   459                 case opc_fstore_2:
   460                     emit(out, "var @1 = @2;", lmapper.setF(2), smapper.popF());
   461                     break;
   462                 case opc_dstore_2:
   463                     emit(out, "var @1 = @2;", lmapper.setD(2), smapper.popD());
   464                     break;
   465                 case opc_astore_3:
   466                     emit(out, "var @1 = @2;", lmapper.setA(3), smapper.popA());
   467                     break;
   468                 case opc_istore_3:
   469                     emit(out, "var @1 = @2;", lmapper.setI(3), smapper.popI());
   470                     break;
   471                 case opc_lstore_3:
   472                     emit(out, "var @1 = @2;", lmapper.setL(3), smapper.popL());
   473                     break;
   474                 case opc_fstore_3:
   475                     emit(out, "var @1 = @2;", lmapper.setF(3), smapper.popF());
   476                     break;
   477                 case opc_dstore_3:
   478                     emit(out, "var @1 = @2;", lmapper.setD(3), smapper.popD());
   479                     break;
   480                 case opc_iadd:
   481                     emit(out, "@1 = @1.add32(@2);", smapper.getI(1), smapper.popI());
   482                     break;
   483                 case opc_ladd:
   484                     emit(out, "@1 += @2;", smapper.getL(1), smapper.popL());
   485                     break;
   486                 case opc_fadd:
   487                     emit(out, "@1 += @2;", smapper.getF(1), smapper.popF());
   488                     break;
   489                 case opc_dadd:
   490                     emit(out, "@1 += @2;", smapper.getD(1), smapper.popD());
   491                     break;
   492                 case opc_isub:
   493                     emit(out, "@1 = @1.sub32(@2);", smapper.getI(1), smapper.popI());
   494                     break;
   495                 case opc_lsub:
   496                     emit(out, "@1 -= @2;", smapper.getL(1), smapper.popL());
   497                     break;
   498                 case opc_fsub:
   499                     emit(out, "@1 -= @2;", smapper.getF(1), smapper.popF());
   500                     break;
   501                 case opc_dsub:
   502                     emit(out, "@1 -= @2;", smapper.getD(1), smapper.popD());
   503                     break;
   504                 case opc_imul:
   505                     emit(out, "@1 = @1.mul32(@2);", smapper.getI(1), smapper.popI());
   506                     break;
   507                 case opc_lmul:
   508                     emit(out, "@1 *= @2;", smapper.getL(1), smapper.popL());
   509                     break;
   510                 case opc_fmul:
   511                     emit(out, "@1 *= @2;", smapper.getF(1), smapper.popF());
   512                     break;
   513                 case opc_dmul:
   514                     emit(out, "@1 *= @2;", smapper.getD(1), smapper.popD());
   515                     break;
   516                 case opc_idiv:
   517                     emit(out, "@1 = Math.floor(@1 / @2);",
   518                          smapper.getI(1), smapper.popI());
   519                     break;
   520                 case opc_ldiv:
   521                     emit(out, "@1 = Math.floor(@1 / @2);",
   522                          smapper.getL(1), smapper.popL());
   523                     break;
   524                 case opc_fdiv:
   525                     emit(out, "@1 /= @2;", smapper.getF(1), smapper.popF());
   526                     break;
   527                 case opc_ddiv:
   528                     emit(out, "@1 /= @2;", smapper.getD(1), smapper.popD());
   529                     break;
   530                 case opc_irem:
   531                     emit(out, "@1 %= @2;", smapper.getI(1), smapper.popI());
   532                     break;
   533                 case opc_lrem:
   534                     emit(out, "@1 %= @2;", smapper.getL(1), smapper.popL());
   535                     break;
   536                 case opc_frem:
   537                     emit(out, "@1 %= @2;", smapper.getF(1), smapper.popF());
   538                     break;
   539                 case opc_drem:
   540                     emit(out, "@1 %= @2;", smapper.getD(1), smapper.popD());
   541                     break;
   542                 case opc_iand:
   543                     emit(out, "@1 &= @2;", smapper.getI(1), smapper.popI());
   544                     break;
   545                 case opc_land:
   546                     emit(out, "@1 &= @2;", smapper.getL(1), smapper.popL());
   547                     break;
   548                 case opc_ior:
   549                     emit(out, "@1 |= @2;", smapper.getI(1), smapper.popI());
   550                     break;
   551                 case opc_lor:
   552                     emit(out, "@1 |= @2;", smapper.getL(1), smapper.popL());
   553                     break;
   554                 case opc_ixor:
   555                     emit(out, "@1 ^= @2;", smapper.getI(1), smapper.popI());
   556                     break;
   557                 case opc_lxor:
   558                     emit(out, "@1 ^= @2;", smapper.getL(1), smapper.popL());
   559                     break;
   560                 case opc_ineg:
   561                     emit(out, "@1 = -@1;", smapper.getI(0));
   562                     break;
   563                 case opc_lneg:
   564                     emit(out, "@1 = -@1;", smapper.getL(0));
   565                     break;
   566                 case opc_fneg:
   567                     emit(out, "@1 = -@1;", smapper.getF(0));
   568                     break;
   569                 case opc_dneg:
   570                     emit(out, "@1 = -@1;", smapper.getD(0));
   571                     break;
   572                 case opc_ishl:
   573                     emit(out, "@1 <<= @2;", smapper.getI(1), smapper.popI());
   574                     break;
   575                 case opc_lshl:
   576                     emit(out, "@1 <<= @2;", smapper.getL(1), smapper.popI());
   577                     break;
   578                 case opc_ishr:
   579                     emit(out, "@1 >>= @2;", smapper.getI(1), smapper.popI());
   580                     break;
   581                 case opc_lshr:
   582                     emit(out, "@1 >>= @2;", smapper.getL(1), smapper.popI());
   583                     break;
   584                 case opc_iushr:
   585                     emit(out, "@1 >>>= @2;", smapper.getI(1), smapper.popI());
   586                     break;
   587                 case opc_lushr:
   588                     emit(out, "@1 >>>= @2;", smapper.getL(1), smapper.popI());
   589                     break;
   590                 case opc_iinc: {
   591                     final int varIndx = readByte(byteCodes, ++i);
   592                     final int incrBy = byteCodes[++i];
   593                     if (incrBy == 1) {
   594                         emit(out, "@1++;", lmapper.getI(varIndx));
   595                     } else {
   596                         emit(out, "@1 += @2;",
   597                              lmapper.getI(varIndx),
   598                              Integer.toString(incrBy));
   599                     }
   600                     break;
   601                 }
   602                 case opc_return:
   603                     emit(out, "return;");
   604                     break;
   605                 case opc_ireturn:
   606                     emit(out, "return @1;", smapper.popI());
   607                     break;
   608                 case opc_lreturn:
   609                     emit(out, "return @1;", smapper.popL());
   610                     break;
   611                 case opc_freturn:
   612                     emit(out, "return @1;", smapper.popF());
   613                     break;
   614                 case opc_dreturn:
   615                     emit(out, "return @1;", smapper.popD());
   616                     break;
   617                 case opc_areturn:
   618                     emit(out, "return @1;", smapper.popA());
   619                     break;
   620                 case opc_i2l:
   621                     emit(out, "var @2 = @1;", smapper.popI(), smapper.pushL());
   622                     break;
   623                 case opc_i2f:
   624                     emit(out, "var @2 = @1;", smapper.popI(), smapper.pushF());
   625                     break;
   626                 case opc_i2d:
   627                     emit(out, "var @2 = @1;", smapper.popI(), smapper.pushD());
   628                     break;
   629                 case opc_l2i:
   630                     emit(out, "var @2 = @1;", smapper.popL(), smapper.pushI());
   631                     break;
   632                     // max int check?
   633                 case opc_l2f:
   634                     emit(out, "var @2 = @1;", smapper.popL(), smapper.pushF());
   635                     break;
   636                 case opc_l2d:
   637                     emit(out, "var @2 = @1;", smapper.popL(), smapper.pushD());
   638                     break;
   639                 case opc_f2d:
   640                     emit(out, "var @2 = @1;", smapper.popF(), smapper.pushD());
   641                     break;
   642                 case opc_d2f:
   643                     emit(out, "var @2 = @1;", smapper.popD(), smapper.pushF());
   644                     break;
   645                 case opc_f2i:
   646                     emit(out, "var @2 = Math.floor(@1);",
   647                          smapper.popF(), smapper.pushI());
   648                     break;
   649                 case opc_f2l:
   650                     emit(out, "var @2 = Math.floor(@1);",
   651                          smapper.popF(), smapper.pushL());
   652                     break;
   653                 case opc_d2i:
   654                     emit(out, "var @2 = Math.floor(@1);",
   655                          smapper.popD(), smapper.pushI());
   656                     break;
   657                 case opc_d2l:
   658                     emit(out, "var @2 = Math.floor(@1);",
   659                          smapper.popD(), smapper.pushL());
   660                     break;
   661                 case opc_i2b:
   662                     emit(out, "var @1 = @1.toInt8();", smapper.getI(0));
   663                     break;
   664                 case opc_i2c:
   665                     out.append("{ /* number conversion */ }");
   666                     break;
   667                 case opc_i2s:
   668                     emit(out, "var @1 = @1.toInt16();", smapper.getI(0));
   669                     break;
   670                 case opc_aconst_null:
   671                     emit(out, "var @1 = null;", smapper.pushA());
   672                     break;
   673                 case opc_iconst_m1:
   674                     emit(out, "var @1 = -1;", smapper.pushI());
   675                     break;
   676                 case opc_iconst_0:
   677                     emit(out, "var @1 = 0;", smapper.pushI());
   678                     break;
   679                 case opc_dconst_0:
   680                     emit(out, "var @1 = 0;", smapper.pushD());
   681                     break;
   682                 case opc_lconst_0:
   683                     emit(out, "var @1 = 0;", smapper.pushL());
   684                     break;
   685                 case opc_fconst_0:
   686                     emit(out, "var @1 = 0;", smapper.pushF());
   687                     break;
   688                 case opc_iconst_1:
   689                     emit(out, "var @1 = 1;", smapper.pushI());
   690                     break;
   691                 case opc_lconst_1:
   692                     emit(out, "var @1 = 1;", smapper.pushL());
   693                     break;
   694                 case opc_fconst_1:
   695                     emit(out, "var @1 = 1;", smapper.pushF());
   696                     break;
   697                 case opc_dconst_1:
   698                     emit(out, "var @1 = 1;", smapper.pushD());
   699                     break;
   700                 case opc_iconst_2:
   701                     emit(out, "var @1 = 2;", smapper.pushI());
   702                     break;
   703                 case opc_fconst_2:
   704                     emit(out, "var @1 = 2;", smapper.pushF());
   705                     break;
   706                 case opc_iconst_3:
   707                     emit(out, "var @1 = 3;", smapper.pushI());
   708                     break;
   709                 case opc_iconst_4:
   710                     emit(out, "var @1 = 4;", smapper.pushI());
   711                     break;
   712                 case opc_iconst_5:
   713                     emit(out, "var @1 = 5;", smapper.pushI());
   714                     break;
   715                 case opc_ldc: {
   716                     int indx = readByte(byteCodes, ++i);
   717                     String v = encodeConstant(indx);
   718                     int type = VarType.fromConstantType(jc.getTag(indx));
   719                     emit(out, "var @1 = @2;", smapper.pushT(type), v);
   720                     break;
   721                 }
   722                 case opc_ldc_w:
   723                 case opc_ldc2_w: {
   724                     int indx = readIntArg(byteCodes, i);
   725                     i += 2;
   726                     String v = encodeConstant(indx);
   727                     int type = VarType.fromConstantType(jc.getTag(indx));
   728                     emit(out, "var @1 = @2;", smapper.pushT(type), v);
   729                     break;
   730                 }
   731                 case opc_lcmp:
   732                     emit(out, "var @3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
   733                          smapper.popL(), smapper.popL(), smapper.pushI());
   734                     break;
   735                 case opc_fcmpl:
   736                 case opc_fcmpg:
   737                     emit(out, "var @3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
   738                          smapper.popF(), smapper.popF(), smapper.pushI());
   739                     break;
   740                 case opc_dcmpl:
   741                 case opc_dcmpg:
   742                     emit(out, "var @3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
   743                          smapper.popD(), smapper.popD(), smapper.pushI());
   744                     break;
   745                 case opc_if_acmpeq:
   746                     i = generateIf(byteCodes, i, smapper.popA(), smapper.popA(),
   747                                    "===");
   748                     break;
   749                 case opc_if_acmpne:
   750                     i = generateIf(byteCodes, i, smapper.popA(), smapper.popA(),
   751                                    "!=");
   752                     break;
   753                 case opc_if_icmpeq:
   754                     i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
   755                                    "==");
   756                     break;
   757                 case opc_ifeq: {
   758                     int indx = i + readIntArg(byteCodes, i);
   759                     emit(out, "if (@1 == 0) { gt = @2; continue; }",
   760                          smapper.popI(), Integer.toString(indx));
   761                     i += 2;
   762                     break;
   763                 }
   764                 case opc_ifne: {
   765                     int indx = i + readIntArg(byteCodes, i);
   766                     emit(out, "if (@1 != 0) { gt = @2; continue; }",
   767                          smapper.popI(), Integer.toString(indx));
   768                     i += 2;
   769                     break;
   770                 }
   771                 case opc_iflt: {
   772                     int indx = i + readIntArg(byteCodes, i);
   773                     emit(out, "if (@1 < 0) { gt = @2; continue; }",
   774                          smapper.popI(), Integer.toString(indx));
   775                     i += 2;
   776                     break;
   777                 }
   778                 case opc_ifle: {
   779                     int indx = i + readIntArg(byteCodes, i);
   780                     emit(out, "if (@1 <= 0) { gt = @2; continue; }",
   781                          smapper.popI(), Integer.toString(indx));
   782                     i += 2;
   783                     break;
   784                 }
   785                 case opc_ifgt: {
   786                     int indx = i + readIntArg(byteCodes, i);
   787                     emit(out, "if (@1 > 0) { gt = @2; continue; }",
   788                          smapper.popI(), Integer.toString(indx));
   789                     i += 2;
   790                     break;
   791                 }
   792                 case opc_ifge: {
   793                     int indx = i + readIntArg(byteCodes, i);
   794                     emit(out, "if (@1 >= 0) { gt = @2; continue; }",
   795                          smapper.popI(), Integer.toString(indx));
   796                     i += 2;
   797                     break;
   798                 }
   799                 case opc_ifnonnull: {
   800                     int indx = i + readIntArg(byteCodes, i);
   801                     emit(out, "if (@1 !== null) { gt = @2; continue; }",
   802                          smapper.popA(), Integer.toString(indx));
   803                     i += 2;
   804                     break;
   805                 }
   806                 case opc_ifnull: {
   807                     int indx = i + readIntArg(byteCodes, i);
   808                     emit(out, "if (@1 === null) { gt = @2; continue; }",
   809                          smapper.popA(), Integer.toString(indx));
   810                     i += 2;
   811                     break;
   812                 }
   813                 case opc_if_icmpne:
   814                     i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
   815                                    "!=");
   816                     break;
   817                 case opc_if_icmplt:
   818                     i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
   819                                    "<");
   820                     break;
   821                 case opc_if_icmple:
   822                     i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
   823                                    "<=");
   824                     break;
   825                 case opc_if_icmpgt:
   826                     i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
   827                                    ">");
   828                     break;
   829                 case opc_if_icmpge:
   830                     i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
   831                                    ">=");
   832                     break;
   833                 case opc_goto: {
   834                     int indx = i + readIntArg(byteCodes, i);
   835                     emit(out, "gt = @1; continue;", Integer.toString(indx));
   836                     i += 2;
   837                     break;
   838                 }
   839                 case opc_lookupswitch: {
   840                     int table = i / 4 * 4 + 4;
   841                     int dflt = i + readInt4(byteCodes, table);
   842                     table += 4;
   843                     int n = readInt4(byteCodes, table);
   844                     table += 4;
   845                     out.append("switch (").append(smapper.popI()).append(") {\n");
   846                     while (n-- > 0) {
   847                         int cnstnt = readInt4(byteCodes, table);
   848                         table += 4;
   849                         int offset = i + readInt4(byteCodes, table);
   850                         table += 4;
   851                         out.append("  case " + cnstnt).append(": gt = " + offset).append("; continue;\n");
   852                     }
   853                     out.append("  default: gt = " + dflt).append("; continue;\n}");
   854                     i = table - 1;
   855                     break;
   856                 }
   857                 case opc_tableswitch: {
   858                     int table = i / 4 * 4 + 4;
   859                     int dflt = i + readInt4(byteCodes, table);
   860                     table += 4;
   861                     int low = readInt4(byteCodes, table);
   862                     table += 4;
   863                     int high = readInt4(byteCodes, table);
   864                     table += 4;
   865                     out.append("switch (").append(smapper.popI()).append(") {\n");
   866                     while (low <= high) {
   867                         int offset = i + readInt4(byteCodes, table);
   868                         table += 4;
   869                         out.append("  case " + low).append(": gt = " + offset).append("; continue;\n");
   870                         low++;
   871                     }
   872                     out.append("  default: gt = " + dflt).append("; continue;\n}");
   873                     i = table - 1;
   874                     break;
   875                 }
   876                 case opc_invokeinterface: {
   877                     i = invokeVirtualMethod(byteCodes, i, smapper) + 2;
   878                     break;
   879                 }
   880                 case opc_invokevirtual:
   881                     i = invokeVirtualMethod(byteCodes, i, smapper);
   882                     break;
   883                 case opc_invokespecial:
   884                     i = invokeStaticMethod(byteCodes, i, smapper, false);
   885                     break;
   886                 case opc_invokestatic:
   887                     i = invokeStaticMethod(byteCodes, i, smapper, true);
   888                     break;
   889                 case opc_new: {
   890                     int indx = readIntArg(byteCodes, i);
   891                     String ci = jc.getClassName(indx);
   892                     emit(out, "var @1 = new @2;",
   893                          smapper.pushA(), accessClass(ci.replace('/', '_')));
   894                     addReference(ci);
   895                     i += 2;
   896                     break;
   897                 }
   898                 case opc_newarray:
   899                     int atype = readByte(byteCodes, ++i);
   900                     String jvmType;
   901                     switch (atype) {
   902                         case 4: jvmType = "[Z"; break;
   903                         case 5: jvmType = "[C"; break;
   904                         case 6: jvmType = "[F"; break;
   905                         case 7: jvmType = "[D"; break;
   906                         case 8: jvmType = "[B"; break;
   907                         case 9: jvmType = "[S"; break;
   908                         case 10: jvmType = "[I"; break;
   909                         case 11: jvmType = "[J"; break;
   910                         default: throw new IllegalStateException("Array type: " + atype);
   911                     }
   912                     emit(out, "var @2 = Array.prototype.newArray__Ljava_lang_Object_2ZLjava_lang_String_2I(true, '@3', @1);",
   913                          smapper.popI(), smapper.pushA(), jvmType);
   914                     break;
   915                 case opc_anewarray: {
   916                     int type = readIntArg(byteCodes, i);
   917                     i += 2;
   918                     String typeName = jc.getClassName(type);
   919                     if (typeName.startsWith("[")) {
   920                         typeName = "[" + typeName;
   921                     } else {
   922                         typeName = "[L" + typeName + ";";
   923                     }
   924                     emit(out, "var @2 = Array.prototype.newArray__Ljava_lang_Object_2ZLjava_lang_String_2I(false, '@3', @1);",
   925                          smapper.popI(), smapper.pushA(), typeName);
   926                     break;
   927                 }
   928                 case opc_multianewarray: {
   929                     int type = readIntArg(byteCodes, i);
   930                     i += 2;
   931                     String typeName = jc.getClassName(type);
   932                     int dim = readByte(byteCodes, ++i);
   933                     StringBuilder dims = new StringBuilder();
   934                     dims.append('[');
   935                     for (int d = 0; d < dim; d++) {
   936                         if (d != 0) {
   937                             dims.append(",");
   938                         }
   939                         dims.append(smapper.popI());
   940                     }
   941                     dims.append(']');
   942                     emit(out, "var @2 = Array.prototype.multiNewArray__Ljava_lang_Object_2Ljava_lang_String_2_3II('@3', @1, 0);",
   943                          dims.toString(), smapper.pushA(), typeName);
   944                     break;
   945                 }
   946                 case opc_arraylength:
   947                     emit(out, "var @2 = @1.length;",
   948                          smapper.popA(), smapper.pushI());
   949                     break;
   950                 case opc_lastore:
   951                     emit(out, "@3.at(@2, @1);",
   952                          smapper.popL(), smapper.popI(), smapper.popA());
   953                     break;
   954                 case opc_fastore:
   955                     emit(out, "@3.at(@2, @1);",
   956                          smapper.popF(), smapper.popI(), smapper.popA());
   957                     break;
   958                 case opc_dastore:
   959                     emit(out, "@3.at(@2, @1);",
   960                          smapper.popD(), smapper.popI(), smapper.popA());
   961                     break;
   962                 case opc_aastore:
   963                     emit(out, "@3.at(@2, @1);",
   964                          smapper.popA(), smapper.popI(), smapper.popA());
   965                     break;
   966                 case opc_iastore:
   967                 case opc_bastore:
   968                 case opc_castore:
   969                 case opc_sastore:
   970                     emit(out, "@3.at(@2, @1);",
   971                          smapper.popI(), smapper.popI(), smapper.popA());
   972                     break;
   973                 case opc_laload:
   974                     emit(out, "var @3 = @2.at(@1);",
   975                          smapper.popI(), smapper.popA(), smapper.pushL());
   976                     break;
   977                 case opc_faload:
   978                     emit(out, "var @3 = @2.at(@1);",
   979                          smapper.popI(), smapper.popA(), smapper.pushF());
   980                     break;
   981                 case opc_daload:
   982                     emit(out, "var @3 = @2.at(@1);",
   983                          smapper.popI(), smapper.popA(), smapper.pushD());
   984                     break;
   985                 case opc_aaload:
   986                     emit(out, "var @3 = @2.at(@1);",
   987                          smapper.popI(), smapper.popA(), smapper.pushA());
   988                     break;
   989                 case opc_iaload:
   990                 case opc_baload:
   991                 case opc_caload:
   992                 case opc_saload:
   993                     emit(out, "var @3 = @2.at(@1);",
   994                          smapper.popI(), smapper.popA(), smapper.pushI());
   995                     break;
   996                 case opc_pop:
   997                 case opc_pop2:
   998                     smapper.pop(1);
   999                     debug("/* pop */");
  1000                     break;
  1001                 case opc_dup: {
  1002                     final Variable v = smapper.get(0);
  1003                     emit(out, "var @1 = @2;", smapper.pushT(v.getType()), v);
  1004                     break;
  1005                 }
  1006                 case opc_dup2: {
  1007                     if (smapper.get(0).isCategory2()) {
  1008                         final Variable v = smapper.get(0);
  1009                         emit(out, "var @1 = @2;",
  1010                              smapper.pushT(v.getType()), v);
  1011                     } else {
  1012                         final Variable v1 = smapper.get(0);
  1013                         final Variable v2 = smapper.get(1);
  1014                         emit(out, "var @1 = @2, @3 = @4;",
  1015                              smapper.pushT(v2.getType()), v2,
  1016                              smapper.pushT(v1.getType()), v1);
  1017                     }
  1018                     break;
  1019                 }
  1020                 case opc_dup_x1: {
  1021                     final Variable vi1 = smapper.pop();
  1022                     final Variable vi2 = smapper.pop();
  1023                     final Variable vo3 = smapper.pushT(vi1.getType());
  1024                     final Variable vo2 = smapper.pushT(vi2.getType());
  1025                     final Variable vo1 = smapper.pushT(vi1.getType());
  1026 
  1027                     emit(out, "var @1 = @2, @3 = @4, @5 = @6;",
  1028                          vo1, vi1, vo2, vi2, vo3, vo1);
  1029                     break;
  1030                 }
  1031                 case opc_dup_x2: {
  1032                     if (smapper.get(1).isCategory2()) {
  1033                         final Variable vi1 = smapper.pop();
  1034                         final Variable vi2 = smapper.pop();
  1035                         final Variable vo3 = smapper.pushT(vi1.getType());
  1036                         final Variable vo2 = smapper.pushT(vi2.getType());
  1037                         final Variable vo1 = smapper.pushT(vi1.getType());
  1038 
  1039                         emit(out, "var @1 = @2, @3 = @4, @5 = @6;",
  1040                              vo1, vi1, vo2, vi2, vo3, vo1);
  1041                     } else {
  1042                         final Variable vi1 = smapper.pop();
  1043                         final Variable vi2 = smapper.pop();
  1044                         final Variable vi3 = smapper.pop();
  1045                         final Variable vo4 = smapper.pushT(vi1.getType());
  1046                         final Variable vo3 = smapper.pushT(vi3.getType());
  1047                         final Variable vo2 = smapper.pushT(vi2.getType());
  1048                         final Variable vo1 = smapper.pushT(vi1.getType());
  1049 
  1050                         emit(out, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
  1051                              vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
  1052                     }
  1053                     break;
  1054                 }
  1055                 case opc_bipush:
  1056                     emit(out, "var @1 = @2;",
  1057                          smapper.pushI(), Integer.toString(byteCodes[++i]));
  1058                     break;
  1059                 case opc_sipush:
  1060                     emit(out, "var @1 = @2;",
  1061                          smapper.pushI(),
  1062                          Integer.toString(readIntArg(byteCodes, i)));
  1063                     i += 2;
  1064                     break;
  1065                 case opc_getfield: {
  1066                     int indx = readIntArg(byteCodes, i);
  1067                     String[] fi = jc.getFieldInfoName(indx);
  1068                     final int type = VarType.fromFieldType(fi[2].charAt(0));
  1069                     emit(out, "var @2 = @1.fld_@3;",
  1070                          smapper.popA(), smapper.pushT(type), fi[1]);
  1071                     i += 2;
  1072                     break;
  1073                 }
  1074                 case opc_getstatic: {
  1075                     int indx = readIntArg(byteCodes, i);
  1076                     String[] fi = jc.getFieldInfoName(indx);
  1077                     final int type = VarType.fromFieldType(fi[2].charAt(0));
  1078                     emit(out, "var @1 = @2(false).constructor.@3;",
  1079                          smapper.pushT(type),
  1080                          accessClass(fi[0].replace('/', '_')), fi[1]);
  1081                     i += 2;
  1082                     addReference(fi[0]);
  1083                     break;
  1084                 }
  1085                 case opc_putfield: {
  1086                     int indx = readIntArg(byteCodes, i);
  1087                     String[] fi = jc.getFieldInfoName(indx);
  1088                     final int type = VarType.fromFieldType(fi[2].charAt(0));
  1089                     emit(out, "@2.fld_@3 = @1;",
  1090                          smapper.popT(type), smapper.popA(), fi[1]);
  1091                     i += 2;
  1092                     break;
  1093                 }
  1094                 case opc_putstatic: {
  1095                     int indx = readIntArg(byteCodes, i);
  1096                     String[] fi = jc.getFieldInfoName(indx);
  1097                     final int type = VarType.fromFieldType(fi[2].charAt(0));
  1098                     emit(out, "@1(false).constructor.@2 = @3;",
  1099                          accessClass(fi[0].replace('/', '_')), fi[1],
  1100                          smapper.popT(type));
  1101                     i += 2;
  1102                     addReference(fi[0]);
  1103                     break;
  1104                 }
  1105                 case opc_checkcast: {
  1106                     int indx = readIntArg(byteCodes, i);
  1107                     final String type = jc.getClassName(indx);
  1108                     if (!type.startsWith("[")) {
  1109                         // no way to check arrays right now
  1110                         // XXX proper exception
  1111                         emit(out,
  1112                              "if (@1 !== null && !@1.$instOf_@2) throw {};",
  1113                              smapper.getA(0), type.replace('/', '_'));
  1114                     }
  1115                     i += 2;
  1116                     break;
  1117                 }
  1118                 case opc_instanceof: {
  1119                     int indx = readIntArg(byteCodes, i);
  1120                     final String type = jc.getClassName(indx);
  1121                     emit(out, "var @2 = @1.$instOf_@3 ? 1 : 0;",
  1122                          smapper.popA(), smapper.pushI(),
  1123                          type.replace('/', '_'));
  1124                     i += 2;
  1125                     break;
  1126                 }
  1127                 case opc_athrow: {
  1128                     final Variable v = smapper.popA();
  1129                     smapper.clear();
  1130 
  1131                     emit(out, "{ var @1 = @2; throw @2; }",
  1132                          smapper.pushA(), v);
  1133                     break;
  1134                 }
  1135 
  1136                 case opc_monitorenter: {
  1137                     out.append("/* monitor enter */");
  1138                     smapper.popA();
  1139                     break;
  1140                 }
  1141 
  1142                 case opc_monitorexit: {
  1143                     out.append("/* monitor exit */");
  1144                     smapper.popA();
  1145                     break;
  1146                 }
  1147 
  1148                 default: {
  1149                     emit(out, "throw 'unknown bytecode @1';",
  1150                          Integer.toString(c));
  1151                 }
  1152             }
  1153             if (debug(" //")) {
  1154                 for (int j = prev; j <= i; j++) {
  1155                     out.append(" ");
  1156                     final int cc = readByte(byteCodes, j);
  1157                     out.append(Integer.toString(cc));
  1158                 }
  1159             }
  1160             out.append("\n");            
  1161         }
  1162         if (previousTrap != null) {
  1163             generateCatch(previousTrap);
  1164         }
  1165         out.append("  }\n");
  1166         out.append("};");
  1167     }
  1168 
  1169     private int generateIf(byte[] byteCodes, int i,
  1170                            final Variable v2, final Variable v1,
  1171                            final String test) throws IOException {
  1172         int indx = i + readIntArg(byteCodes, i);
  1173         out.append("if (").append(v1)
  1174            .append(' ').append(test).append(' ')
  1175            .append(v2).append(") { gt = " + indx)
  1176            .append("; continue; }");
  1177         return i + 2;
  1178     }
  1179 
  1180     private int readIntArg(byte[] byteCodes, int offsetInstruction) {
  1181         final int indxHi = byteCodes[offsetInstruction + 1] << 8;
  1182         final int indxLo = byteCodes[offsetInstruction + 2];
  1183         return (indxHi & 0xffffff00) | (indxLo & 0xff);
  1184     }
  1185     private int readInt4(byte[] byteCodes, int offsetInstruction) {
  1186         final int d = byteCodes[offsetInstruction + 0] << 24;
  1187         final int c = byteCodes[offsetInstruction + 1] << 16;
  1188         final int b = byteCodes[offsetInstruction + 2] << 8;
  1189         final int a = byteCodes[offsetInstruction + 3];
  1190         return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
  1191     }
  1192     private int readByte(byte[] byteCodes, int offsetInstruction) {
  1193         return byteCodes[offsetInstruction] & 0xff;
  1194     }
  1195     
  1196     private static void countArgs(String descriptor, char[] returnType, StringBuilder sig, StringBuilder cnt) {
  1197         int i = 0;
  1198         Boolean count = null;
  1199         boolean array = false;
  1200         sig.append("__");
  1201         int firstPos = sig.length();
  1202         while (i < descriptor.length()) {
  1203             char ch = descriptor.charAt(i++);
  1204             switch (ch) {
  1205                 case '(':
  1206                     count = true;
  1207                     continue;
  1208                 case ')':
  1209                     count = false;
  1210                     continue;
  1211                 case 'B': 
  1212                 case 'C': 
  1213                 case 'D': 
  1214                 case 'F': 
  1215                 case 'I': 
  1216                 case 'J': 
  1217                 case 'S': 
  1218                 case 'Z': 
  1219                     if (count) {
  1220                         if (array) {
  1221                             sig.append("_3");
  1222                         }
  1223                         sig.append(ch);
  1224                         if (ch == 'J' || ch == 'D') {
  1225                             cnt.append('1');
  1226                         } else {
  1227                             cnt.append('0');
  1228                         }
  1229                     } else {
  1230                         sig.insert(firstPos, ch);
  1231                         if (array) {
  1232                             returnType[0] = '[';
  1233                             sig.insert(firstPos, "_3");
  1234                         } else {
  1235                             returnType[0] = ch;
  1236                         }
  1237                     }
  1238                     array = false;
  1239                     continue;
  1240                 case 'V': 
  1241                     assert !count;
  1242                     returnType[0] = 'V';
  1243                     sig.insert(firstPos, 'V');
  1244                     continue;
  1245                 case 'L':
  1246                     int next = descriptor.indexOf(';', i);
  1247                     String realSig = mangleSig(descriptor, i - 1, next + 1);
  1248                     if (count) {
  1249                         if (array) {
  1250                             sig.append("_3");
  1251                         }
  1252                         sig.append(realSig);
  1253                         cnt.append('0');
  1254                     } else {
  1255                         sig.insert(firstPos, realSig);
  1256                         if (array) {
  1257                             sig.insert(firstPos, "_3");
  1258                         }
  1259                         returnType[0] = 'L';
  1260                     }
  1261                     i = next + 1;
  1262                     array = false;
  1263                     continue;
  1264                 case '[':
  1265                     array = true;
  1266                     continue;
  1267                 default:
  1268                     throw new IllegalStateException("Invalid char: " + ch);
  1269             }
  1270         }
  1271     }
  1272     
  1273     private static String mangleSig(String txt, int first, int last) {
  1274         StringBuilder sb = new StringBuilder();
  1275         for (int i = first; i < last; i++) {
  1276             final char ch = txt.charAt(i);
  1277             switch (ch) {
  1278                 case '/': sb.append('_'); break;
  1279                 case '_': sb.append("_1"); break;
  1280                 case ';': sb.append("_2"); break;
  1281                 case '[': sb.append("_3"); break;
  1282                 default: sb.append(ch); break;
  1283             }
  1284         }
  1285         return sb.toString();
  1286     }
  1287 
  1288     private static String findMethodName(MethodData m, StringBuilder cnt) {
  1289         StringBuilder name = new StringBuilder();
  1290         if ("<init>".equals(m.getName())) { // NOI18N
  1291             name.append("cons"); // NOI18N
  1292         } else if ("<clinit>".equals(m.getName())) { // NOI18N
  1293             name.append("class"); // NOI18N
  1294         } else {
  1295             name.append(m.getName());
  1296         } 
  1297         
  1298         countArgs(m.getInternalSig(), new char[1], name, cnt);
  1299         return name.toString();
  1300     }
  1301 
  1302     static String findMethodName(String[] mi, StringBuilder cnt, char[] returnType) {
  1303         StringBuilder name = new StringBuilder();
  1304         String descr = mi[2];//mi.getDescriptor();
  1305         String nm= mi[1];
  1306         if ("<init>".equals(nm)) { // NOI18N
  1307             name.append("cons"); // NOI18N
  1308         } else {
  1309             name.append(nm);
  1310         }
  1311         countArgs(descr, returnType, name, cnt);
  1312         return name.toString();
  1313     }
  1314 
  1315     private int invokeStaticMethod(byte[] byteCodes, int i, final StackMapper mapper, boolean isStatic)
  1316     throws IOException {
  1317         int methodIndex = readIntArg(byteCodes, i);
  1318         String[] mi = jc.getFieldInfoName(methodIndex);
  1319         char[] returnType = { 'V' };
  1320         StringBuilder cnt = new StringBuilder();
  1321         String mn = findMethodName(mi, cnt, returnType);
  1322 
  1323         final int numArguments = isStatic ? cnt.length() : cnt.length() + 1;
  1324         final Variable[] vars = new Variable[numArguments];
  1325 
  1326         for (int j = numArguments - 1; j >= 0; --j) {
  1327             vars[j] = mapper.pop();
  1328         }
  1329 
  1330         if (returnType[0] != 'V') {
  1331             out.append("var ")
  1332                .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
  1333                .append(" = ");
  1334         }
  1335 
  1336         final String in = mi[0];
  1337         out.append(accessClass(in.replace('/', '_')));
  1338         out.append("(false).");
  1339         if (mn.startsWith("cons_")) {
  1340             out.append("constructor.");
  1341         }
  1342         out.append(mn);
  1343         if (isStatic) {
  1344             out.append('(');
  1345         } else {
  1346             out.append(".call(");
  1347         }
  1348         if (numArguments > 0) {
  1349             out.append(vars[0]);
  1350             for (int j = 1; j < numArguments; ++j) {
  1351                 out.append(", ");
  1352                 out.append(vars[j]);
  1353             }
  1354         }
  1355         out.append(");");
  1356         i += 2;
  1357         addReference(in);
  1358         return i;
  1359     }
  1360     private int invokeVirtualMethod(byte[] byteCodes, int i, final StackMapper mapper)
  1361     throws IOException {
  1362         int methodIndex = readIntArg(byteCodes, i);
  1363         String[] mi = jc.getFieldInfoName(methodIndex);
  1364         char[] returnType = { 'V' };
  1365         StringBuilder cnt = new StringBuilder();
  1366         String mn = findMethodName(mi, cnt, returnType);
  1367 
  1368         final int numArguments = cnt.length() + 1;
  1369         final Variable[] vars = new Variable[numArguments];
  1370 
  1371         for (int j = numArguments - 1; j >= 0; --j) {
  1372             vars[j] = mapper.pop();
  1373         }
  1374 
  1375         if (returnType[0] != 'V') {
  1376             out.append("var ")
  1377                .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
  1378                .append(" = ");
  1379         }
  1380 
  1381         out.append(vars[0]).append('.');
  1382         out.append(mn);
  1383         out.append('(');
  1384         String sep = "";
  1385         for (int j = 1; j < numArguments; ++j) {
  1386             out.append(sep);
  1387             out.append(vars[j]);
  1388             sep = ", ";
  1389         }
  1390         out.append(");");
  1391         i += 2;
  1392         return i;
  1393     }
  1394 
  1395     private void addReference(String cn) throws IOException {
  1396         if (requireReference(cn)) {
  1397             debug(" /* needs " + cn + " */");
  1398         }
  1399     }
  1400 
  1401     private void outType(String d, StringBuilder out) {
  1402         int arr = 0;
  1403         while (d.charAt(0) == '[') {
  1404             out.append('A');
  1405             d = d.substring(1);
  1406         }
  1407         if (d.charAt(0) == 'L') {
  1408             assert d.charAt(d.length() - 1) == ';';
  1409             out.append(d.replace('/', '_').substring(0, d.length() - 1));
  1410         } else {
  1411             out.append(d);
  1412         }
  1413     }
  1414 
  1415     private String encodeConstant(int entryIndex) throws IOException {
  1416         String[] classRef = { null };
  1417         String s = jc.stringValue(entryIndex, classRef);
  1418         if (classRef[0] != null) {
  1419             addReference(classRef[0]);
  1420             s = accessClass(s.replace('/', '_')) + "(false).constructor.$class";
  1421         }
  1422         return s;
  1423     }
  1424 
  1425     private String javaScriptBody(String prefix, MethodData m, boolean isStatic) throws IOException {
  1426         byte[] arr = m.findAnnotationData(true);
  1427         if (arr == null) {
  1428             return null;
  1429         }
  1430         final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
  1431         class P extends AnnotationParser {
  1432             public P() {
  1433                 super(false);
  1434             }
  1435             
  1436             int cnt;
  1437             String[] args = new String[30];
  1438             String body;
  1439             
  1440             @Override
  1441             protected void visitAttr(String type, String attr, String at, String value) {
  1442                 if (type.equals(jvmType)) {
  1443                     if ("body".equals(attr)) {
  1444                         body = value;
  1445                     } else if ("args".equals(attr)) {
  1446                         args[cnt++] = value;
  1447                     } else {
  1448                         throw new IllegalArgumentException(attr);
  1449                     }
  1450                 }
  1451             }
  1452         }
  1453         P p = new P();
  1454         p.parse(arr, jc);
  1455         if (p.body == null) {
  1456             return null;
  1457         }
  1458         StringBuilder cnt = new StringBuilder();
  1459         final String mn = findMethodName(m, cnt);
  1460         out.append(prefix).append(mn);
  1461         out.append(" = function(");
  1462         String space = "";
  1463         int index = 0;
  1464         for (int i = 0; i < cnt.length(); i++) {
  1465             out.append(space);
  1466             space = outputArg(out, p.args, index);
  1467             index++;
  1468         }
  1469         out.append(") {").append("\n");
  1470         out.append(p.body);
  1471         out.append("\n}\n");
  1472         return mn;
  1473     }
  1474     private static String className(ClassData jc) {
  1475         //return jc.getName().getInternalName().replace('/', '_');
  1476         return jc.getClassName().replace('/', '_');
  1477     }
  1478     
  1479     private static String[] findAnnotation(
  1480         byte[] arr, ClassData cd, final String className, 
  1481         final String... attrNames
  1482     ) throws IOException {
  1483         if (arr == null) {
  1484             return null;
  1485         }
  1486         final String[] values = new String[attrNames.length];
  1487         final boolean[] found = { false };
  1488         final String jvmType = "L" + className.replace('.', '/') + ";";
  1489         AnnotationParser ap = new AnnotationParser(false) {
  1490             @Override
  1491             protected void visitAttr(String type, String attr, String at, String value) {
  1492                 if (type.equals(jvmType)) {
  1493                     found[0] = true;
  1494                     for (int i = 0; i < attrNames.length; i++) {
  1495                         if (attrNames[i].equals(attr)) {
  1496                             values[i] = value;
  1497                         }
  1498                     }
  1499                 }
  1500             }
  1501             
  1502         };
  1503         ap.parse(arr, cd);
  1504         return found[0] ? values : null;
  1505     }
  1506 
  1507     private CharSequence initField(FieldData v) {
  1508         final String is = v.getInternalSig();
  1509         if (is.length() == 1) {
  1510             switch (is.charAt(0)) {
  1511                 case 'S':
  1512                 case 'J':
  1513                 case 'B':
  1514                 case 'Z':
  1515                 case 'C':
  1516                 case 'I': return " = 0;";
  1517                 case 'F': 
  1518                 case 'D': return " = 0.0;";
  1519                 default:
  1520                     throw new IllegalStateException(is);
  1521             }
  1522         }
  1523         return " = null;";
  1524     }
  1525 
  1526     private static void generateAnno(ClassData cd, final Appendable out, byte[] data) throws IOException {
  1527         AnnotationParser ap = new AnnotationParser(true) {
  1528             int anno;
  1529             int cnt;
  1530             
  1531             @Override
  1532             protected void visitAnnotationStart(String type) throws IOException {
  1533                 if (anno++ > 0) {
  1534                     out.append(",");
  1535                 }
  1536                 out.append('"').append(type).append("\" : {\n");
  1537                 cnt = 0;
  1538             }
  1539 
  1540             @Override
  1541             protected void visitAnnotationEnd(String type) throws IOException {
  1542                 out.append("\n}\n");
  1543             }
  1544             
  1545             @Override
  1546             protected void visitAttr(String type, String attr, String attrType, String value) 
  1547             throws IOException {
  1548                 if (attr == null) {
  1549                     return;
  1550                 }
  1551                 if (cnt++ > 0) {
  1552                     out.append(",\n");
  1553                 }
  1554                 out.append(attr).append("__").append(attrType).append(" : ").append(value);
  1555             }
  1556         };
  1557         ap.parse(data, cd);
  1558     }
  1559 
  1560     private static String outputArg(Appendable out, String[] args, int indx) throws IOException {
  1561         final String name = args[indx];
  1562         if (name == null) {
  1563             return "";
  1564         }
  1565         if (name.contains(",")) {
  1566             throw new IOException("Wrong parameter with ',': " + name);
  1567         }
  1568         out.append(name);
  1569         return ",";
  1570     }
  1571 
  1572     private static void emit(final Appendable out,
  1573                              final String format,
  1574                              final CharSequence... params) throws IOException {
  1575         final int length = format.length();
  1576 
  1577         int processed = 0;
  1578         int paramOffset = format.indexOf('@');
  1579         while ((paramOffset != -1) && (paramOffset < (length - 1))) {
  1580             final char paramChar = format.charAt(paramOffset + 1);
  1581             if ((paramChar >= '1') && (paramChar <= '9')) {
  1582                 final int paramIndex = paramChar - '0' - 1;
  1583 
  1584                 out.append(format, processed, paramOffset);
  1585                 out.append(params[paramIndex]);
  1586 
  1587                 ++paramOffset;
  1588                 processed = paramOffset + 1;
  1589             }
  1590 
  1591             paramOffset = format.indexOf('@', paramOffset + 1);
  1592         }
  1593 
  1594         out.append(format, processed, length);
  1595     }
  1596 
  1597     private void generateCatch(TrapData[] traps) throws IOException {
  1598         out.append("} catch (e) {\n");
  1599         int finallyPC = -1;
  1600         for (TrapData e : traps) {
  1601             if (e == null) {
  1602                 break;
  1603             }
  1604             if (e.catch_cpx != 0) { //not finally
  1605                 final String classInternalName = jc.getClassName(e.catch_cpx);
  1606                 addReference(classInternalName);
  1607                 if ("java/lang/Throwable".equals(classInternalName)) {
  1608                     out.append("if (e.$instOf_java_lang_Throwable) {");
  1609                     out.append("  var stA0 = e;");
  1610                     out.append("} else {");
  1611                     out.append("  var stA0 = vm.java_lang_Throwable(true);");
  1612                     out.append("  vm.java_lang_Throwable.cons__VLjava_lang_String_2.call(stA0, e.toString());");
  1613                     out.append("}");
  1614                     out.append("gt=" + e.handler_pc + "; continue;");
  1615                 } else {
  1616                     out.append("if (e.$instOf_" + classInternalName.replace('/', '_') + ") {");
  1617                     out.append("gt=" + e.handler_pc + "; var stA0 = e; continue;");
  1618                     out.append("}\n");
  1619                 }
  1620             } else {
  1621                 finallyPC = e.handler_pc;
  1622             }
  1623         }
  1624         if (finallyPC == -1) {
  1625             out.append("throw e;");
  1626         } else {
  1627             out.append("gt=" + finallyPC + "; var stA0 = e; continue;");
  1628         }
  1629         out.append("\n}");
  1630     }
  1631 }