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