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