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