rt/vm/src/main/java/org/apidesign/vm4brwsr/ByteCodeToJavaScript.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Wed, 15 Apr 2015 12:29:45 +0200
changeset 1823 999cf0169156
parent 1811 ff2a253900ed
child 1840 9d011ab3c192
permissions -rw-r--r--
Make sure the array component we check is properly referenced from the generated file
     1 /**
     2  * Back 2 Browser Bytecode Translator
     3  * Copyright (C) 2012-2015 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
     4  *
     5  * This program is free software: you can redistribute it and/or modify
     6  * it under the terms of the GNU General Public License as published by
     7  * the Free Software Foundation, version 2 of the License.
     8  *
     9  * This program is distributed in the hope that it will be useful,
    10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    12  * GNU General Public License for more details.
    13  *
    14  * You should have received a copy of the GNU General Public License
    15  * along with this program. Look for COPYING file in the top folder.
    16  * If not, see http://opensource.org/licenses/GPL-2.0.
    17  */
    18 package org.apidesign.vm4brwsr;
    19 
    20 import java.io.IOException;
    21 import java.io.InputStream;
    22 import org.apidesign.bck2brwsr.core.JavaScriptBody;
    23 import static org.apidesign.vm4brwsr.ByteCodeParser.*;
    24 
    25 /** Translator of the code inside class files to JavaScript.
    26  *
    27  * @author Jaroslav Tulach <jtulach@netbeans.org>
    28  */
    29 abstract class ByteCodeToJavaScript implements Appendable {
    30     private ClassData jc;
    31     private final Appendable out;
    32     private final StringArray classRefs = new StringArray();
    33     private boolean outChanged;
    34     private boolean callbacks;
    35 
    36     protected ByteCodeToJavaScript(Appendable out) {
    37         this.out = out;
    38     }
    39     
    40     @Override
    41     public final Appendable append(CharSequence csq) throws IOException {
    42         out.append(csq);
    43         outChanged = true;
    44         return this;
    45     }
    46 
    47     @Override
    48     public final Appendable append(CharSequence csq, int start, int end) throws IOException {
    49         out.append(csq, start, end);
    50         outChanged = true;
    51         return this;
    52     }
    53 
    54     @Override
    55     public final Appendable append(char c) throws IOException {
    56         out.append(c);
    57         outChanged = true;
    58         return this;
    59     }
    60     
    61     /* Collects additional required resources.
    62      * 
    63      * @param internalClassName classes that were referenced and should be loaded in order the
    64      *   generated JavaScript code works properly. The names are in internal 
    65      *   JVM form so String is <code>java/lang/String</code>. 
    66      */
    67     protected abstract boolean requireReference(String internalClassName);
    68     
    69     /*
    70      * @param resourcePath name of resources to read
    71      */
    72     protected abstract void requireScript(String resourcePath) throws IOException;
    73     
    74     protected abstract void requireResource(String resourcePath) throws IOException;
    75     
    76     /** Allows subclasses to redefine what field a function representing a
    77      * class gets assigned. By default it returns the suggested name followed
    78      * by <code>" = "</code>;
    79      * 
    80      * @param className suggested name of the class
    81      */
    82     /* protected */ String assignClass(String className) {
    83         return className + " = ";
    84     }
    85     /* protected */ String accessClass(String classOperation) {
    86         return classOperation;
    87     }
    88     
    89     final String accessClassFalse(String classOperation) {
    90         if (jc.getClassName().replace('/', '_').equals(classOperation)) {
    91             return "c";
    92         }
    93         classRefs.addIfMissing(classOperation);
    94         return "(refs_" + classOperation + " || (refs_" + classOperation + " = " + accessClass(classOperation) + "(false)))";
    95     }
    96 
    97     protected String accessField(String object, String mangledName,
    98                                  String[] fieldInfoName) throws IOException {
    99         return object + "." + mangledName;
   100     }
   101 
   102     protected String accessStaticMethod(
   103                              String object,
   104                              String mangledName,
   105                              String[] fieldInfoName) throws IOException {
   106         return object + "." + mangledName;
   107     }
   108 
   109     protected String accessVirtualMethod(
   110             String object, 
   111             String mangledName, 
   112             String[] fieldInfoName, 
   113             int params
   114     ) throws IOException {
   115         return object + "." + mangledName + '(';
   116     }
   117 
   118     protected void declaredClass(ClassData classData, String mangledName)
   119             throws IOException {
   120     }
   121 
   122     protected void declaredField(FieldData fieldData,
   123                                  String destObject,
   124                                  String mangledName) throws IOException {
   125     }
   126 
   127     protected void declaredMethod(MethodData methodData,
   128                                   String destObject,
   129                                   String mangledName) throws IOException {
   130     }
   131 
   132     /** Prints out a debug message. 
   133      * 
   134      * @param msg the message
   135      * @return true if the message has been printed
   136      * @throws IOException 
   137      */
   138     boolean debug(String msg) throws IOException {
   139         append(msg);
   140         return true;
   141     }
   142 
   143     /**
   144      * Converts a given class file to a JavaScript version.
   145      *
   146      * @param classFile input stream with code of the .class file
   147      * @return the initialization code for this class, if any. Otherwise <code>null</code>
   148      * 
   149      * @throws IOException if something goes wrong during read or write or translating
   150      */
   151     
   152     public String compile(InputStream classFile) throws IOException {
   153         return compile(new ClassData(classFile));
   154     }
   155 
   156     protected String compile(ClassData classData) throws IOException {
   157         this.jc = classData;
   158         final String cn = this.jc.getClassName();
   159         try {
   160             return compileImpl(cn);
   161         } catch (IOException ex) {
   162             throw new IOException("Cannot compile " + cn + ":", ex);
   163         }
   164     }
   165 
   166     private String compileImpl(final String cn) throws IOException {
   167         this.callbacks = cn.endsWith("/$JsCallbacks$");
   168         if (jc.getMajor_version() < 50 && !cn.endsWith("/package-info")) {
   169             throw new IOException("Can't compile " + cn + ". Class file version " + jc.getMajor_version() + "."
   170                 + jc.getMinor_version() + " - recompile with -target 1.6 (at least)."
   171             );
   172         }
   173         byte[] arrData = jc.findAnnotationData(true);
   174         {
   175             String[] arr = findAnnotation(arrData, jc,
   176                 "org.apidesign.bck2brwsr.core.ExtraJavaScript", 
   177                 "resource", "processByteCode"
   178             );
   179             if (arr != null) {
   180                 if (!arr[0].isEmpty()) {
   181                     requireScript(arr[0]);
   182                 }
   183                 if ("0".equals(arr[1])) {
   184                     return null;
   185                 }
   186             }
   187         }
   188         final String jsResource;
   189         {
   190             String[] arr = findAnnotation(arrData, jc,
   191                 "net.java.html.js.JavaScriptResource", 
   192                 "value"
   193             );
   194             if (arr != null) {
   195                 if (arr[0].startsWith("/")) {
   196                     jsResource = arr[0];
   197                 } else {
   198                     int last = cn.lastIndexOf('/');
   199                     jsResource = cn.substring(0, last + 1).replace('.', '/') + arr[0];
   200                 }
   201             } else {
   202                 jsResource = null;
   203             }
   204         }
   205         String[] proto = findAnnotation(arrData, jc,
   206             "org.apidesign.bck2brwsr.core.JavaScriptPrototype", 
   207             "container", "prototype"
   208         );
   209         StringArray toInitilize = new StringArray();
   210         final String className = className(jc);
   211         append("\n\n").append(assignClass(className));
   212         append("function ").append(className).append("() {");
   213         append("\n  var m;");
   214         append("\n  var CLS = ").append(className).append(';');
   215         append("\n  if (!CLS.$class) {");
   216         if (proto == null) {
   217             String sc = jc.getSuperClassName(); // with _
   218             append("\n    var pp = ").
   219                 append(accessClass(mangleClassName(sc))).append("(true);");
   220             append("\n    var p = CLS.prototype = pp;");
   221             append("\n    var c = p;");
   222             append("\n    var sprcls = pp.constructor.$class;");
   223         } else {
   224             append("\n    var p = CLS.prototype = ").append(proto[1]).append(";");
   225             if (proto[0] == null) {
   226                 proto[0] = "p";
   227             }
   228             append("\n    var c = ").append(proto[0]).append(";");
   229             append("\n    var sprcls = null;");
   230         }
   231         for (FieldData v : jc.getFields()) {
   232             if (v.isStatic()) {
   233                 if ((v.access & ACC_FINAL) != 0 && v.hasConstantValue()) {
   234                     if (v.getInternalSig().length() == 1 || v.getInternalSig().equals("Ljava/lang/String;")) {
   235                         continue;
   236                     }
   237                 }
   238                 append("\n  CLS.fld_").append(v.getName()).append(initField(v));
   239                 append("\n  m = c._").append(v.getName()).append(" = function (v) {")
   240                     .append("  if (arguments.length == 1) CLS.fld_").append(v.getName())
   241                     .append(" = v; return CLS.fld_").
   242                     append(v.getName()).append("; };");
   243             } else {
   244                 append("\n  m = c._").append(v.getName()).append(" = function (v) {")
   245                     .append("  if (arguments.length == 1) this.fld_").
   246                     append(className).append('_').append(v.getName())
   247                     .append(" = v; return this.fld_").
   248                     append(className).append('_').append(v.getName())
   249                     .append("; };");
   250             }
   251 
   252             declaredField(v, "c", "_" + v.getName());
   253         }
   254         for (MethodData m : jc.getMethods()) {
   255             byte[] onlyArr = m.findAnnotationData(true);
   256             if (javaScriptOnly(onlyArr)) continue;
   257             String destObject;
   258             String mn;
   259             append("\n    ");
   260             if (m.isStatic()) {
   261                 destObject = "c";
   262                 mn = generateStaticMethod(destObject, m, toInitilize);
   263             } else {
   264                 if (m.isConstructor()) {
   265                     destObject = "CLS";
   266                     mn = generateInstanceMethod(destObject, m);
   267                 } else {
   268                     destObject = "c";
   269                     mn = generateInstanceMethod(destObject, m);
   270                 }
   271             }
   272             declaredMethod(m, destObject, mn);
   273             byte[] runAnno = m.findAnnotationData(false);
   274             if (runAnno != null) {
   275                 append("\n    m.anno = {");
   276                 generateAnno(jc, runAnno);
   277                 append("\n    };");
   278             }
   279             append("\n    m.access = " + m.getAccess()).append(";");
   280             append("\n    m.cls = CLS;");
   281         }
   282         append("\n    c.constructor = CLS;");
   283         append("\n    function ").append(className).append("fillInstOf(x) {");
   284         String instOfName = "$instOf_" + className;
   285         append("\n        Object.defineProperty(x, '").append(instOfName).append("', { value : true });");
   286         if (jc.isInterface()) {
   287             for (MethodData m : jc.getMethods()) {
   288                 if ((m.getAccess() & ACC_ABSTRACT) == 0
   289                     && (m.getAccess() & ACC_STATIC) == 0
   290                     && (m.getAccess() & ACC_PRIVATE) == 0) {
   291                     final String mn = findMethodName(m, new StringBuilder());
   292                     append("\n        if (!x['").append(mn).append("']) Object.defineProperty(x, '").append(mn).append("', { value : c['").append(mn).append("']});");
   293                 }
   294             }
   295         }
   296         for (String superInterface : jc.getSuperInterfaces()) {
   297             String intrfc = superInterface.replace('/', '_');
   298             append("\n      vm.").append(intrfc).append("(false)['fillInstOf'](x);");
   299             requireReference(superInterface);
   300         }
   301         append("\n    }");
   302         append("\n    if (!c.hasOwnProperty('fillInstOf')) Object.defineProperty(c, 'fillInstOf', { value: ").append(className).append("fillInstOf });");
   303         append("\n    ").append(className).append("fillInstOf(c);");
   304 //        obfuscationDelegate.exportJSProperty(this, "c", instOfName);
   305         append("\n    CLS.$class = 'temp';");
   306         append("\n    CLS.$class = ");
   307         append(accessClass("java_lang_Class(true);"));
   308         append("\n    CLS.$class.jvmName = '").append(cn).append("';");
   309         append("\n    CLS.$class.superclass = sprcls;");
   310         append("\n    CLS.$class.interfaces = function() { return [");
   311         {
   312             boolean first = true;
   313             for (String intrfc : jc.getSuperInterfaces()) {
   314                 if (!first) {
   315                     append(",");
   316                 }
   317                 requireReference(intrfc);
   318                 String mangledIface = mangleClassName(intrfc);
   319                 append("\n        ");
   320                 append(accessClass(mangledIface)).append("(false).constructor.$class");
   321                 first = false;
   322             }
   323         }
   324         append("\n    ]; };");
   325         append("\n    CLS.$class.access = ").append(jc.getAccessFlags()+";");
   326         append("\n    CLS.$class.cnstr = CLS;");
   327         byte[] classAnno = jc.findAnnotationData(false);
   328         if (classAnno != null) {
   329             append("\n    CLS.$class.anno = {");
   330             generateAnno(jc, classAnno);
   331             append("\n    };");
   332         }
   333         for (String init : toInitilize.toArray()) {
   334             append("\n    ").append(init).append("();");
   335         }
   336         for (String ref : classRefs.toArray()) {
   337             append("\n    var refs_").append(ref).append(";");
   338         }
   339         classRefs.clear();
   340         
   341         if (jsResource != null) {
   342             requireResource(jsResource);
   343         }
   344         
   345         append("\n  }");
   346         append("\n  if (arguments.length === 0) {");
   347         append("\n    if (!(this instanceof CLS)) {");
   348         append("\n      return new CLS();");
   349         append("\n    }");
   350         for (FieldData v : jc.getFields()) {
   351             byte[] onlyArr = v.findAnnotationData(true);
   352             if (javaScriptOnly(onlyArr)) continue;
   353             if (!v.isStatic()) {
   354                 append("\n    this.fld_").
   355                     append(className).append('_').
   356                     append(v.getName()).append(initField(v));
   357             }
   358         }
   359         append("\n    return this;");
   360         append("\n  }");
   361         append("\n  return arguments[0] ? new CLS() : CLS.prototype;");
   362         append("\n};");
   363 
   364         declaredClass(jc, className);
   365 
   366 //        StringBuilder sb = new StringBuilder();
   367 //        for (String init : toInitilize.toArray()) {
   368 //            sb.append("\n").append(init).append("();");
   369 //        }
   370         return "";
   371     }
   372 
   373     private boolean javaScriptOnly(byte[] anno) throws IOException {
   374         String[] only = findAnnotation(anno, jc,
   375             "org.apidesign.bck2brwsr.core.JavaScriptOnly",
   376             "name", "value"
   377         );
   378         if (only != null) {
   379             if (only[0] != null && only[1] != null) {
   380                 append("\n    p.").append(only[0]).append(" = ")
   381                     .append(only[1]).append(";");
   382             }
   383             if (ExportedSymbols.isMarkedAsExported(anno, jc)) {
   384                 append("\n    p['").append(only[0]).append("'] = p.")
   385                     .append(only[0]).append(";");
   386             }
   387             return true;
   388         }
   389         return false;
   390     }
   391     private String generateStaticMethod(String destObject, MethodData m, StringArray toInitilize) throws IOException {
   392         String jsb = javaScriptBody(destObject, m, true);
   393         if (jsb != null) {
   394             return jsb;
   395         }
   396         final String mn = findMethodName(m, new StringBuilder());
   397         boolean defineProp = generateMethod(destObject, mn, m);
   398         if (mn.equals("class__V")) {
   399             if (defineProp) {
   400                 toInitilize.add(accessClassFalse(className(jc)) + "['" + mn + "']");
   401             } else {
   402                 toInitilize.add(accessClassFalse(className(jc)) + "." + mn);
   403             }
   404         }
   405         return mn;
   406     }
   407 
   408     private String generateInstanceMethod(String destObject, MethodData m) throws IOException {
   409         String jsb = javaScriptBody(destObject, m, false);
   410         if (jsb != null) {
   411             return jsb;
   412         }
   413         final String mn = findMethodName(m, new StringBuilder());
   414         generateMethod(destObject, mn, m);
   415         return mn;
   416     }
   417 
   418     private boolean generateMethod(String destObject, String name, MethodData m)
   419             throws IOException {
   420         final StackMapIterator stackMapIterator = m.createStackMapIterator();
   421         TrapDataIterator trap = m.getTrapDataIterator();
   422         final LocalsMapper lmapper =
   423                 new LocalsMapper(stackMapIterator.getArguments());
   424 
   425         boolean defineProp = 
   426             "java/lang/Object".equals(jc.getClassName()) ||
   427             "java/lang/reflect/Array".equals(jc.getClassName());
   428         
   429         if (defineProp) {
   430             append("Object.defineProperty(").append(destObject).
   431             append(", '").append(name).append("', { configurable: true, writable: true, value: m = function(");
   432         } else {
   433             append("m = ").append(destObject).append(".").append(name).append(" = function(");
   434         }
   435         lmapper.outputArguments(this, m.isStatic());
   436         append(") {").append("\n");
   437 
   438         final byte[] byteCodes = m.getCode();
   439         if (byteCodes == null) {
   440             if (debug("  throw 'no code found for ")) {
   441                this
   442                .append(jc.getClassName()).append('.')
   443                .append(m.getName()).append("';\n");
   444             }
   445             if (defineProp) {
   446                 append("}});");
   447             } else {
   448                 append("};");
   449             }
   450             return defineProp;
   451         }
   452 
   453         final StackMapper smapper = new StackMapper();
   454 
   455         if (!m.isStatic()) {
   456             append("  var ").append(" lcA0 = this;\n");
   457         }
   458 
   459         int lastStackFrame;
   460         TrapData[] previousTrap = null;
   461         boolean wide = false;
   462         boolean didBranches;
   463         if (stackMapIterator.isEmpty()) {
   464             didBranches = false;
   465             lastStackFrame = 0;
   466         } else {
   467             didBranches = true;
   468             lastStackFrame = -1;
   469             append("\n  var gt = 0;\n");
   470         }
   471         
   472         int openBraces = 0;
   473         int topMostLabel = 0;
   474         for (int i = 0; i < byteCodes.length; i++) {
   475             int prev = i;
   476             outChanged = false;
   477             stackMapIterator.advanceTo(i);
   478             boolean changeInCatch = trap.advanceTo(i);
   479             if (changeInCatch || lastStackFrame != stackMapIterator.getFrameIndex()) {
   480                 if (previousTrap != null) {
   481                     generateCatch(previousTrap, i, topMostLabel);
   482                     previousTrap = null;
   483                 }
   484             }
   485             if (lastStackFrame != stackMapIterator.getFrameIndex()) {
   486                 smapper.flush(this);
   487                 if (i != 0) {
   488                     append("    }\n");
   489                 }
   490                 if (openBraces > 64) {
   491                     for (int c = 0; c < 64; c++) {
   492                         append("break;}\n");
   493                     }
   494                     openBraces = 1;
   495                     topMostLabel = i;
   496                 }
   497                 
   498                 lastStackFrame = stackMapIterator.getFrameIndex();
   499                 lmapper.syncWithFrameLocals(stackMapIterator.getFrameLocals());
   500                 smapper.syncWithFrameStack(stackMapIterator.getFrameStack());
   501                 append("    X_" + i).append(": for (;;) { IF: if (gt <= " + i + ") {\n");
   502                 openBraces++;
   503                 changeInCatch = true;
   504             } else {
   505                 debug("    /* " + i + " */ ");
   506             }
   507             if (changeInCatch && trap.useTry()) {
   508                 append("try {");
   509                 previousTrap = trap.current();
   510             }
   511             final int c = readUByte(byteCodes, i);
   512             switch (c) {
   513                 case opc_aload_0:
   514                     smapper.assign(this, VarType.REFERENCE, lmapper.getA(0));
   515                     break;
   516                 case opc_iload_0:
   517                     smapper.assign(this, VarType.INTEGER, lmapper.getI(0));
   518                     break;
   519                 case opc_lload_0:
   520                     smapper.assign(this, VarType.LONG, lmapper.getL(0));
   521                     break;
   522                 case opc_fload_0:
   523                     smapper.assign(this, VarType.FLOAT, lmapper.getF(0));
   524                     break;
   525                 case opc_dload_0:
   526                     smapper.assign(this, VarType.DOUBLE, lmapper.getD(0));
   527                     break;
   528                 case opc_aload_1:
   529                     smapper.assign(this, VarType.REFERENCE, lmapper.getA(1));
   530                     break;
   531                 case opc_iload_1:
   532                     smapper.assign(this, VarType.INTEGER, lmapper.getI(1));
   533                     break;
   534                 case opc_lload_1:
   535                     smapper.assign(this, VarType.LONG, lmapper.getL(1));
   536                     break;
   537                 case opc_fload_1:
   538                     smapper.assign(this, VarType.FLOAT, lmapper.getF(1));
   539                     break;
   540                 case opc_dload_1:
   541                     smapper.assign(this, VarType.DOUBLE, lmapper.getD(1));
   542                     break;
   543                 case opc_aload_2:
   544                     smapper.assign(this, VarType.REFERENCE, lmapper.getA(2));
   545                     break;
   546                 case opc_iload_2:
   547                     smapper.assign(this, VarType.INTEGER, lmapper.getI(2));
   548                     break;
   549                 case opc_lload_2:
   550                     smapper.assign(this, VarType.LONG, lmapper.getL(2));
   551                     break;
   552                 case opc_fload_2:
   553                     smapper.assign(this, VarType.FLOAT, lmapper.getF(2));
   554                     break;
   555                 case opc_dload_2:
   556                     smapper.assign(this, VarType.DOUBLE, lmapper.getD(2));
   557                     break;
   558                 case opc_aload_3:
   559                     smapper.assign(this, VarType.REFERENCE, lmapper.getA(3));
   560                     break;
   561                 case opc_iload_3:
   562                     smapper.assign(this, VarType.INTEGER, lmapper.getI(3));
   563                     break;
   564                 case opc_lload_3:
   565                     smapper.assign(this, VarType.LONG, lmapper.getL(3));
   566                     break;
   567                 case opc_fload_3:
   568                     smapper.assign(this, VarType.FLOAT, lmapper.getF(3));
   569                     break;
   570                 case opc_dload_3:
   571                     smapper.assign(this, VarType.DOUBLE, lmapper.getD(3));
   572                     break;
   573                 case opc_iload: {
   574                     ++i;
   575                     final int indx = wide ? readUShort(byteCodes, i++)
   576                                           : readUByte(byteCodes, i);
   577                     wide = false;
   578                     smapper.assign(this, VarType.INTEGER, lmapper.getI(indx));
   579                     break;
   580                 }
   581                 case opc_lload: {
   582                     ++i;
   583                     final int indx = wide ? readUShort(byteCodes, i++)
   584                                           : readUByte(byteCodes, i);
   585                     wide = false;
   586                     smapper.assign(this, VarType.LONG, lmapper.getL(indx));
   587                     break;
   588                 }
   589                 case opc_fload: {
   590                     ++i;
   591                     final int indx = wide ? readUShort(byteCodes, i++)
   592                                           : readUByte(byteCodes, i);
   593                     wide = false;
   594                     smapper.assign(this, VarType.FLOAT, lmapper.getF(indx));
   595                     break;
   596                 }
   597                 case opc_dload: {
   598                     ++i;
   599                     final int indx = wide ? readUShort(byteCodes, i++)
   600                                           : readUByte(byteCodes, i);
   601                     wide = false;
   602                     smapper.assign(this, VarType.DOUBLE, lmapper.getD(indx));
   603                     break;
   604                 }
   605                 case opc_aload: {
   606                     ++i;
   607                     final int indx = wide ? readUShort(byteCodes, i++)
   608                                           : readUByte(byteCodes, i);
   609                     wide = false;
   610                     smapper.assign(this, VarType.REFERENCE, lmapper.getA(indx));
   611                     break;
   612                 }
   613                 case opc_istore: {
   614                     ++i;
   615                     final int indx = wide ? readUShort(byteCodes, i++)
   616                                           : readUByte(byteCodes, i);
   617                     wide = false;
   618                     emit(smapper, this, "var @1 = @2;",
   619                          lmapper.setI(indx), smapper.popI());
   620                     break;
   621                 }
   622                 case opc_lstore: {
   623                     ++i;
   624                     final int indx = wide ? readUShort(byteCodes, i++)
   625                                           : readUByte(byteCodes, i);
   626                     wide = false;
   627                     emit(smapper, this, "var @1 = @2;",
   628                          lmapper.setL(indx), smapper.popL());
   629                     break;
   630                 }
   631                 case opc_fstore: {
   632                     ++i;
   633                     final int indx = wide ? readUShort(byteCodes, i++)
   634                                           : readUByte(byteCodes, i);
   635                     wide = false;
   636                     emit(smapper, this, "var @1 = @2;",
   637                          lmapper.setF(indx), smapper.popF());
   638                     break;
   639                 }
   640                 case opc_dstore: {
   641                     ++i;
   642                     final int indx = wide ? readUShort(byteCodes, i++)
   643                                           : readUByte(byteCodes, i);
   644                     wide = false;
   645                     emit(smapper, this, "var @1 = @2;",
   646                          lmapper.setD(indx), smapper.popD());
   647                     break;
   648                 }
   649                 case opc_astore: {
   650                     ++i;
   651                     final int indx = wide ? readUShort(byteCodes, i++)
   652                                           : readUByte(byteCodes, i);
   653                     wide = false;
   654                     emit(smapper, this, "var @1 = @2;",
   655                          lmapper.setA(indx), smapper.popA());
   656                     break;
   657                 }
   658                 case opc_astore_0:
   659                     emit(smapper, this, "var @1 = @2;", lmapper.setA(0), smapper.popA());
   660                     break;
   661                 case opc_istore_0:
   662                     emit(smapper, this, "var @1 = @2;", lmapper.setI(0), smapper.popI());
   663                     break;
   664                 case opc_lstore_0:
   665                     emit(smapper, this, "var @1 = @2;", lmapper.setL(0), smapper.popL());
   666                     break;
   667                 case opc_fstore_0:
   668                     emit(smapper, this, "var @1 = @2;", lmapper.setF(0), smapper.popF());
   669                     break;
   670                 case opc_dstore_0:
   671                     emit(smapper, this, "var @1 = @2;", lmapper.setD(0), smapper.popD());
   672                     break;
   673                 case opc_astore_1:
   674                     emit(smapper, this, "var @1 = @2;", lmapper.setA(1), smapper.popA());
   675                     break;
   676                 case opc_istore_1:
   677                     emit(smapper, this, "var @1 = @2;", lmapper.setI(1), smapper.popI());
   678                     break;
   679                 case opc_lstore_1:
   680                     emit(smapper, this, "var @1 = @2;", lmapper.setL(1), smapper.popL());
   681                     break;
   682                 case opc_fstore_1:
   683                     emit(smapper, this, "var @1 = @2;", lmapper.setF(1), smapper.popF());
   684                     break;
   685                 case opc_dstore_1:
   686                     emit(smapper, this, "var @1 = @2;", lmapper.setD(1), smapper.popD());
   687                     break;
   688                 case opc_astore_2:
   689                     emit(smapper, this, "var @1 = @2;", lmapper.setA(2), smapper.popA());
   690                     break;
   691                 case opc_istore_2:
   692                     emit(smapper, this, "var @1 = @2;", lmapper.setI(2), smapper.popI());
   693                     break;
   694                 case opc_lstore_2:
   695                     emit(smapper, this, "var @1 = @2;", lmapper.setL(2), smapper.popL());
   696                     break;
   697                 case opc_fstore_2:
   698                     emit(smapper, this, "var @1 = @2;", lmapper.setF(2), smapper.popF());
   699                     break;
   700                 case opc_dstore_2:
   701                     emit(smapper, this, "var @1 = @2;", lmapper.setD(2), smapper.popD());
   702                     break;
   703                 case opc_astore_3:
   704                     emit(smapper, this, "var @1 = @2;", lmapper.setA(3), smapper.popA());
   705                     break;
   706                 case opc_istore_3:
   707                     emit(smapper, this, "var @1 = @2;", lmapper.setI(3), smapper.popI());
   708                     break;
   709                 case opc_lstore_3:
   710                     emit(smapper, this, "var @1 = @2;", lmapper.setL(3), smapper.popL());
   711                     break;
   712                 case opc_fstore_3:
   713                     emit(smapper, this, "var @1 = @2;", lmapper.setF(3), smapper.popF());
   714                     break;
   715                 case opc_dstore_3:
   716                     emit(smapper, this, "var @1 = @2;", lmapper.setD(3), smapper.popD());
   717                     break;
   718                 case opc_iadd:
   719                     smapper.replace(this, VarType.INTEGER, "(@1).add32(@2)", smapper.getI(1), smapper.popI());
   720                     break;
   721                 case opc_ladd:
   722                     smapper.replace(this, VarType.LONG, "(@1).add64(@2)", smapper.getL(1), smapper.popL());
   723                     break;
   724                 case opc_fadd:
   725                     smapper.replace(this, VarType.FLOAT, "(@1 + @2)", smapper.getF(1), smapper.popF());
   726                     break;
   727                 case opc_dadd:
   728                     smapper.replace(this, VarType.DOUBLE, "(@1 + @2)", smapper.getD(1), smapper.popD());
   729                     break;
   730                 case opc_isub:
   731                     smapper.replace(this, VarType.INTEGER, "(@1).sub32(@2)", smapper.getI(1), smapper.popI());
   732                     break;
   733                 case opc_lsub:
   734                     smapper.replace(this, VarType.LONG, "(@1).sub64(@2)", smapper.getL(1), smapper.popL());
   735                     break;
   736                 case opc_fsub:
   737                     smapper.replace(this, VarType.FLOAT, "(@1 - @2)", smapper.getF(1), smapper.popF());
   738                     break;
   739                 case opc_dsub:
   740                     smapper.replace(this, VarType.DOUBLE, "(@1 - @2)", smapper.getD(1), smapper.popD());
   741                     break;
   742                 case opc_imul:
   743                     smapper.replace(this, VarType.INTEGER, "(@1).mul32(@2)", smapper.getI(1), smapper.popI());
   744                     break;
   745                 case opc_lmul:
   746                     smapper.replace(this, VarType.LONG, "(@1).mul64(@2)", smapper.getL(1), smapper.popL());
   747                     break;
   748                 case opc_fmul:
   749                     smapper.replace(this, VarType.FLOAT, "(@1 * @2)", smapper.getF(1), smapper.popF());
   750                     break;
   751                 case opc_dmul:
   752                     smapper.replace(this, VarType.DOUBLE, "(@1 * @2)", smapper.getD(1), smapper.popD());
   753                     break;
   754                 case opc_idiv:
   755                     smapper.replace(this, VarType.INTEGER, "(@1).div32(@2)",
   756                          smapper.getI(1), smapper.popI());
   757                     break;
   758                 case opc_ldiv:
   759                     smapper.replace(this, VarType.LONG, "(@1).div64(@2)",
   760                          smapper.getL(1), smapper.popL());
   761                     break;
   762                 case opc_fdiv:
   763                     smapper.replace(this, VarType.FLOAT, "(@1 / @2)", smapper.getF(1), smapper.popF());
   764                     break;
   765                 case opc_ddiv:
   766                     smapper.replace(this, VarType.DOUBLE, "(@1 / @2)", smapper.getD(1), smapper.popD());
   767                     break;
   768                 case opc_irem:
   769                     smapper.replace(this, VarType.INTEGER, "(@1).mod32(@2)",
   770                          smapper.getI(1), smapper.popI());
   771                     break;
   772                 case opc_lrem:
   773                     smapper.replace(this, VarType.LONG, "(@1).mod64(@2)",
   774                          smapper.getL(1), smapper.popL());
   775                     break;
   776                 case opc_frem:
   777                     smapper.replace(this, VarType.FLOAT, "(@1 % @2)", smapper.getF(1), smapper.popF());
   778                     break;
   779                 case opc_drem:
   780                     smapper.replace(this, VarType.DOUBLE, "(@1 % @2)", smapper.getD(1), smapper.popD());
   781                     break;
   782                 case opc_iand:
   783                     smapper.replace(this, VarType.INTEGER, "(@1 & @2)", smapper.getI(1), smapper.popI());
   784                     break;
   785                 case opc_land:
   786                     smapper.replace(this, VarType.LONG, "(@1).and64(@2)", smapper.getL(1), smapper.popL());
   787                     break;
   788                 case opc_ior:
   789                     smapper.replace(this, VarType.INTEGER, "(@1 | @2)", smapper.getI(1), smapper.popI());
   790                     break;
   791                 case opc_lor:
   792                     smapper.replace(this, VarType.LONG, "(@1).or64(@2)", smapper.getL(1), smapper.popL());
   793                     break;
   794                 case opc_ixor:
   795                     smapper.replace(this, VarType.INTEGER, "(@1 ^ @2)", smapper.getI(1), smapper.popI());
   796                     break;
   797                 case opc_lxor:
   798                     smapper.replace(this, VarType.LONG, "(@1).xor64(@2)", smapper.getL(1), smapper.popL());
   799                     break;
   800                 case opc_ineg:
   801                     smapper.replace(this, VarType.INTEGER, "(@1).neg32()", smapper.getI(0));
   802                     break;
   803                 case opc_lneg:
   804                     smapper.replace(this, VarType.LONG, "(@1).neg64()", smapper.getL(0));
   805                     break;
   806                 case opc_fneg:
   807                     smapper.replace(this, VarType.FLOAT, "(-@1)", smapper.getF(0));
   808                     break;
   809                 case opc_dneg:
   810                     smapper.replace(this, VarType.DOUBLE, "(-@1)", smapper.getD(0));
   811                     break;
   812                 case opc_ishl:
   813                     smapper.replace(this, VarType.INTEGER, "(@1 << @2)", smapper.getI(1), smapper.popI());
   814                     break;
   815                 case opc_lshl:
   816                     smapper.replace(this, VarType.LONG, "(@1).shl64(@2)", smapper.getL(1), smapper.popI());
   817                     break;
   818                 case opc_ishr:
   819                     smapper.replace(this, VarType.INTEGER, "(@1 >> @2)", smapper.getI(1), smapper.popI());
   820                     break;
   821                 case opc_lshr:
   822                     smapper.replace(this, VarType.LONG, "(@1).shr64(@2)", smapper.getL(1), smapper.popI());
   823                     break;
   824                 case opc_iushr:
   825                     smapper.replace(this, VarType.INTEGER, "(@1 >>> @2)", smapper.getI(1), smapper.popI());
   826                     break;
   827                 case opc_lushr:
   828                     smapper.replace(this, VarType.LONG, "(@1).ushr64(@2)", smapper.getL(1), smapper.popI());
   829                     break;
   830                 case opc_iinc: {
   831                     ++i;
   832                     final int varIndx = wide ? readUShort(byteCodes, i++)
   833                                              : readUByte(byteCodes, i);
   834                     ++i;
   835                     final int incrBy = wide ? readShort(byteCodes, i++)
   836                                             : byteCodes[i];
   837                     wide = false;
   838                     if (incrBy == 1) {
   839                         emit(smapper, this, "@1++;", lmapper.getI(varIndx));
   840                     } else {
   841                         emit(smapper, this, "@1 += @2;",
   842                              lmapper.getI(varIndx),
   843                              Integer.toString(incrBy));
   844                     }
   845                     break;
   846                 }
   847                 case opc_return:
   848                     emit(smapper, this, "return;");
   849                     break;
   850                 case opc_ireturn:
   851                     emit(smapper, this, "return @1;", smapper.popI());
   852                     break;
   853                 case opc_lreturn:
   854                     emit(smapper, this, "return @1;", smapper.popL());
   855                     break;
   856                 case opc_freturn:
   857                     emit(smapper, this, "return @1;", smapper.popF());
   858                     break;
   859                 case opc_dreturn:
   860                     emit(smapper, this, "return @1;", smapper.popD());
   861                     break;
   862                 case opc_areturn:
   863                     emit(smapper, this, "return @1;", smapper.popA());
   864                     break;
   865                 case opc_i2l:
   866                     smapper.replace(this, VarType.LONG, "@1", smapper.getI(0));
   867                     break;
   868                 case opc_i2f:
   869                     smapper.replace(this, VarType.FLOAT, "@1", smapper.getI(0));
   870                     break;
   871                 case opc_i2d:
   872                     smapper.replace(this, VarType.DOUBLE, "@1", smapper.getI(0));
   873                     break;
   874                 case opc_l2i:
   875                     smapper.replace(this, VarType.INTEGER, "(@1).toInt32()", smapper.getL(0));
   876                     break;
   877                     // max int check?
   878                 case opc_l2f:
   879                     smapper.replace(this, VarType.FLOAT, "(@1).toFP()", smapper.getL(0));
   880                     break;
   881                 case opc_l2d:
   882                     smapper.replace(this, VarType.DOUBLE, "(@1).toFP()", smapper.getL(0));
   883                     break;
   884                 case opc_f2d:
   885                     smapper.replace(this, VarType.DOUBLE, "@1",
   886                          smapper.getF(0));
   887                     break;
   888                 case opc_d2f:
   889                     smapper.replace(this, VarType.FLOAT, "@1",
   890                          smapper.getD(0));
   891                     break;
   892                 case opc_f2i:
   893                     smapper.replace(this, VarType.INTEGER, "(@1).toInt32()",
   894                          smapper.getF(0));
   895                     break;
   896                 case opc_f2l:
   897                     smapper.replace(this, VarType.LONG, "(@1).toLong()",
   898                          smapper.getF(0));
   899                     break;
   900                 case opc_d2i:
   901                     smapper.replace(this, VarType.INTEGER, "(@1).toInt32()",
   902                          smapper.getD(0));
   903                     break;
   904                 case opc_d2l:
   905                     smapper.replace(this, VarType.LONG, "(@1).toLong()", smapper.getD(0));
   906                     break;
   907                 case opc_i2b:
   908                     smapper.replace(this, VarType.INTEGER, "(@1).toInt8()", smapper.getI(0));
   909                     break;
   910                 case opc_i2c:
   911                 case opc_i2s:
   912                     smapper.replace(this, VarType.INTEGER, "(@1).toInt16()", smapper.getI(0));
   913                     break;
   914                 case opc_aconst_null:
   915                     smapper.assign(this, VarType.REFERENCE, "null");
   916                     break;
   917                 case opc_iconst_m1:
   918                     smapper.assign(this, VarType.INTEGER, "-1");
   919                     break;
   920                 case opc_iconst_0:
   921                     smapper.assign(this, VarType.INTEGER, "0");
   922                     break;
   923                 case opc_dconst_0:
   924                     smapper.assign(this, VarType.DOUBLE, "0");
   925                     break;
   926                 case opc_lconst_0:
   927                     smapper.assign(this, VarType.LONG, "0");
   928                     break;
   929                 case opc_fconst_0:
   930                     smapper.assign(this, VarType.FLOAT, "0");
   931                     break;
   932                 case opc_iconst_1:
   933                     smapper.assign(this, VarType.INTEGER, "1");
   934                     break;
   935                 case opc_lconst_1:
   936                     smapper.assign(this, VarType.LONG, "1");
   937                     break;
   938                 case opc_fconst_1:
   939                     smapper.assign(this, VarType.FLOAT, "1");
   940                     break;
   941                 case opc_dconst_1:
   942                     smapper.assign(this, VarType.DOUBLE, "1");
   943                     break;
   944                 case opc_iconst_2:
   945                     smapper.assign(this, VarType.INTEGER, "2");
   946                     break;
   947                 case opc_fconst_2:
   948                     smapper.assign(this, VarType.FLOAT, "2");
   949                     break;
   950                 case opc_iconst_3:
   951                     smapper.assign(this, VarType.INTEGER, "3");
   952                     break;
   953                 case opc_iconst_4:
   954                     smapper.assign(this, VarType.INTEGER, "4");
   955                     break;
   956                 case opc_iconst_5:
   957                     smapper.assign(this, VarType.INTEGER, "5");
   958                     break;
   959                 case opc_ldc: {
   960                     int indx = readUByte(byteCodes, ++i);
   961                     String v = encodeConstant(indx);
   962                     int type = VarType.fromConstantType(jc.getTag(indx));
   963                     smapper.assign(this, type, v);
   964                     break;
   965                 }
   966                 case opc_ldc_w:
   967                 case opc_ldc2_w: {
   968                     int indx = readUShortArg(byteCodes, i);
   969                     i += 2;
   970                     String v = encodeConstant(indx);
   971                     int type = VarType.fromConstantType(jc.getTag(indx));
   972                     if (type == VarType.LONG) {
   973                         final Long lv = new Long(v);
   974                         final int low = (int)(lv.longValue() & 0xFFFFFFFF);
   975                         final int hi = (int)(lv.longValue() >> 32);
   976                         if (hi == 0) {
   977                             smapper.assign(this, VarType.LONG, "0x" + Integer.toHexString(low));
   978                         } else {
   979                             smapper.assign(this, VarType.LONG,
   980                                 "0x" + Integer.toHexString(hi) + ".next32(0x" + 
   981                                     Integer.toHexString(low) + ")"
   982                             );
   983                         }
   984                     } else {
   985                         smapper.assign(this, type, v);
   986                     }
   987                     break;
   988                 }
   989                 case opc_lcmp:
   990                     smapper.replace(this, VarType.INTEGER, "(@2).compare64(@1)", smapper.popL(), smapper.getL(0));
   991                     break;
   992                 case opc_fcmpl:
   993                 case opc_fcmpg:
   994                     emit(smapper, this, "var @3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
   995                          smapper.popF(), smapper.popF(), smapper.pushI());
   996                     break;
   997                 case opc_dcmpl:
   998                 case opc_dcmpg:
   999                     emit(smapper, this, "var @3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
  1000                          smapper.popD(), smapper.popD(), smapper.pushI());
  1001                     break;
  1002                 case opc_if_acmpeq:
  1003                     i = generateIf(smapper, byteCodes, i, smapper.popA(), smapper.popA(),
  1004                                    "===", topMostLabel);
  1005                     break;
  1006                 case opc_if_acmpne:
  1007                     i = generateIf(smapper, byteCodes, i, smapper.popA(), smapper.popA(),
  1008                                    "!==", topMostLabel);
  1009                     break;
  1010                 case opc_if_icmpeq:
  1011                     i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
  1012                                    "==", topMostLabel);
  1013                     break;
  1014                 case opc_ifeq: {
  1015                     int indx = i + readShortArg(byteCodes, i);
  1016                     emitIf(smapper, this, "if ((@1) == 0) ",
  1017                          smapper.popI(), i, indx, topMostLabel);
  1018                     i += 2;
  1019                     break;
  1020                 }
  1021                 case opc_ifne: {
  1022                     int indx = i + readShortArg(byteCodes, i);
  1023                     emitIf(smapper, this, "if ((@1) != 0) ",
  1024                          smapper.popI(), i, indx, topMostLabel);
  1025                     i += 2;
  1026                     break;
  1027                 }
  1028                 case opc_iflt: {
  1029                     int indx = i + readShortArg(byteCodes, i);
  1030                     emitIf(smapper, this, "if ((@1) < 0) ",
  1031                          smapper.popI(), i, indx, topMostLabel);
  1032                     i += 2;
  1033                     break;
  1034                 }
  1035                 case opc_ifle: {
  1036                     int indx = i + readShortArg(byteCodes, i);
  1037                     emitIf(smapper, this, "if ((@1) <= 0) ",
  1038                          smapper.popI(), i, indx, topMostLabel);
  1039                     i += 2;
  1040                     break;
  1041                 }
  1042                 case opc_ifgt: {
  1043                     int indx = i + readShortArg(byteCodes, i);
  1044                     emitIf(smapper, this, "if ((@1) > 0) ",
  1045                          smapper.popI(), i, indx, topMostLabel);
  1046                     i += 2;
  1047                     break;
  1048                 }
  1049                 case opc_ifge: {
  1050                     int indx = i + readShortArg(byteCodes, i);
  1051                     emitIf(smapper, this, "if ((@1) >= 0) ",
  1052                          smapper.popI(), i, indx, topMostLabel);
  1053                     i += 2;
  1054                     break;
  1055                 }
  1056                 case opc_ifnonnull: {
  1057                     int indx = i + readShortArg(byteCodes, i);
  1058                     emitIf(smapper, this, "if ((@1) !== null) ",
  1059                          smapper.popA(), i, indx, topMostLabel);
  1060                     i += 2;
  1061                     break;
  1062                 }
  1063                 case opc_ifnull: {
  1064                     int indx = i + readShortArg(byteCodes, i);
  1065                     emitIf(smapper, this, "if ((@1) === null) ",
  1066                          smapper.popA(), i, indx, topMostLabel);
  1067                     i += 2;
  1068                     break;
  1069                 }
  1070                 case opc_if_icmpne:
  1071                     i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
  1072                                    "!=", topMostLabel);
  1073                     break;
  1074                 case opc_if_icmplt:
  1075                     i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
  1076                                    "<", topMostLabel);
  1077                     break;
  1078                 case opc_if_icmple:
  1079                     i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
  1080                                    "<=", topMostLabel);
  1081                     break;
  1082                 case opc_if_icmpgt:
  1083                     i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
  1084                                    ">", topMostLabel);
  1085                     break;
  1086                 case opc_if_icmpge:
  1087                     i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
  1088                                    ">=", topMostLabel);
  1089                     break;
  1090                 case opc_goto: {
  1091                     smapper.flush(this);
  1092                     int indx = i + readShortArg(byteCodes, i);
  1093                     goTo(this, i, indx, topMostLabel);
  1094                     i += 2;
  1095                     break;
  1096                 }
  1097                 case opc_lookupswitch: {
  1098                     i = generateLookupSwitch(i, byteCodes, smapper, topMostLabel);
  1099                     break;
  1100                 }
  1101                 case opc_tableswitch: {
  1102                     i = generateTableSwitch(i, byteCodes, smapper, topMostLabel);
  1103                     break;
  1104                 }
  1105                 case opc_invokeinterface: {
  1106                     i = invokeVirtualMethod(byteCodes, i, smapper) + 2;
  1107                     break;
  1108                 }
  1109                 case opc_invokevirtual:
  1110                     i = invokeVirtualMethod(byteCodes, i, smapper);
  1111                     break;
  1112                 case opc_invokespecial:
  1113                     i = invokeStaticMethod(byteCodes, i, smapper, false);
  1114                     break;
  1115                 case opc_invokestatic:
  1116                     i = invokeStaticMethod(byteCodes, i, smapper, true);
  1117                     break;
  1118                 case opc_invokedynamic: {
  1119                     int indx = readUShortArg(byteCodes, i);
  1120                     println("invoke dynamic: " + indx);
  1121                     ByteCodeParser.CPX2 c2 = jc.getCpoolEntry(indx);
  1122                     BootMethodData bm = jc.getBootMethod(c2.cpx1);
  1123                     CPX2 methodHandle = jc.getCpoolEntry(bm.method);
  1124                     println("  type: " + methodHandle.cpx1);
  1125                     String[] mi = jc.getFieldInfoName(methodHandle.cpx2);
  1126                     String mcn = mangleClassName(mi[0]);
  1127                     char[] returnType = {'V'};
  1128                     StringBuilder cnt = new StringBuilder();
  1129                     String mn = findMethodName(mi, cnt, returnType);
  1130                     StringBuilder sb = new StringBuilder();
  1131                     sb.append("We don't handle invokedynamic, need to preprocess ahead-of-time:\n");
  1132                     sb.append("  mi[0]: ").append(mi[0]).append("\n");
  1133                     sb.append("  mi[1]: ").append(mi[1]).append("\n");
  1134                     sb.append("  mi[2]: ").append(mi[2]).append("\n");
  1135                     sb.append("  mn   : ").append(mn).append("\n");
  1136                     sb.append("  name and type: ").append(jc.stringValue(c2.cpx2, true)).append("\n");
  1137                     throw new IOException(sb.toString());
  1138                     /*
  1139                     CPX2 nameAndType = jc.getCpoolEntry(c2.cpx2);
  1140                     String type = jc.StringValue(nameAndType.cpx2);
  1141                     String object = accessClass(mcn) + "(false)";
  1142                     if (mn.startsWith("cons_")) {
  1143                         object += ".constructor";
  1144                     }
  1145                     append("var metHan = ");
  1146                     append(accessStaticMethod(object, mn, mi));
  1147                     append('(');
  1148                     String lookup = accessClass("java_lang_invoke_MethodHandles") + "(false).findFor__Ljava_lang_invoke_MethodHandles$Lookup_2Ljava_lang_Class_2(CLS.$class)";
  1149                     append(lookup);
  1150                     append(", '").append(mi[1]).append("', ");
  1151                     String methodType = accessClass("java_lang_invoke_MethodType") + "(false).fromMethodDescriptorString__Ljava_lang_invoke_MethodType_2Ljava_lang_String_2Ljava_lang_ClassLoader_2(";
  1152                     append(methodType).append("'").append(type).append("', null)");
  1153 //                    if (numArguments > 0) {
  1154 //                        append(vars[0]);
  1155 //                        for (int j = 1; j < numArguments; ++j) {
  1156 //                            append(", ");
  1157 //                            append(vars[j]);
  1158 //                        }
  1159 //                    }
  1160                     append(");");
  1161                     emit(smapper, this, "throw 'Invoke dynamic: ' + @1 + ': ' + metHan;", "" + indx);
  1162                     i += 4;
  1163                     break;
  1164                     */
  1165                 }
  1166                 case opc_new: {
  1167                     int indx = readUShortArg(byteCodes, i);
  1168                     String ci = jc.getClassName(indx);
  1169                     emit(smapper, this, "var @1 = new @2;",
  1170                          smapper.pushA(), accessClass(mangleClassName(ci)));
  1171                     addReference(ci);
  1172                     i += 2;
  1173                     break;
  1174                 }
  1175                 case opc_newarray:
  1176                     int atype = readUByte(byteCodes, ++i);
  1177                     generateNewArray(atype, smapper);
  1178                     break;
  1179                 case opc_anewarray: {
  1180                     int type = readUShortArg(byteCodes, i);
  1181                     i += 2;
  1182                     generateANewArray(type, smapper);
  1183                     break;
  1184                 }
  1185                 case opc_multianewarray: {
  1186                     int type = readUShortArg(byteCodes, i);
  1187                     i += 2;
  1188                     i = generateMultiANewArray(type, byteCodes, i, smapper);
  1189                     break;
  1190                 }
  1191                 case opc_arraylength:
  1192                     smapper.replace(this, VarType.INTEGER, "(@1).length", smapper.getA(0));
  1193                     break;
  1194                 case opc_lastore:
  1195                     emit(smapper, this, "Array.at(@3, @2, @1);",
  1196                          smapper.popL(), smapper.popI(), smapper.popA());
  1197                     break;
  1198                 case opc_fastore:
  1199                     emit(smapper, this, "Array.at(@3, @2, @1);",
  1200                          smapper.popF(), smapper.popI(), smapper.popA());
  1201                     break;
  1202                 case opc_dastore:
  1203                     emit(smapper, this, "Array.at(@3, @2, @1);",
  1204                          smapper.popD(), smapper.popI(), smapper.popA());
  1205                     break;
  1206                 case opc_aastore:
  1207                     emit(smapper, this, "Array.at(@3, @2, @1);",
  1208                          smapper.popA(), smapper.popI(), smapper.popA());
  1209                     break;
  1210                 case opc_iastore:
  1211                 case opc_bastore:
  1212                 case opc_castore:
  1213                 case opc_sastore:
  1214                     emit(smapper, this, "Array.at(@3, @2, @1);",
  1215                          smapper.popI(), smapper.popI(), smapper.popA());
  1216                     break;
  1217                 case opc_laload:
  1218                     smapper.replace(this, VarType.LONG, "Array.at(@2, @1)",
  1219                          smapper.popI(), smapper.getA(0));
  1220                     break;
  1221                 case opc_faload:
  1222                     smapper.replace(this, VarType.FLOAT, "Array.at(@2, @1)",
  1223                          smapper.popI(), smapper.getA(0));
  1224                     break;
  1225                 case opc_daload:
  1226                     smapper.replace(this, VarType.DOUBLE, "Array.at(@2, @1)",
  1227                          smapper.popI(), smapper.getA(0));
  1228                     break;
  1229                 case opc_aaload:
  1230                     smapper.replace(this, VarType.REFERENCE, "Array.at(@2, @1)",
  1231                          smapper.popI(), smapper.getA(0));
  1232                     break;
  1233                 case opc_iaload:
  1234                 case opc_baload:
  1235                 case opc_caload:
  1236                 case opc_saload:
  1237                     smapper.replace(this, VarType.INTEGER, "Array.at(@2, @1)",
  1238                          smapper.popI(), smapper.getA(0));
  1239                     break;
  1240                 case opc_pop:
  1241                 case opc_pop2:
  1242                     smapper.pop(1);
  1243                     debug("/* pop */");
  1244                     break;
  1245                 case opc_dup: {
  1246                     final Variable v = smapper.get(0);
  1247                     if (smapper.isDirty()) {
  1248                         emit(smapper, this, "var @1 = @2;", smapper.pushT(v.getType()), v);
  1249                     } else {
  1250                         smapper.assign(this, v.getType(), v);
  1251                     }   
  1252                     break;
  1253                 }
  1254                 case opc_dup2: {
  1255                     final Variable vi1 = smapper.get(0);
  1256 
  1257                     if (vi1.isCategory2()) {
  1258                         emit(smapper, this, "var @1 = @2;",
  1259                              smapper.pushT(vi1.getType()), vi1);
  1260                     } else {
  1261                         final Variable vi2 = smapper.get(1);
  1262                         emit(smapper, this, "var @1 = @2, @3 = @4;",
  1263                              smapper.pushT(vi2.getType()), vi2,
  1264                              smapper.pushT(vi1.getType()), vi1);
  1265                     }
  1266                     break;
  1267                 }
  1268                 case opc_dup_x1: {
  1269                     final Variable vi1 = smapper.pop(this);
  1270                     final Variable vi2 = smapper.pop(this);
  1271                     final Variable vo3 = smapper.pushT(vi1.getType());
  1272                     final Variable vo2 = smapper.pushT(vi2.getType());
  1273                     final Variable vo1 = smapper.pushT(vi1.getType());
  1274 
  1275                     emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
  1276                          vo1, vi1, vo2, vi2, vo3, vo1);
  1277                     break;
  1278                 }
  1279                 case opc_dup2_x1: {
  1280                     final Variable vi1 = smapper.pop(this);
  1281                     final Variable vi2 = smapper.pop(this);
  1282 
  1283                     if (vi1.isCategory2()) {
  1284                         final Variable vo3 = smapper.pushT(vi1.getType());
  1285                         final Variable vo2 = smapper.pushT(vi2.getType());
  1286                         final Variable vo1 = smapper.pushT(vi1.getType());
  1287 
  1288                         emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
  1289                              vo1, vi1, vo2, vi2, vo3, vo1);
  1290                     } else {
  1291                         final Variable vi3 = smapper.pop(this);
  1292                         final Variable vo5 = smapper.pushT(vi2.getType());
  1293                         final Variable vo4 = smapper.pushT(vi1.getType());
  1294                         final Variable vo3 = smapper.pushT(vi3.getType());
  1295                         final Variable vo2 = smapper.pushT(vi2.getType());
  1296                         final Variable vo1 = smapper.pushT(vi1.getType());
  1297 
  1298                         emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
  1299                              vo1, vi1, vo2, vi2, vo3, vi3);
  1300                         emit(smapper, this, " @1 = @2, @3 = @4;",
  1301                              vo4, vo1, vo5, vo2);
  1302                     }
  1303                     break;
  1304                 }
  1305                 case opc_dup_x2: {
  1306                     final Variable vi1 = smapper.pop(this);
  1307                     final Variable vi2 = smapper.pop(this);
  1308 
  1309                     if (vi2.isCategory2()) {
  1310                         final Variable vo3 = smapper.pushT(vi1.getType());
  1311                         final Variable vo2 = smapper.pushT(vi2.getType());
  1312                         final Variable vo1 = smapper.pushT(vi1.getType());
  1313 
  1314                         emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
  1315                              vo1, vi1, vo2, vi2, vo3, vo1);
  1316                     } else {
  1317                         final Variable vi3 = smapper.pop(this);
  1318                         final Variable vo4 = smapper.pushT(vi1.getType());
  1319                         final Variable vo3 = smapper.pushT(vi3.getType());
  1320                         final Variable vo2 = smapper.pushT(vi2.getType());
  1321                         final Variable vo1 = smapper.pushT(vi1.getType());
  1322 
  1323                         emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
  1324                              vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
  1325                     }
  1326                     break;
  1327                 }
  1328                 case opc_dup2_x2: {
  1329                     final Variable vi1 = smapper.pop(this);
  1330                     final Variable vi2 = smapper.pop(this);
  1331 
  1332                     if (vi1.isCategory2()) {
  1333                         if (vi2.isCategory2()) {
  1334                             final Variable vo3 = smapper.pushT(vi1.getType());
  1335                             final Variable vo2 = smapper.pushT(vi2.getType());
  1336                             final Variable vo1 = smapper.pushT(vi1.getType());
  1337 
  1338                             emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
  1339                                  vo1, vi1, vo2, vi2, vo3, vo1);
  1340                         } else {
  1341                             final Variable vi3 = smapper.pop(this);
  1342                             final Variable vo4 = smapper.pushT(vi1.getType());
  1343                             final Variable vo3 = smapper.pushT(vi3.getType());
  1344                             final Variable vo2 = smapper.pushT(vi2.getType());
  1345                             final Variable vo1 = smapper.pushT(vi1.getType());
  1346 
  1347                             emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
  1348                                  vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
  1349                         }
  1350                     } else {
  1351                         final Variable vi3 = smapper.pop(this);
  1352 
  1353                         if (vi3.isCategory2()) {
  1354                             final Variable vo5 = smapper.pushT(vi2.getType());
  1355                             final Variable vo4 = smapper.pushT(vi1.getType());
  1356                             final Variable vo3 = smapper.pushT(vi3.getType());
  1357                             final Variable vo2 = smapper.pushT(vi2.getType());
  1358                             final Variable vo1 = smapper.pushT(vi1.getType());
  1359 
  1360                             emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
  1361                                  vo1, vi1, vo2, vi2, vo3, vi3);
  1362                             emit(smapper, this, " @1 = @2, @3 = @4;",
  1363                                  vo4, vo1, vo5, vo2);
  1364                         } else {
  1365                             final Variable vi4 = smapper.pop(this);
  1366                             final Variable vo6 = smapper.pushT(vi2.getType());
  1367                             final Variable vo5 = smapper.pushT(vi1.getType());
  1368                             final Variable vo4 = smapper.pushT(vi4.getType());
  1369                             final Variable vo3 = smapper.pushT(vi3.getType());
  1370                             final Variable vo2 = smapper.pushT(vi2.getType());
  1371                             final Variable vo1 = smapper.pushT(vi1.getType());
  1372                             
  1373                             emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8,",
  1374                                  vo1, vi1, vo2, vi2, vo3, vi3, vo4, vi4);
  1375                             emit(smapper, this, " @1 = @2, @3 = @4;",
  1376                                  vo5, vo1, vo6, vo2);
  1377                         }
  1378                     }
  1379                     break;
  1380                 }
  1381                 case opc_swap: {
  1382                     final Variable vi1 = smapper.get(0);
  1383                     final Variable vi2 = smapper.get(1);
  1384 
  1385                     if (vi1.getType() == vi2.getType()) {
  1386                         final Variable tmp = smapper.pushT(vi1.getType());
  1387 
  1388                         emit(smapper, this, "var @1 = @2, @2 = @3, @3 = @1;",
  1389                              tmp, vi1, vi2);
  1390                         smapper.pop(1);
  1391                     } else {
  1392                         smapper.pop(2);
  1393                         smapper.pushT(vi1.getType());
  1394                         smapper.pushT(vi2.getType());
  1395                     }
  1396                     break;
  1397                 }
  1398                 case opc_bipush:
  1399                     smapper.assign(this, VarType.INTEGER, 
  1400                         "(" + Integer.toString(byteCodes[++i]) + ")");
  1401                     break;
  1402                 case opc_sipush:
  1403                     smapper.assign(this, VarType.INTEGER, 
  1404                         "(" + Integer.toString(readShortArg(byteCodes, i)) + ")"
  1405                     );
  1406                     i += 2;
  1407                     break;
  1408                 case opc_getfield: {
  1409                     int indx = readUShortArg(byteCodes, i);
  1410                     String[] fi = jc.getFieldInfoName(indx);
  1411                     final int type = VarType.fromFieldType(fi[2].charAt(0));
  1412                     final String mangleClass = mangleClassName(fi[0]);
  1413                     final String mangleClassAccess = accessClassFalse(mangleClass);
  1414                     smapper.replace(this, type, "@2.call(@1)",
  1415                          smapper.getA(0),
  1416                          accessField(mangleClassAccess,
  1417                                      "_" + fi[1], fi)
  1418                     );
  1419                     i += 2;
  1420                     addReference(fi[0]);
  1421                     break;
  1422                 }
  1423                 case opc_putfield: {
  1424                     int indx = readUShortArg(byteCodes, i);
  1425                     String[] fi = jc.getFieldInfoName(indx);
  1426                     final int type = VarType.fromFieldType(fi[2].charAt(0));
  1427                     final String mangleClass = mangleClassName(fi[0]);
  1428                     final String mangleClassAccess = accessClassFalse(mangleClass);
  1429                     emit(smapper, this, "@3.call(@2, @1);",
  1430                          smapper.popT(type),
  1431                          smapper.popA(),
  1432                          accessField(mangleClassAccess,
  1433                                      "_" + fi[1], fi));
  1434                     i += 2;
  1435                     addReference(fi[0]);
  1436                     break;
  1437                 }
  1438                 case opc_getstatic: {
  1439                     int indx = readUShortArg(byteCodes, i);
  1440                     String[] fi = jc.getFieldInfoName(indx);
  1441                     final int type = VarType.fromFieldType(fi[2].charAt(0));
  1442                     String ac = accessClassFalse(mangleClassName(fi[0]));
  1443                     String af = accessField(ac, "_" + fi[1], fi);
  1444                     smapper.assign(this, type, af + "()");
  1445                     i += 2;
  1446                     addReference(fi[0]);
  1447                     break;
  1448                 }
  1449                 case opc_putstatic: {
  1450                     int indx = readUShortArg(byteCodes, i);
  1451                     String[] fi = jc.getFieldInfoName(indx);
  1452                     final int type = VarType.fromFieldType(fi[2].charAt(0));
  1453                     emit(smapper, this, "@1._@2(@3);",
  1454                          accessClassFalse(mangleClassName(fi[0])), fi[1],
  1455                          smapper.popT(type));
  1456                     i += 2;
  1457                     addReference(fi[0]);
  1458                     break;
  1459                 }
  1460                 case opc_checkcast: {
  1461                     int indx = readUShortArg(byteCodes, i);
  1462                     generateCheckcast(indx, smapper);
  1463                     i += 2;
  1464                     break;
  1465                 }
  1466                 case opc_instanceof: {
  1467                     int indx = readUShortArg(byteCodes, i);
  1468                     generateInstanceOf(indx, smapper);
  1469                     i += 2;
  1470                     break;
  1471                 }
  1472                 case opc_athrow: {
  1473                     final CharSequence v = smapper.popA();
  1474                     smapper.clear();
  1475 
  1476                     emit(smapper, this, "{ var @1 = @2; throw @2; }",
  1477                          smapper.pushA(), v);
  1478                     break;
  1479                 }
  1480 
  1481                 case opc_monitorenter: {
  1482                     debug("/* monitor enter */");
  1483                     smapper.popA();
  1484                     break;
  1485                 }
  1486 
  1487                 case opc_monitorexit: {
  1488                     debug("/* monitor exit */");
  1489                     smapper.popA();
  1490                     break;
  1491                 }
  1492 
  1493                 case opc_wide:
  1494                     wide = true;
  1495                     break;
  1496 
  1497                 default: {
  1498                     wide = false;
  1499                     emit(smapper, this, "throw 'unknown bytecode @1';",
  1500                          Integer.toString(c));
  1501                 }
  1502             }
  1503             if (debug(" //")) {
  1504                 generateByteCodeComment(prev, i, byteCodes);
  1505             }
  1506             if (outChanged) {
  1507                 append("\n");
  1508             }
  1509         }
  1510         if (previousTrap != null) {
  1511             generateCatch(previousTrap, byteCodes.length, topMostLabel);
  1512         }
  1513         if (didBranches) {
  1514             append("\n    }\n");
  1515         }
  1516         while (openBraces-- > 0) {
  1517             append('}');
  1518         }
  1519         if (defineProp) {
  1520             append("\n}});");
  1521         } else {
  1522             append("\n};");
  1523         }
  1524         return defineProp;
  1525     }
  1526 
  1527     private int generateIf(StackMapper mapper, byte[] byteCodes, 
  1528         int i, final CharSequence v2, final CharSequence v1, 
  1529         final String test, int topMostLabel
  1530     ) throws IOException {
  1531         mapper.flush(this);
  1532         int indx = i + readShortArg(byteCodes, i);
  1533         append("if ((").append(v1)
  1534            .append(") ").append(test).append(" (")
  1535            .append(v2).append(")) ");
  1536         goTo(this, i, indx, topMostLabel);
  1537         return i + 2;
  1538     }
  1539     
  1540     private int readInt4(byte[] byteCodes, int offset) {
  1541         final int d = byteCodes[offset + 0] << 24;
  1542         final int c = byteCodes[offset + 1] << 16;
  1543         final int b = byteCodes[offset + 2] << 8;
  1544         final int a = byteCodes[offset + 3];
  1545         return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
  1546     }
  1547     private static int readUByte(byte[] byteCodes, int offset) {
  1548         return byteCodes[offset] & 0xff;
  1549     }
  1550 
  1551     private static int readUShort(byte[] byteCodes, int offset) {
  1552         return ((byteCodes[offset] & 0xff) << 8)
  1553                     | (byteCodes[offset + 1] & 0xff);
  1554     }
  1555     private static int readUShortArg(byte[] byteCodes, int offsetInstruction) {
  1556         return readUShort(byteCodes, offsetInstruction + 1);
  1557     }
  1558 
  1559     private static int readShort(byte[] byteCodes, int offset) {
  1560         int signed = byteCodes[offset];
  1561         byte b0 = (byte)signed;
  1562         return (b0 << 8) | (byteCodes[offset + 1] & 0xff);
  1563     }
  1564     private static int readShortArg(byte[] byteCodes, int offsetInstruction) {
  1565         return readShort(byteCodes, offsetInstruction + 1);
  1566     }
  1567 
  1568     private static void countArgs(String descriptor, char[] returnType, StringBuilder sig, StringBuilder cnt) {
  1569         int i = 0;
  1570         Boolean count = null;
  1571         boolean array = false;
  1572         sig.append("__");
  1573         int firstPos = sig.length();
  1574         while (i < descriptor.length()) {
  1575             char ch = descriptor.charAt(i++);
  1576             switch (ch) {
  1577                 case '(':
  1578                     count = true;
  1579                     continue;
  1580                 case ')':
  1581                     count = false;
  1582                     continue;
  1583                 case 'B': 
  1584                 case 'C': 
  1585                 case 'D': 
  1586                 case 'F': 
  1587                 case 'I': 
  1588                 case 'J': 
  1589                 case 'S': 
  1590                 case 'Z': 
  1591                     if (count) {
  1592                         if (array) {
  1593                             sig.append("_3");
  1594                         }
  1595                         sig.append(ch);
  1596                         if (ch == 'J' || ch == 'D') {
  1597                             cnt.append('1');
  1598                         } else {
  1599                             cnt.append('0');
  1600                         }
  1601                     } else {
  1602                         sig.insert(firstPos, ch);
  1603                         if (array) {
  1604                             returnType[0] = '[';
  1605                             sig.insert(firstPos, "_3");
  1606                         } else {
  1607                             returnType[0] = ch;
  1608                         }
  1609                     }
  1610                     array = false;
  1611                     continue;
  1612                 case 'V': 
  1613                     assert !count;
  1614                     returnType[0] = 'V';
  1615                     sig.insert(firstPos, 'V');
  1616                     continue;
  1617                 case 'L':
  1618                     int next = descriptor.indexOf(';', i);
  1619                     String realSig = mangleSig(descriptor, i - 1, next + 1);
  1620                     if (count) {
  1621                         if (array) {
  1622                             sig.append("_3");
  1623                         }
  1624                         sig.append(realSig);
  1625                         cnt.append('0');
  1626                     } else {
  1627                         sig.insert(firstPos, realSig);
  1628                         if (array) {
  1629                             sig.insert(firstPos, "_3");
  1630                         }
  1631                         returnType[0] = 'L';
  1632                     }
  1633                     i = next + 1;
  1634                     array = false;
  1635                     continue;
  1636                 case '[':
  1637                     array = true;
  1638                     continue;
  1639                 default:
  1640                     throw new IllegalStateException("Invalid char: " + ch);
  1641             }
  1642         }
  1643     }
  1644     
  1645     static String mangleSig(String sig) {
  1646         return mangleSig(sig, 0, sig.length());
  1647     }
  1648     
  1649     private static String mangleMethodName(String name) {
  1650         StringBuilder sb = new StringBuilder(name.length() * 2);
  1651         int last = name.length();
  1652         for (int i = 0; i < last; i++) {
  1653             final char ch = name.charAt(i);
  1654             switch (ch) {
  1655                 case '_': sb.append("_1"); break;
  1656                 default: sb.append(ch); break;
  1657             }
  1658         }
  1659         return sb.toString();
  1660     }
  1661     private static String mangleSig(String txt, int first, int last) {
  1662         StringBuilder sb = new StringBuilder((last - first) * 2);
  1663         for (int i = first; i < last; i++) {
  1664             final char ch = txt.charAt(i);
  1665             switch (ch) {
  1666                 case '/': sb.append('_'); break;
  1667                 case '_': sb.append("_1"); break;
  1668                 case ';': sb.append("_2"); break;
  1669                 case '[': sb.append("_3"); break;
  1670                 default: 
  1671                     if (Character.isJavaIdentifierPart(ch)) {
  1672                         sb.append(ch);
  1673                     } else {
  1674                         sb.append("_0");
  1675                         String hex = Integer.toHexString(ch).toLowerCase();
  1676                         for (int m = hex.length(); m < 4; m++) {
  1677                             sb.append("0");
  1678                         }
  1679                         sb.append(hex);
  1680                     }
  1681                 break;
  1682             }
  1683         }
  1684         return sb.toString();
  1685     }
  1686     
  1687     private static String mangleClassName(String name) {
  1688         return mangleSig(name);
  1689     }
  1690 
  1691     private static String findMethodName(MethodData m, StringBuilder cnt) {
  1692         StringBuilder name = new StringBuilder();
  1693         if ("<init>".equals(m.getName())) { // NOI18N
  1694             name.append("cons"); // NOI18N
  1695         } else if ("<clinit>".equals(m.getName())) { // NOI18N
  1696             name.append("class"); // NOI18N
  1697         } else {
  1698             name.append(mangleMethodName(m.getName()));
  1699         } 
  1700         
  1701         countArgs(m.getInternalSig(), new char[1], name, cnt);
  1702         return name.toString();
  1703     }
  1704 
  1705     static String findMethodName(String[] mi, StringBuilder cnt, char[] returnType) {
  1706         StringBuilder name = new StringBuilder();
  1707         String descr = mi[2];//mi.getDescriptor();
  1708         String nm= mi[1];
  1709         if ("<init>".equals(nm)) { // NOI18N
  1710             name.append("cons"); // NOI18N
  1711         } else {
  1712             name.append(mangleMethodName(nm));
  1713         }
  1714         countArgs(descr, returnType, name, cnt);
  1715         return name.toString();
  1716     }
  1717 
  1718     private int invokeStaticMethod(byte[] byteCodes, int i, final StackMapper mapper, boolean isStatic)
  1719     throws IOException {
  1720         int methodIndex = readUShortArg(byteCodes, i);
  1721         String[] mi = jc.getFieldInfoName(methodIndex);
  1722         char[] returnType = { 'V' };
  1723         StringBuilder cnt = new StringBuilder();
  1724         String mn = findMethodName(mi, cnt, returnType);
  1725         
  1726         final int numArguments = isStatic ? cnt.length() : cnt.length() + 1;
  1727         final CharSequence[] vars = new CharSequence[numArguments];
  1728 
  1729         for (int j = numArguments - 1; j >= 0; --j) {
  1730             vars[j] = mapper.popValue();
  1731         }
  1732 
  1733         if ((
  1734             "newUpdater__Ljava_util_concurrent_atomic_AtomicIntegerFieldUpdater_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
  1735             && "java/util/concurrent/atomic/AtomicIntegerFieldUpdater".equals(mi[0])
  1736         ) || (
  1737             "newUpdater__Ljava_util_concurrent_atomic_AtomicLongFieldUpdater_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
  1738             && "java/util/concurrent/atomic/AtomicLongFieldUpdater".equals(mi[0])
  1739         )) {
  1740             if (vars[1] instanceof String) {
  1741                 String field = vars[1].toString();
  1742                 if (field.length() > 2 && field.charAt(0) == '"' && field.charAt(field.length() - 1) == '"') {
  1743                     vars[1] = "c._" + field.substring(1, field.length() - 1);
  1744                 }
  1745             }
  1746         }
  1747         if (
  1748             "newUpdater__Ljava_util_concurrent_atomic_AtomicReferenceFieldUpdater_2Ljava_lang_Class_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
  1749             && "java/util/concurrent/atomic/AtomicReferenceFieldUpdater".equals(mi[0])
  1750         ) {
  1751             if (vars[1] instanceof String) {
  1752                 String field = vars[2].toString();
  1753                 if (field.length() > 2 && field.charAt(0) == '"' && field.charAt(field.length() - 1) == '"') {
  1754                     vars[2] = "c._" + field.substring(1, field.length() - 1);
  1755                 }
  1756             }
  1757         }
  1758 
  1759         if (returnType[0] != 'V') {
  1760             mapper.flush(this);
  1761             append("var ")
  1762                .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
  1763                .append(" = ");
  1764         }
  1765 
  1766         final String in = mi[0];
  1767         String mcn;
  1768         if (callbacks && (
  1769             in.equals("org/apidesign/html/boot/spi/Fn") ||
  1770             in.equals("org/netbeans/html/boot/spi/Fn")
  1771         )) {
  1772             mcn = "java_lang_Class";
  1773         } else {
  1774             mcn = mangleClassName(in);
  1775         }
  1776         String object = accessClassFalse(mcn);
  1777         if (mn.startsWith("cons_")) {
  1778             object += ".constructor";
  1779         }
  1780         append(accessStaticMethod(object, mn, mi));
  1781         if (isStatic) {
  1782             append('(');
  1783         } else {
  1784             append(".call(");
  1785         }
  1786         if (numArguments > 0) {
  1787             append(vars[0]);
  1788             for (int j = 1; j < numArguments; ++j) {
  1789                 append(", ");
  1790                 append(vars[j]);
  1791             }
  1792         }
  1793         append(");");
  1794         i += 2;
  1795         addReference(in);
  1796         return i;
  1797     }
  1798     private int invokeVirtualMethod(byte[] byteCodes, int i, final StackMapper mapper)
  1799     throws IOException {
  1800         int methodIndex = readUShortArg(byteCodes, i);
  1801         String[] mi = jc.getFieldInfoName(methodIndex);
  1802         char[] returnType = { 'V' };
  1803         StringBuilder cnt = new StringBuilder();
  1804         String mn = findMethodName(mi, cnt, returnType);
  1805 
  1806         final int numArguments = cnt.length() + 1;
  1807         final CharSequence[] vars =  new CharSequence[numArguments];
  1808 
  1809         for (int j = numArguments - 1; j >= 0; --j) {
  1810             vars[j] = mapper.popValue();
  1811         }
  1812 
  1813         if (returnType[0] != 'V') {
  1814             mapper.flush(this);
  1815             append("var ")
  1816                .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
  1817                .append(" = ");
  1818         }
  1819 
  1820         append(accessVirtualMethod(vars[0].toString(), mn, mi, numArguments));
  1821         String sep = "";
  1822         for (int j = 1; j < numArguments; ++j) {
  1823             append(sep);
  1824             append(vars[j]);
  1825             sep = ", ";
  1826         }
  1827         append(");");
  1828         i += 2;
  1829         return i;
  1830     }
  1831 
  1832     private void addReference(String cn) throws IOException {
  1833         if (requireReference(cn)) {
  1834             debug(" /* needs " + cn + " */");
  1835         }
  1836     }
  1837 
  1838     private void outType(String d, StringBuilder out) {
  1839         int arr = 0;
  1840         while (d.charAt(0) == '[') {
  1841             out.append('A');
  1842             d = d.substring(1);
  1843         }
  1844         if (d.charAt(0) == 'L') {
  1845             assert d.charAt(d.length() - 1) == ';';
  1846             out.append(d.replace('/', '_').substring(0, d.length() - 1));
  1847         } else {
  1848             out.append(d);
  1849         }
  1850     }
  1851 
  1852     private String encodeConstant(int entryIndex) throws IOException {
  1853         String[] classRef = { null };
  1854         String s = jc.stringValue(entryIndex, classRef);
  1855         if (classRef[0] != null) {
  1856             if (classRef[0].startsWith("[")) {
  1857                 s = accessClass("java_lang_Class") + "(false)['forName__Ljava_lang_Class_2Ljava_lang_String_2']('" + classRef[0] + "')";
  1858             } else {
  1859                 addReference(classRef[0]);
  1860                 s = accessClassFalse(mangleClassName(s)) + ".constructor.$class";
  1861             }
  1862         }
  1863         return s;
  1864     }
  1865 
  1866     private String javaScriptBody(String destObject, MethodData m, boolean isStatic) throws IOException {
  1867         byte[] arr = m.findAnnotationData(true);
  1868         if (arr == null) {
  1869             return null;
  1870         }
  1871         final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
  1872         final String htmlType = "Lnet/java/html/js/JavaScriptBody;";
  1873         class P extends AnnotationParser {
  1874             public P() {
  1875                 super(false, true);
  1876             }
  1877             
  1878             int cnt;
  1879             String[] args = new String[30];
  1880             String body;
  1881             boolean javacall;
  1882             boolean html4j;
  1883             
  1884             @Override
  1885             protected void visitAttr(String type, String attr, String at, String value) {
  1886                 if (type.equals(jvmType)) {
  1887                     if ("body".equals(attr)) {
  1888                         body = value;
  1889                     } else if ("args".equals(attr)) {
  1890                         args[cnt++] = value;
  1891                     } else {
  1892                         throw new IllegalArgumentException(attr);
  1893                     }
  1894                 }
  1895                 if (type.equals(htmlType)) {
  1896                     html4j = true;
  1897                     if ("body".equals(attr)) {
  1898                         body = value;
  1899                     } else if ("args".equals(attr)) {
  1900                         args[cnt++] = value;
  1901                     } else if ("javacall".equals(attr)) {
  1902                         javacall = "1".equals(value);
  1903                     } else if ("wait4js".equals(attr)) {
  1904                         // ignore, we always invoke synchronously
  1905                     } else {
  1906                         throw new IllegalArgumentException(attr);
  1907                     }
  1908                 }
  1909             }
  1910         }
  1911         P p = new P();
  1912         p.parse(arr, jc);
  1913         if (p.body == null) {
  1914             return null;
  1915         }
  1916         StringBuilder cnt = new StringBuilder();
  1917         final String mn = findMethodName(m, cnt);
  1918         append("m = ").append(destObject).append(".").append(mn);
  1919         append(" = function(");
  1920         String space = "";
  1921         int index = 0;
  1922         StringBuilder toValue = new StringBuilder();
  1923         for (int i = 0; i < cnt.length(); i++) {
  1924             append(space);
  1925             space = outputArg(this, p.args, index);
  1926             if (p.html4j && space.length() > 0) {
  1927                 toValue.append("\n  ").append(p.args[index]).append(" = ")
  1928                     .append(accessClass("java_lang_Class")).append("(false).toJS(").
  1929                     append(p.args[index]).append(");");
  1930             }
  1931             index++;
  1932         }
  1933         append(") {").append("\n");
  1934         append(toValue.toString());
  1935         if (p.javacall) {
  1936             int lastSlash = jc.getClassName().lastIndexOf('/');
  1937             final String pkg = jc.getClassName().substring(0, lastSlash);
  1938             append(mangleCallbacks(pkg, p.body));
  1939             requireReference(pkg + "/$JsCallbacks$");
  1940         } else {
  1941             append(p.body);
  1942         }
  1943         append("\n}\n");
  1944         return mn;
  1945     }
  1946     
  1947     private static CharSequence mangleCallbacks(String pkgName, String body) {
  1948         StringBuilder sb = new StringBuilder();
  1949         int pos = 0;
  1950         for (;;) {
  1951             int next = body.indexOf(".@", pos);
  1952             if (next == -1) {
  1953                 sb.append(body.substring(pos));
  1954                 body = sb.toString();
  1955                 break;
  1956             }
  1957             int ident = next;
  1958             while (ident > 0) {
  1959                 if (!Character.isJavaIdentifierPart(body.charAt(--ident))) {
  1960                     ident++;
  1961                     break;
  1962                 }
  1963             }
  1964             String refId = body.substring(ident, next);
  1965 
  1966             sb.append(body.substring(pos, ident));
  1967 
  1968             int sigBeg = body.indexOf('(', next);
  1969             int sigEnd = body.indexOf(')', sigBeg);
  1970             int colon4 = body.indexOf("::", next);
  1971             if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
  1972                 throw new IllegalStateException("Malformed body " + body);
  1973             }
  1974             String fqn = body.substring(next + 2, colon4);
  1975             String method = body.substring(colon4 + 2, sigBeg);
  1976             String params = body.substring(sigBeg, sigEnd + 1);
  1977 
  1978             int paramBeg = body.indexOf('(', sigEnd + 1);
  1979             
  1980             sb.append("vm.").append(pkgName.replace('/', '_')).append("_$JsCallbacks$(false)._VM().");
  1981             sb.append(mangleJsCallbacks(fqn, method, params, false));
  1982             sb.append("(").append(refId);
  1983             if (body.charAt(paramBeg + 1) != ')') {
  1984                 sb.append(",");
  1985             }
  1986             pos = paramBeg + 1;
  1987         }
  1988         sb = null;
  1989         pos = 0;
  1990         for (;;) {
  1991             int next = body.indexOf("@", pos);
  1992             if (next == -1) {
  1993                 if (sb == null) {
  1994                     return body;
  1995                 }
  1996                 sb.append(body.substring(pos));
  1997                 return sb;
  1998             }
  1999             if (sb == null) {
  2000                 sb = new StringBuilder();
  2001             }
  2002 
  2003             sb.append(body.substring(pos, next));
  2004 
  2005             int sigBeg = body.indexOf('(', next);
  2006             int sigEnd = body.indexOf(')', sigBeg);
  2007             int colon4 = body.indexOf("::", next);
  2008             if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
  2009                 throw new IllegalStateException("Malformed body " + body);
  2010             }
  2011             String fqn = body.substring(next + 1, colon4);
  2012             String method = body.substring(colon4 + 2, sigBeg);
  2013             String params = body.substring(sigBeg, sigEnd + 1);
  2014 
  2015             int paramBeg = body.indexOf('(', sigEnd + 1);
  2016             
  2017             sb.append("vm.").append(pkgName.replace('/', '_')).append("_$JsCallbacks$(false)._VM().");
  2018             sb.append(mangleJsCallbacks(fqn, method, params, true));
  2019             sb.append("(");
  2020             pos = paramBeg + 1;
  2021         }
  2022     }
  2023 
  2024     static String mangleJsCallbacks(String fqn, String method, String params, boolean isStatic) {
  2025         if (params.startsWith("(")) {
  2026             params = params.substring(1);
  2027         }
  2028         if (params.endsWith(")")) {
  2029             params = params.substring(0, params.length() - 1);
  2030         }
  2031         StringBuilder sb = new StringBuilder();
  2032         final String fqnu = fqn.replace('.', '_');
  2033         final String rfqn = mangleClassName(fqnu);
  2034         final String rm = mangleMethodName(method);
  2035         final String srp;
  2036         {
  2037             StringBuilder pb = new StringBuilder();
  2038             int len = params.length();
  2039             int indx = 0;
  2040             while (indx < len) {
  2041                 char ch = params.charAt(indx);
  2042                 if (ch == '[' || ch == 'L') {
  2043                     int column = params.indexOf(';', indx) + 1;
  2044                     if (column > indx) {
  2045                         String real = params.substring(indx, column);
  2046                         if ("Ljava/lang/String;".equals(real)) {
  2047                             pb.append("Ljava/lang/String;");
  2048                             indx = column;
  2049                             continue;
  2050                         }
  2051                     }
  2052                     pb.append("Ljava/lang/Object;");
  2053                     indx = column;
  2054                 } else {
  2055                     pb.append(ch);
  2056                     indx++;
  2057                 }
  2058             }
  2059             srp = mangleSig(pb.toString());
  2060         }
  2061         final String rp = mangleSig(params);
  2062         final String mrp = mangleMethodName(rp);
  2063         sb.append(rfqn).append("$").append(rm).
  2064             append('$').append(mrp).append("__Ljava_lang_Object_2");
  2065         if (!isStatic) {
  2066             sb.append('L').append(fqnu).append("_2");
  2067         }
  2068         sb.append(srp);
  2069         return sb.toString();
  2070     }
  2071 
  2072     private static String className(ClassData jc) {
  2073         //return jc.getName().getInternalName().replace('/', '_');
  2074         return mangleClassName(jc.getClassName());
  2075     }
  2076     
  2077     private static String[] findAnnotation(
  2078         byte[] arr, ClassData cd, final String className, 
  2079         final String... attrNames
  2080     ) throws IOException {
  2081         if (arr == null) {
  2082             return null;
  2083         }
  2084         final String[] values = new String[attrNames.length];
  2085         final boolean[] found = { false };
  2086         final String jvmType = "L" + className.replace('.', '/') + ";";
  2087         AnnotationParser ap = new AnnotationParser(false, true) {
  2088             @Override
  2089             protected void visitAttr(String type, String attr, String at, String value) {
  2090                 if (type.equals(jvmType)) {
  2091                     found[0] = true;
  2092                     for (int i = 0; i < attrNames.length; i++) {
  2093                         if (attrNames[i].equals(attr)) {
  2094                             values[i] = value;
  2095                         }
  2096                     }
  2097                 }
  2098             }
  2099             
  2100         };
  2101         ap.parse(arr, cd);
  2102         return found[0] ? values : null;
  2103     }
  2104 
  2105     private CharSequence initField(FieldData v) {
  2106         final String is = v.getInternalSig();
  2107         if (is.length() == 1) {
  2108             switch (is.charAt(0)) {
  2109                 case 'S':
  2110                 case 'J':
  2111                 case 'B':
  2112                 case 'Z':
  2113                 case 'C':
  2114                 case 'I': return " = 0;";
  2115                 case 'F': 
  2116                 case 'D': return " = 0.0;";
  2117                 default:
  2118                     throw new IllegalStateException(is);
  2119             }
  2120         }
  2121         return " = null;";
  2122     }
  2123 
  2124     private void generateAnno(ClassData cd, byte[] data) throws IOException {
  2125         AnnotationParser ap = new AnnotationParser(true, false) {
  2126             int[] cnt = new int[32];
  2127             int depth;
  2128             
  2129             @Override
  2130             protected void visitAnnotationStart(String attrType, boolean top) throws IOException {
  2131                 final String slashType = attrType.substring(1, attrType.length() - 1);
  2132                 requireReference(slashType);
  2133                 
  2134                 if (cnt[depth]++ > 0) {
  2135                     append(",");
  2136                 }
  2137                 if (top) {
  2138                     append('"').append(attrType).append("\" : ");
  2139                 }
  2140                 append("{\n");
  2141                 cnt[++depth] = 0;
  2142             }
  2143 
  2144             @Override
  2145             protected void visitAnnotationEnd(String type, boolean top) throws IOException {
  2146                 append("\n}\n");
  2147                 depth--;
  2148             }
  2149 
  2150             @Override
  2151             protected void visitValueStart(String attrName, char type) throws IOException {
  2152                 if (cnt[depth]++ > 0) {
  2153                     append(",\n");
  2154                 }
  2155                 cnt[++depth] = 0;
  2156                 if (attrName != null) {
  2157                     append('"').append(attrName).append("\" : ");
  2158                 }
  2159                 if (type == '[') {
  2160                     append("[");
  2161                 }
  2162             }
  2163 
  2164             @Override
  2165             protected void visitValueEnd(String attrName, char type) throws IOException {
  2166                 if (type == '[') {
  2167                     append("]");
  2168                 }
  2169                 depth--;
  2170             }
  2171             
  2172             @Override
  2173             protected void visitAttr(String type, String attr, String attrType, String value) 
  2174             throws IOException {
  2175                 if (attr == null && value == null) {
  2176                     return;
  2177                 }
  2178                 append(value);
  2179             }
  2180 
  2181             @Override
  2182             protected void visitEnumAttr(String type, String attr, String attrType, String value) 
  2183             throws IOException {
  2184                 final String slashType = attrType.substring(1, attrType.length() - 1);
  2185                 requireReference(slashType);
  2186                 
  2187                 final String cn = mangleClassName(slashType);
  2188                 append(accessClassFalse(cn))
  2189                    .append("['valueOf__L").
  2190                     append(cn).
  2191                     append("_2Ljava_lang_String_2']('").
  2192                     append(value).
  2193                     append("')");
  2194             }
  2195         };
  2196         ap.parse(data, cd);
  2197     }
  2198 
  2199     private static String outputArg(Appendable out, String[] args, int indx) throws IOException {
  2200         final String name = args[indx];
  2201         if (name == null) {
  2202             return "";
  2203         }
  2204         if (name.contains(",")) {
  2205             throw new IOException("Wrong parameter with ',': " + name);
  2206         }
  2207         out.append(name);
  2208         return ",";
  2209     }
  2210 
  2211     final void emitNoFlush(
  2212         StackMapper sm, 
  2213         final String format, final CharSequence... params
  2214     ) throws IOException {
  2215         emitImpl(this, format, params);
  2216     }
  2217     static final void emit(
  2218         StackMapper sm, 
  2219         final Appendable out, 
  2220         final String format, final CharSequence... params
  2221     ) throws IOException {
  2222         sm.flush(out);
  2223         emitImpl(out, format, params);
  2224     }
  2225     static void emitImpl(final Appendable out,
  2226                              final String format,
  2227                              final CharSequence... params) throws IOException {
  2228         final int length = format.length();
  2229 
  2230         int processed = 0;
  2231         int paramOffset = format.indexOf('@');
  2232         while ((paramOffset != -1) && (paramOffset < (length - 1))) {
  2233             final char paramChar = format.charAt(paramOffset + 1);
  2234             if ((paramChar >= '1') && (paramChar <= '9')) {
  2235                 final int paramIndex = paramChar - '0' - 1;
  2236 
  2237                 out.append(format, processed, paramOffset);
  2238                 out.append(params[paramIndex]);
  2239 
  2240                 ++paramOffset;
  2241                 processed = paramOffset + 1;
  2242             }
  2243 
  2244             paramOffset = format.indexOf('@', paramOffset + 1);
  2245         }
  2246 
  2247         out.append(format, processed, length);
  2248     }
  2249 
  2250     private void generateCatch(TrapData[] traps, int current, int topMostLabel) throws IOException {
  2251         append("} catch (e) {\n");
  2252         int finallyPC = -1;
  2253         for (TrapData e : traps) {
  2254             if (e == null) {
  2255                 break;
  2256             }
  2257             if (e.catch_cpx != 0) { //not finally
  2258                 final String classInternalName = jc.getClassName(e.catch_cpx);
  2259                 addReference(classInternalName);
  2260                 append("e = vm.java_lang_Class(false).bck2BrwsrThrwrbl(e);");
  2261                 append("if (e['$instOf_" + classInternalName.replace('/', '_') + "']) {");
  2262                 append("var stA0 = e;");
  2263                 goTo(this, current, e.handler_pc, topMostLabel);
  2264                 append("}\n");
  2265             } else {
  2266                 finallyPC = e.handler_pc;
  2267             }
  2268         }
  2269         if (finallyPC == -1) {
  2270             append("throw e;");
  2271         } else {
  2272             append("var stA0 = e;");
  2273             goTo(this, current, finallyPC, topMostLabel);
  2274         }
  2275         append("\n}");
  2276     }
  2277 
  2278     private static void goTo(Appendable out, int current, int to, int canBack) throws IOException {
  2279         if (to < current) {
  2280             if (canBack < to) {
  2281                 out.append("{ gt = 0; continue X_" + to + "; }");
  2282             } else {
  2283                 out.append("{ gt = " + to + "; continue X_0; }");
  2284             }
  2285         } else {
  2286             out.append("{ gt = " + to + "; break IF; }");
  2287         }
  2288     }
  2289 
  2290     private static void emitIf(
  2291         StackMapper sm, 
  2292         Appendable out, String pattern, 
  2293         CharSequence param, 
  2294         int current, int to, int canBack
  2295     ) throws IOException {
  2296         sm.flush(out);
  2297         emitImpl(out, pattern, param);
  2298         goTo(out, current, to, canBack);
  2299     }
  2300 
  2301     private void generateNewArray(int atype, final StackMapper smapper) throws IOException, IllegalStateException {
  2302         String jvmType;
  2303         switch (atype) {
  2304             case 4: jvmType = "[Z"; break;
  2305             case 5: jvmType = "[C"; break;
  2306             case 6: jvmType = "[F"; break;
  2307             case 7: jvmType = "[D"; break;
  2308             case 8: jvmType = "[B"; break;
  2309             case 9: jvmType = "[S"; break;
  2310             case 10: jvmType = "[I"; break;
  2311             case 11: jvmType = "[J"; break;
  2312             default: throw new IllegalStateException("Array type: " + atype);
  2313         }
  2314         emit(smapper, this, 
  2315             "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](true, '@3', null, @1);",
  2316              smapper.popI(), smapper.pushA(), jvmType);
  2317     }
  2318 
  2319     private void generateANewArray(int type, final StackMapper smapper) throws IOException {
  2320         String typeName = jc.getClassName(type);
  2321         String ref = "null";
  2322         if (typeName.startsWith("[")) {
  2323             typeName = "'[" + typeName + "'";
  2324         } else {
  2325             ref = "vm." + mangleClassName(typeName);
  2326             typeName = "'[L" + typeName + ";'";
  2327         }
  2328         emit(smapper, this,
  2329             "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](false, @3, @4, @1);",
  2330              smapper.popI(), smapper.pushA(), typeName, ref);
  2331     }
  2332 
  2333     private int generateMultiANewArray(int type, final byte[] byteCodes, int i, final StackMapper smapper) throws IOException {
  2334         String typeName = jc.getClassName(type);
  2335         int dim = readUByte(byteCodes, ++i);
  2336         StringBuilder dims = new StringBuilder();
  2337         dims.append('[');
  2338         for (int d = 0; d < dim; d++) {
  2339             if (d != 0) {
  2340                 dims.insert(1, ",");
  2341             }
  2342             dims.insert(1, smapper.popI());
  2343         }
  2344         dims.append(']');
  2345         String fn = "null";
  2346         if (typeName.charAt(dim) == 'L') {
  2347             fn = "vm." + mangleClassName(typeName.substring(dim + 1, typeName.length() - 1));
  2348         }
  2349         emit(smapper, this, 
  2350             "var @2 = Array.prototype['multiNewArray__Ljava_lang_Object_2Ljava_lang_String_2_3ILjava_lang_Object_2']('@3', @1, @4);",
  2351              dims.toString(), smapper.pushA(), typeName, fn
  2352         );
  2353         return i;
  2354     }
  2355 
  2356     private int generateTableSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
  2357         int table = i / 4 * 4 + 4;
  2358         int dflt = i + readInt4(byteCodes, table);
  2359         table += 4;
  2360         int low = readInt4(byteCodes, table);
  2361         table += 4;
  2362         int high = readInt4(byteCodes, table);
  2363         table += 4;
  2364         final CharSequence swVar = smapper.popValue();
  2365         smapper.flush(this);
  2366         append("switch (").append(swVar).append(") {\n");
  2367         while (low <= high) {
  2368             int offset = i + readInt4(byteCodes, table);
  2369             table += 4;
  2370             append("  case " + low).append(":"); goTo(this, i, offset, topMostLabel); append('\n');
  2371             low++;
  2372         }
  2373         append("  default: ");
  2374         goTo(this, i, dflt, topMostLabel);
  2375         append("\n}");
  2376         i = table - 1;
  2377         return i;
  2378     }
  2379 
  2380     private int generateLookupSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
  2381         int table = i / 4 * 4 + 4;
  2382         int dflt = i + readInt4(byteCodes, table);
  2383         table += 4;
  2384         int n = readInt4(byteCodes, table);
  2385         table += 4;
  2386         final CharSequence swVar = smapper.popValue();
  2387         smapper.flush(this);
  2388         append("switch (").append(swVar).append(") {\n");
  2389         while (n-- > 0) {
  2390             int cnstnt = readInt4(byteCodes, table);
  2391             table += 4;
  2392             int offset = i + readInt4(byteCodes, table);
  2393             table += 4;
  2394             append("  case " + cnstnt).append(": "); goTo(this, i, offset, topMostLabel); append('\n');
  2395         }
  2396         append("  default: ");
  2397         goTo(this, i, dflt, topMostLabel);
  2398         append("\n}");
  2399         i = table - 1;
  2400         return i;
  2401     }
  2402 
  2403     private void generateInstanceOf(int indx, final StackMapper smapper) throws IOException {
  2404         String type = jc.getClassName(indx);
  2405         if (!type.startsWith("[")) {
  2406             emit(smapper, this, 
  2407                     "var @2 = @1 != null && @1['$instOf_@3'] ? 1 : 0;",
  2408                  smapper.popA(), smapper.pushI(),
  2409                  type.replace('/', '_'));
  2410         } else {
  2411             int cnt = 0;
  2412             while (type.charAt(cnt) == '[') {
  2413                 cnt++;
  2414             }
  2415             if (type.charAt(cnt) == 'L') {
  2416                 String component = type.substring(cnt + 1, type.length() - 1);
  2417                 requireReference(component);
  2418                 type = "vm." + mangleClassName(component);
  2419                 emit(smapper, this, 
  2420                     "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @4, @3);",
  2421                     smapper.popA(), smapper.pushI(),
  2422                     type, "" + cnt
  2423                 );
  2424             } else {
  2425                 emit(smapper, this, 
  2426                     "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@3');",
  2427                     smapper.popA(), smapper.pushI(), type
  2428                 );
  2429             }
  2430         }
  2431     }
  2432 
  2433     private void generateCheckcast(int indx, final StackMapper smapper) throws IOException {
  2434         String type = jc.getClassName(indx);
  2435         if (!type.startsWith("[")) {
  2436             emitNoFlush(smapper, 
  2437                  "if (@1 !== null && !@1['$instOf_@2']) vm.java_lang_Class(false).castEx();",
  2438                  smapper.getT(0, VarType.REFERENCE, false), type.replace('/', '_'));
  2439         } else {
  2440             int cnt = 0;
  2441             while (type.charAt(cnt) == '[') {
  2442                 cnt++;
  2443             }
  2444             if (type.charAt(cnt) == 'L') {
  2445                 String component = type.substring(cnt + 1, type.length() - 1);
  2446                 requireReference(component);
  2447                 type = "vm." + mangleClassName(component);
  2448                 emitNoFlush(smapper, 
  2449                     "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @3, @2)) vm.java_lang_Class(false).castEx();",
  2450                      smapper.getT(0, VarType.REFERENCE, false), type, "" + cnt
  2451                 );
  2452             } else {
  2453                 emitNoFlush(smapper, 
  2454                     "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@2')) vm.java_lang_Class(false).castEx();",
  2455                      smapper.getT(0, VarType.REFERENCE, false), type
  2456                 );
  2457             }
  2458         }
  2459     }
  2460 
  2461     private void generateByteCodeComment(int prev, int i, final byte[] byteCodes) throws IOException {
  2462         for (int j = prev; j <= i; j++) {
  2463             append(" ");
  2464             final int cc = readUByte(byteCodes, j);
  2465             append(Integer.toString(cc));
  2466         }
  2467     }
  2468     
  2469     @JavaScriptBody(args = "msg", body = "")
  2470     private static void println(String msg) {
  2471         System.err.println(msg);
  2472     }
  2473 }