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