rt/vm/src/main/java/org/apidesign/vm4brwsr/ByteCodeToJavaScript.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sun, 24 Jan 2016 17:00:17 +0100
branchFasterSieve
changeset 1951 3781fd782472
parent 1950 71e5cd5b29bc
permissions -rw-r--r--
Essential speedup when reading fields
     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 
    45     protected ByteCodeToJavaScript(Appendable out) {
    46         this.out = out;
    47     }
    48     
    49     @Override
    50     public final Appendable append(CharSequence csq) throws IOException {
    51         out.append(csq);
    52         outChanged = true;
    53         return this;
    54     }
    55 
    56     @Override
    57     public final Appendable append(CharSequence csq, int start, int end) throws IOException {
    58         out.append(csq, start, end);
    59         outChanged = true;
    60         return this;
    61     }
    62 
    63     @Override
    64     public final Appendable append(char c) throws IOException {
    65         out.append(c);
    66         outChanged = true;
    67         return this;
    68     }
    69     
    70     /* Collects additional required resources.
    71      * 
    72      * @param internalClassName classes that were referenced and should be loaded in order the
    73      *   generated JavaScript code works properly. The names are in internal 
    74      *   JVM form so String is <code>java/lang/String</code>. 
    75      */
    76     protected abstract boolean requireReference(String internalClassName);
    77     
    78     /*
    79      * @param resourcePath name of resources to read
    80      */
    81     protected abstract void requireScript(String resourcePath) throws IOException;
    82     
    83     protected abstract void requireResource(String resourcePath) throws IOException;
    84     
    85     /** Allows subclasses to redefine what field a function representing a
    86      * class gets assigned. By default it returns the suggested name followed
    87      * by <code>" = "</code>;
    88      * 
    89      * @param className suggested name of the class
    90      */
    91     /* protected */ String assignClass(String className) {
    92         return className + " = ";
    93     }
    94     /* protected */ String accessClass(String classOperation) {
    95         return classOperation;
    96     }
    97     
    98     final String accessClassFalse(String classOperation) {
    99         if (mangleClassName(jc.getClassName()).equals(classOperation)) {
   100             return "c";
   101         }
   102         classRefs.addIfMissing(classOperation);
   103         return "(refs_" + classOperation + " || (refs_" + classOperation + " = " + accessClass(classOperation) + "(false)))";
   104     }
   105 
   106     protected String accessField(String object, String mangledName,
   107                                  String[] fieldInfoName) throws IOException {
   108         return object + "." + mangledName;
   109     }
   110 
   111     protected String accessStaticMethod(
   112                              String object,
   113                              String mangledName,
   114                              String[] fieldInfoName) throws IOException {
   115         return object + "." + mangledName;
   116     }
   117 
   118     protected String accessVirtualMethod(
   119             String object, 
   120             String mangledName, 
   121             String[] fieldInfoName, 
   122             int params
   123     ) throws IOException {
   124         return object + "." + mangledName + '(';
   125     }
   126 
   127     protected void declaredClass(ClassData classData, String mangledName)
   128             throws IOException {
   129     }
   130 
   131     protected void declaredField(FieldData fieldData,
   132                                  String destObject,
   133                                  String mangledName) throws IOException {
   134     }
   135 
   136     protected void declaredMethod(MethodData methodData,
   137                                   String destObject,
   138                                   String mangledName) throws IOException {
   139     }
   140 
   141     /** Prints out a debug message. 
   142      * 
   143      * @param msg the message
   144      * @return true if the message has been printed
   145      * @throws IOException 
   146      */
   147     boolean debug(String msg) throws IOException {
   148         append(msg);
   149         return true;
   150     }
   151 
   152     /**
   153      * Converts a given class file to a JavaScript version.
   154      *
   155      * @param classFile input stream with code of the .class file
   156      * @return the initialization code for this class, if any. Otherwise <code>null</code>
   157      * 
   158      * @throws IOException if something goes wrong during read or write or translating
   159      */
   160     
   161     public String compile(InputStream classFile) throws IOException {
   162         return compile(new ClassData(classFile));
   163     }
   164 
   165     protected String compile(ClassData classData) throws IOException {
   166         this.jc = classData;
   167         final String cn = this.jc.getClassName();
   168         try {
   169             return compileImpl(cn);
   170         } catch (IOException ex) {
   171             throw new IOException("Cannot compile " + cn + ":", ex);
   172         }
   173     }
   174 
   175     private String compileImpl(final String cn) throws IOException {
   176         this.callbacks = cn.endsWith("/$JsCallbacks$");
   177         if (jc.getMajor_version() < 50 && !cn.endsWith("/package-info")) {
   178             throw new IOException("Can't compile " + cn + ". Class file version " + jc.getMajor_version() + "."
   179                 + jc.getMinor_version() + " - recompile with -target 1.6 (at least)."
   180             );
   181         }
   182         byte[] arrData = jc.findAnnotationData(true);
   183         {
   184             String[] arr = findAnnotation(arrData, jc,
   185                 "org.apidesign.bck2brwsr.core.ExtraJavaScript", 
   186                 "resource", "processByteCode"
   187             );
   188             if (arr != null) {
   189                 if (!arr[0].isEmpty()) {
   190                     requireScript(arr[0]);
   191                 }
   192                 if ("0".equals(arr[1])) {
   193                     return null;
   194                 }
   195             }
   196         }
   197         final String jsResource;
   198         {
   199             String[] arr = findAnnotation(arrData, jc,
   200                 "net.java.html.js.JavaScriptResource", 
   201                 "value"
   202             );
   203             if (arr != null) {
   204                 if (arr[0].startsWith("/")) {
   205                     jsResource = arr[0];
   206                 } else {
   207                     int last = cn.lastIndexOf('/');
   208                     jsResource = cn.substring(0, last + 1).replace('.', '/') + arr[0];
   209                 }
   210             } else {
   211                 jsResource = null;
   212             }
   213         }
   214         String[] proto = findAnnotation(arrData, jc,
   215             "org.apidesign.bck2brwsr.core.JavaScriptPrototype", 
   216             "container", "prototype"
   217         );
   218         StringArray toInitilize = new StringArray();
   219         final String className = className(jc);
   220         append("\n\n").append(assignClass(className));
   221         append("function ").append(className).append("() {");
   222         append("\n  var m;");
   223         append("\n  var CLS = ").append(className).append(';');
   224         append("\n  if (!CLS.$class) {");
   225         if (proto == null) {
   226             String sc = jc.getSuperClassName(); // with _
   227             append("\n    var pp = ").
   228                 append(accessClass(mangleClassName(sc))).append("(true);");
   229             append("\n    var p = CLS.prototype = pp;");
   230             append("\n    var c = p;");
   231             append("\n    var sprcls = pp.constructor.$class;");
   232         } else {
   233             append("\n    var p = CLS.prototype = ").append(proto[1]).append(";");
   234             if (proto[0] == null) {
   235                 proto[0] = "p";
   236             }
   237             append("\n    var c = ").append(proto[0]).append(";");
   238             append("\n    var sprcls = null;");
   239         }
   240         for (FieldData v : jc.getFields()) {
   241             if (v.isStatic()) {
   242                 if ((v.access & ACC_FINAL) != 0 && v.hasConstantValue()) {
   243                     if (v.getInternalSig().length() == 1 || v.getInternalSig().equals("Ljava/lang/String;")) {
   244                         continue;
   245                     }
   246                 }
   247                 append("\n  CLS.fld_").append(v.getName()).append(initField(v));
   248                 append("\n  m = c._").append(v.getName()).append(" = function (v) {")
   249                     .append("  if (arguments.length == 1) CLS.fld_").append(v.getName())
   250                     .append(" = v; return CLS.fld_").
   251                     append(v.getName()).append("; };");
   252             } else {
   253                 append("\n  m = c._").append(v.getName()).append(" = function (v) {")
   254                     .append("  if (arguments.length == 1) this.fld_").
   255                     append(className).append('_').append(v.getName())
   256                     .append(" = v; return this.fld_").
   257                     append(className).append('_').append(v.getName())
   258                     .append("; };");
   259             }
   260 
   261             declaredField(v, "c", "_" + v.getName());
   262         }
   263         for (MethodData m : jc.getMethods()) {
   264             byte[] onlyArr = m.findAnnotationData(true);
   265             if (javaScriptOnly(onlyArr)) continue;
   266             String destObject;
   267             String mn;
   268             append("\n    ");
   269             if (m.isStatic()) {
   270                 destObject = "c";
   271                 mn = generateStaticMethod(destObject, m, toInitilize);
   272             } else {
   273                 if (m.isConstructor()) {
   274                     destObject = "CLS";
   275                     mn = generateInstanceMethod(destObject, m);
   276                 } else {
   277                     destObject = "c";
   278                     mn = generateInstanceMethod(destObject, m);
   279                 }
   280             }
   281             declaredMethod(m, destObject, mn);
   282             byte[] runAnno = m.findAnnotationData(false);
   283             if (runAnno != null) {
   284                 append("\n    m.anno = {");
   285                 generateAnno(jc, runAnno);
   286                 append("\n    };");
   287             }
   288             append("\n    m.access = " + m.getAccess()).append(";");
   289             append("\n    m.cls = CLS;");
   290         }
   291         append("\n    c.constructor = CLS;");
   292         append("\n    function ").append(className).append("fillInstOf(x) {");
   293         String instOfName = "$instOf_" + className;
   294         append("\n        Object.defineProperty(x, '").append(instOfName).append("', { value : true });");
   295         if (jc.isInterface()) {
   296             for (MethodData m : jc.getMethods()) {
   297                 if ((m.getAccess() & ACC_ABSTRACT) == 0
   298                     && (m.getAccess() & ACC_STATIC) == 0
   299                     && (m.getAccess() & ACC_PRIVATE) == 0) {
   300                     final String mn = findMethodName(m, new StringBuilder());
   301                     append("\n        if (!x['").append(mn).append("']) Object.defineProperty(x, '").append(mn).append("', { value : c['").append(mn).append("']});");
   302                 }
   303             }
   304         }
   305         for (String superInterface : jc.getSuperInterfaces()) {
   306             String intrfc = mangleClassName(superInterface);
   307             append("\n      vm.").append(intrfc).append("(false)['fillInstOf'](x);");
   308             requireReference(superInterface);
   309         }
   310         append("\n    }");
   311         append("\n    if (!c.hasOwnProperty('fillInstOf')) Object.defineProperty(c, 'fillInstOf', { value: ").append(className).append("fillInstOf });");
   312         append("\n    ").append(className).append("fillInstOf(c);");
   313 //        obfuscationDelegate.exportJSProperty(this, "c", instOfName);
   314         append("\n    CLS.$class = 'temp';");
   315         append("\n    CLS.$class = ");
   316         append(accessClass("java_lang_Class(true);"));
   317         append("\n    CLS.$class.jvmName = '").append(cn).append("';");
   318         append("\n    CLS.$class.superclass = sprcls;");
   319         append("\n    CLS.$class.interfaces = function() { return [");
   320         {
   321             boolean first = true;
   322             for (String intrfc : jc.getSuperInterfaces()) {
   323                 if (!first) {
   324                     append(",");
   325                 }
   326                 requireReference(intrfc);
   327                 String mangledIface = mangleClassName(intrfc);
   328                 append("\n        ");
   329                 append(accessClass(mangledIface)).append("(false).constructor.$class");
   330                 first = false;
   331             }
   332         }
   333         append("\n    ]; };");
   334         append("\n    CLS.$class.access = ").append(jc.getAccessFlags()+";");
   335         append("\n    CLS.$class.cnstr = CLS;");
   336         byte[] classAnno = jc.findAnnotationData(false);
   337         if (classAnno != null) {
   338             append("\n    CLS.$class.anno = {");
   339             generateAnno(jc, classAnno);
   340             append("\n    };");
   341         }
   342         for (String init : toInitilize.toArray()) {
   343             append("\n    ").append(init).append("();");
   344         }
   345         for (String ref : classRefs.toArray()) {
   346             append("\n    var refs_").append(ref).append(";");
   347         }
   348         classRefs.clear();
   349         
   350         if (jsResource != null) {
   351             requireResource(jsResource);
   352         }
   353         
   354         append("\n  }");
   355         append("\n  if (arguments.length === 0) {");
   356         append("\n    if (!(this instanceof CLS)) {");
   357         append("\n      return new CLS();");
   358         append("\n    }");
   359         for (FieldData v : jc.getFields()) {
   360             byte[] onlyArr = v.findAnnotationData(true);
   361             if (javaScriptOnly(onlyArr)) continue;
   362             if (!v.isStatic()) {
   363                 append("\n    this.fld_").
   364                     append(className).append('_').
   365                     append(v.getName()).append(initField(v));
   366             }
   367         }
   368         append("\n    return this;");
   369         append("\n  }");
   370         append("\n  return arguments[0] ? new CLS() : CLS.prototype;");
   371         append("\n};");
   372 
   373         declaredClass(jc, className);
   374 
   375 //        StringBuilder sb = new StringBuilder();
   376 //        for (String init : toInitilize.toArray()) {
   377 //            sb.append("\n").append(init).append("();");
   378 //        }
   379         return "";
   380     }
   381 
   382     private boolean javaScriptOnly(byte[] anno) throws IOException {
   383         String[] only = findAnnotation(anno, jc,
   384             "org.apidesign.bck2brwsr.core.JavaScriptOnly",
   385             "name", "value"
   386         );
   387         if (only != null) {
   388             if (only[0] != null && only[1] != null) {
   389                 append("\n    p.").append(only[0]).append(" = ")
   390                     .append(only[1]).append(";");
   391             }
   392             if (ExportedSymbols.isMarkedAsExported(anno, jc)) {
   393                 append("\n    p['").append(only[0]).append("'] = p.")
   394                     .append(only[0]).append(";");
   395             }
   396             return true;
   397         }
   398         return false;
   399     }
   400     private String generateStaticMethod(String destObject, MethodData m, StringArray toInitilize) throws IOException {
   401         String jsb = javaScriptBody(destObject, m, true);
   402         if (jsb != null) {
   403             return jsb;
   404         }
   405         final String mn = findMethodName(m, new StringBuilder());
   406         boolean defineProp = generateMethod(destObject, mn, m);
   407         if (mn.equals("class__V")) {
   408             if (defineProp) {
   409                 toInitilize.add(accessClassFalse(className(jc)) + "['" + mn + "']");
   410             } else {
   411                 toInitilize.add(accessClassFalse(className(jc)) + "." + mn);
   412             }
   413         }
   414         return mn;
   415     }
   416 
   417     private String generateInstanceMethod(String destObject, MethodData m) throws IOException {
   418         String jsb = javaScriptBody(destObject, m, false);
   419         if (jsb != null) {
   420             return jsb;
   421         }
   422         final String mn = findMethodName(m, new StringBuilder());
   423         generateMethod(destObject, mn, m);
   424         return mn;
   425     }
   426 
   427     private boolean generateMethod(String destObject, String name, MethodData m)
   428             throws IOException {
   429         final StackMapIterator stackMapIterator = m.createStackMapIterator();
   430         TrapDataIterator trap = m.getTrapDataIterator();
   431         final LocalsMapper lmapper =
   432                 new LocalsMapper(stackMapIterator.getArguments());
   433 
   434         boolean defineProp = 
   435             "java/lang/Object".equals(jc.getClassName()) ||
   436             "java/lang/reflect/Array".equals(jc.getClassName());
   437         
   438         if (defineProp) {
   439             append("Object.defineProperty(").append(destObject).
   440             append(", '").append(name).append("', { configurable: true, writable: true, value: m = function(");
   441         } else {
   442             append("m = ").append(destObject).append(".").append(name).append(" = function(");
   443         }
   444         lmapper.outputArguments(this, m.isStatic());
   445         append(") {").append("\n");
   446 
   447         final byte[] byteCodes = m.getCode();
   448         if (byteCodes == null) {
   449             if (debug("  throw 'no code found for ")) {
   450                this
   451                .append(jc.getClassName()).append('.')
   452                .append(m.getName()).append("';\n");
   453             }
   454             if (defineProp) {
   455                 append("}});");
   456             } else {
   457                 append("};");
   458             }
   459             return defineProp;
   460         }
   461 
   462         final StackMapper smapper = new StackMapper();
   463 
   464         if (!m.isStatic()) {
   465             append("  var ").append(" lcA0 = this;\n");
   466         }
   467 
   468         int lastStackFrame;
   469         TrapData[] previousTrap = null;
   470         boolean wide = false;
   471         boolean didBranches;
   472         if (stackMapIterator.isEmpty()) {
   473             didBranches = false;
   474             lastStackFrame = 0;
   475         } else {
   476             didBranches = true;
   477             lastStackFrame = -1;
   478             append("\n  var gt = 0;\n");
   479         }
   480         
   481         int openBraces = 0;
   482         int topMostLabel = 0;
   483         for (int i = 0; i < byteCodes.length; i++) {
   484             int prev = i;
   485             outChanged = false;
   486             stackMapIterator.advanceTo(i);
   487             boolean changeInCatch = trap.advanceTo(i);
   488             if (changeInCatch || lastStackFrame != stackMapIterator.getFrameIndex()) {
   489                 if (previousTrap != null) {
   490                     generateCatch(previousTrap, i, topMostLabel);
   491                     previousTrap = null;
   492                 }
   493             }
   494             if (lastStackFrame != stackMapIterator.getFrameIndex()) {
   495                 smapper.flush(this);
   496                 if (i != 0) {
   497                     append("    }\n");
   498                 }
   499                 if (openBraces > 64) {
   500                     for (int c = 0; c < 64; c++) {
   501                         append("break;}\n");
   502                     }
   503                     openBraces = 1;
   504                     topMostLabel = i;
   505                 }
   506                 
   507                 lastStackFrame = stackMapIterator.getFrameIndex();
   508                 lmapper.syncWithFrameLocals(stackMapIterator.getFrameLocals());
   509                 smapper.syncWithFrameStack(stackMapIterator.getFrameStack());
   510                 append("    X_" + i).append(": for (;;) { IF: if (gt <= " + i + ") {\n");
   511                 openBraces++;
   512                 changeInCatch = true;
   513             } else {
   514                 debug("    /* " + i + " */ ");
   515             }
   516             if (changeInCatch && trap.useTry()) {
   517                 append("try {");
   518                 previousTrap = trap.current();
   519             }
   520             final int c = readUByte(byteCodes, i);
   521             switch (c) {
   522                 case opc_aload_0:
   523                     smapper.assign(this, VarType.REFERENCE, lmapper.getA(0));
   524                     break;
   525                 case opc_iload_0:
   526                     smapper.assign(this, VarType.INTEGER, lmapper.getI(0));
   527                     break;
   528                 case opc_lload_0:
   529                     smapper.assign(this, VarType.LONG, lmapper.getL(0));
   530                     break;
   531                 case opc_fload_0:
   532                     smapper.assign(this, VarType.FLOAT, lmapper.getF(0));
   533                     break;
   534                 case opc_dload_0:
   535                     smapper.assign(this, VarType.DOUBLE, lmapper.getD(0));
   536                     break;
   537                 case opc_aload_1:
   538                     smapper.assign(this, VarType.REFERENCE, lmapper.getA(1));
   539                     break;
   540                 case opc_iload_1:
   541                     smapper.assign(this, VarType.INTEGER, lmapper.getI(1));
   542                     break;
   543                 case opc_lload_1:
   544                     smapper.assign(this, VarType.LONG, lmapper.getL(1));
   545                     break;
   546                 case opc_fload_1:
   547                     smapper.assign(this, VarType.FLOAT, lmapper.getF(1));
   548                     break;
   549                 case opc_dload_1:
   550                     smapper.assign(this, VarType.DOUBLE, lmapper.getD(1));
   551                     break;
   552                 case opc_aload_2:
   553                     smapper.assign(this, VarType.REFERENCE, lmapper.getA(2));
   554                     break;
   555                 case opc_iload_2:
   556                     smapper.assign(this, VarType.INTEGER, lmapper.getI(2));
   557                     break;
   558                 case opc_lload_2:
   559                     smapper.assign(this, VarType.LONG, lmapper.getL(2));
   560                     break;
   561                 case opc_fload_2:
   562                     smapper.assign(this, VarType.FLOAT, lmapper.getF(2));
   563                     break;
   564                 case opc_dload_2:
   565                     smapper.assign(this, VarType.DOUBLE, lmapper.getD(2));
   566                     break;
   567                 case opc_aload_3:
   568                     smapper.assign(this, VarType.REFERENCE, lmapper.getA(3));
   569                     break;
   570                 case opc_iload_3:
   571                     smapper.assign(this, VarType.INTEGER, lmapper.getI(3));
   572                     break;
   573                 case opc_lload_3:
   574                     smapper.assign(this, VarType.LONG, lmapper.getL(3));
   575                     break;
   576                 case opc_fload_3:
   577                     smapper.assign(this, VarType.FLOAT, lmapper.getF(3));
   578                     break;
   579                 case opc_dload_3:
   580                     smapper.assign(this, VarType.DOUBLE, lmapper.getD(3));
   581                     break;
   582                 case opc_iload: {
   583                     ++i;
   584                     final int indx = wide ? readUShort(byteCodes, i++)
   585                                           : readUByte(byteCodes, i);
   586                     wide = false;
   587                     smapper.assign(this, VarType.INTEGER, lmapper.getI(indx));
   588                     break;
   589                 }
   590                 case opc_lload: {
   591                     ++i;
   592                     final int indx = wide ? readUShort(byteCodes, i++)
   593                                           : readUByte(byteCodes, i);
   594                     wide = false;
   595                     smapper.assign(this, VarType.LONG, lmapper.getL(indx));
   596                     break;
   597                 }
   598                 case opc_fload: {
   599                     ++i;
   600                     final int indx = wide ? readUShort(byteCodes, i++)
   601                                           : readUByte(byteCodes, i);
   602                     wide = false;
   603                     smapper.assign(this, VarType.FLOAT, lmapper.getF(indx));
   604                     break;
   605                 }
   606                 case opc_dload: {
   607                     ++i;
   608                     final int indx = wide ? readUShort(byteCodes, i++)
   609                                           : readUByte(byteCodes, i);
   610                     wide = false;
   611                     smapper.assign(this, VarType.DOUBLE, lmapper.getD(indx));
   612                     break;
   613                 }
   614                 case opc_aload: {
   615                     ++i;
   616                     final int indx = wide ? readUShort(byteCodes, i++)
   617                                           : readUByte(byteCodes, i);
   618                     wide = false;
   619                     smapper.assign(this, VarType.REFERENCE, lmapper.getA(indx));
   620                     break;
   621                 }
   622                 case opc_istore: {
   623                     ++i;
   624                     final int indx = wide ? readUShort(byteCodes, i++)
   625                                           : readUByte(byteCodes, i);
   626                     wide = false;
   627                     emit(smapper, this, "var @1 = @2;",
   628                          lmapper.setI(indx), smapper.popI());
   629                     break;
   630                 }
   631                 case opc_lstore: {
   632                     ++i;
   633                     final int indx = wide ? readUShort(byteCodes, i++)
   634                                           : readUByte(byteCodes, i);
   635                     wide = false;
   636                     emit(smapper, this, "var @1 = @2;",
   637                          lmapper.setL(indx), smapper.popL());
   638                     break;
   639                 }
   640                 case opc_fstore: {
   641                     ++i;
   642                     final int indx = wide ? readUShort(byteCodes, i++)
   643                                           : readUByte(byteCodes, i);
   644                     wide = false;
   645                     emit(smapper, this, "var @1 = @2;",
   646                          lmapper.setF(indx), smapper.popF());
   647                     break;
   648                 }
   649                 case opc_dstore: {
   650                     ++i;
   651                     final int indx = wide ? readUShort(byteCodes, i++)
   652                                           : readUByte(byteCodes, i);
   653                     wide = false;
   654                     emit(smapper, this, "var @1 = @2;",
   655                          lmapper.setD(indx), smapper.popD());
   656                     break;
   657                 }
   658                 case opc_astore: {
   659                     ++i;
   660                     final int indx = wide ? readUShort(byteCodes, i++)
   661                                           : readUByte(byteCodes, i);
   662                     wide = false;
   663                     emit(smapper, this, "var @1 = @2;",
   664                          lmapper.setA(indx), smapper.popA());
   665                     break;
   666                 }
   667                 case opc_astore_0:
   668                     emit(smapper, this, "var @1 = @2;", lmapper.setA(0), smapper.popA());
   669                     break;
   670                 case opc_istore_0:
   671                     emit(smapper, this, "var @1 = @2;", lmapper.setI(0), smapper.popI());
   672                     break;
   673                 case opc_lstore_0:
   674                     emit(smapper, this, "var @1 = @2;", lmapper.setL(0), smapper.popL());
   675                     break;
   676                 case opc_fstore_0:
   677                     emit(smapper, this, "var @1 = @2;", lmapper.setF(0), smapper.popF());
   678                     break;
   679                 case opc_dstore_0:
   680                     emit(smapper, this, "var @1 = @2;", lmapper.setD(0), smapper.popD());
   681                     break;
   682                 case opc_astore_1:
   683                     emit(smapper, this, "var @1 = @2;", lmapper.setA(1), smapper.popA());
   684                     break;
   685                 case opc_istore_1:
   686                     emit(smapper, this, "var @1 = @2;", lmapper.setI(1), smapper.popI());
   687                     break;
   688                 case opc_lstore_1:
   689                     emit(smapper, this, "var @1 = @2;", lmapper.setL(1), smapper.popL());
   690                     break;
   691                 case opc_fstore_1:
   692                     emit(smapper, this, "var @1 = @2;", lmapper.setF(1), smapper.popF());
   693                     break;
   694                 case opc_dstore_1:
   695                     emit(smapper, this, "var @1 = @2;", lmapper.setD(1), smapper.popD());
   696                     break;
   697                 case opc_astore_2:
   698                     emit(smapper, this, "var @1 = @2;", lmapper.setA(2), smapper.popA());
   699                     break;
   700                 case opc_istore_2:
   701                     emit(smapper, this, "var @1 = @2;", lmapper.setI(2), smapper.popI());
   702                     break;
   703                 case opc_lstore_2:
   704                     emit(smapper, this, "var @1 = @2;", lmapper.setL(2), smapper.popL());
   705                     break;
   706                 case opc_fstore_2:
   707                     emit(smapper, this, "var @1 = @2;", lmapper.setF(2), smapper.popF());
   708                     break;
   709                 case opc_dstore_2:
   710                     emit(smapper, this, "var @1 = @2;", lmapper.setD(2), smapper.popD());
   711                     break;
   712                 case opc_astore_3:
   713                     emit(smapper, this, "var @1 = @2;", lmapper.setA(3), smapper.popA());
   714                     break;
   715                 case opc_istore_3:
   716                     emit(smapper, this, "var @1 = @2;", lmapper.setI(3), smapper.popI());
   717                     break;
   718                 case opc_lstore_3:
   719                     emit(smapper, this, "var @1 = @2;", lmapper.setL(3), smapper.popL());
   720                     break;
   721                 case opc_fstore_3:
   722                     emit(smapper, this, "var @1 = @2;", lmapper.setF(3), smapper.popF());
   723                     break;
   724                 case opc_dstore_3:
   725                     emit(smapper, this, "var @1 = @2;", lmapper.setD(3), smapper.popD());
   726                     break;
   727                 case opc_iadd:
   728                     smapper.replace(this, VarType.INTEGER, "(@1).add32(@2)", smapper.getI(1), smapper.popI());
   729                     break;
   730                 case opc_ladd:
   731                     smapper.replace(this, VarType.LONG, "(@1).add64(@2)", smapper.getL(1), smapper.popL());
   732                     break;
   733                 case opc_fadd:
   734                     smapper.replace(this, VarType.FLOAT, "(@1 + @2)", smapper.getF(1), smapper.popF());
   735                     break;
   736                 case opc_dadd:
   737                     smapper.replace(this, VarType.DOUBLE, "(@1 + @2)", smapper.getD(1), smapper.popD());
   738                     break;
   739                 case opc_isub:
   740                     smapper.replace(this, VarType.INTEGER, "(@1).sub32(@2)", smapper.getI(1), smapper.popI());
   741                     break;
   742                 case opc_lsub:
   743                     smapper.replace(this, VarType.LONG, "(@1).sub64(@2)", smapper.getL(1), smapper.popL());
   744                     break;
   745                 case opc_fsub:
   746                     smapper.replace(this, VarType.FLOAT, "(@1 - @2)", smapper.getF(1), smapper.popF());
   747                     break;
   748                 case opc_dsub:
   749                     smapper.replace(this, VarType.DOUBLE, "(@1 - @2)", smapper.getD(1), smapper.popD());
   750                     break;
   751                 case opc_imul:
   752                     smapper.replace(this, VarType.INTEGER, "(@1).mul32(@2)", smapper.getI(1), smapper.popI());
   753                     break;
   754                 case opc_lmul:
   755                     smapper.replace(this, VarType.LONG, "(@1).mul64(@2)", smapper.getL(1), smapper.popL());
   756                     break;
   757                 case opc_fmul:
   758                     smapper.replace(this, VarType.FLOAT, "(@1 * @2)", smapper.getF(1), smapper.popF());
   759                     break;
   760                 case opc_dmul:
   761                     smapper.replace(this, VarType.DOUBLE, "(@1 * @2)", smapper.getD(1), smapper.popD());
   762                     break;
   763                 case opc_idiv:
   764                     smapper.replace(this, VarType.INTEGER, "(@1).div32(@2)",
   765                          smapper.getI(1), smapper.popI());
   766                     break;
   767                 case opc_ldiv:
   768                     smapper.replace(this, VarType.LONG, "(@1).div64(@2)",
   769                          smapper.getL(1), smapper.popL());
   770                     break;
   771                 case opc_fdiv:
   772                     smapper.replace(this, VarType.FLOAT, "(@1 / @2)", smapper.getF(1), smapper.popF());
   773                     break;
   774                 case opc_ddiv:
   775                     smapper.replace(this, VarType.DOUBLE, "(@1 / @2)", smapper.getD(1), smapper.popD());
   776                     break;
   777                 case opc_irem:
   778 //
   779 // direct check yields few percents
   780 // in case of firefox 5.8s/4.6.s
   781                     smapper.replace(this, VarType.INTEGER, "((@1) % (@2))",
   782                          smapper.getI(1), smapper.popI());
   783 // with myNum being local variable in the generated script
   784 // it compiles and computes 5000 primes in 6s
   785 //                    smapper.replace(this, VarType.INTEGER, "myNum.mod32(@1, @2)",
   786 //                         smapper.getI(1), smapper.popI());
   787                     break;
   788                 case opc_lrem:
   789                     smapper.replace(this, VarType.LONG, "(@1).mod64(@2)",
   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, "(@1).and64(@2)", 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, "(@1).or64(@2)", 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, "(@1).xor64(@2)", smapper.getL(1), smapper.popL());
   815                     break;
   816                 case opc_ineg:
   817                     smapper.replace(this, VarType.INTEGER, "(@1).neg32()", smapper.getI(0));
   818                     break;
   819                 case opc_lneg:
   820                     smapper.replace(this, VarType.LONG, "(@1).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, "(@1).shl64(@2)", 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, "(@1).shr64(@2)", 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, "(@1).ushr64(@2)", 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).toInt32()", 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).toInt32()",
   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).toInt32()",
   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).toInt8()", smapper.getI(0));
   925                     break;
   926                 case opc_i2c:
   927                 case opc_i2s:
   928                     smapper.replace(this, VarType.INTEGER, "(@1).toInt16()", 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, "(@2).compare64(@1)", 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                     final String mangleClass = mangleClassName(fi[0]);
  1429                     final String mangleClassAccess = accessClassFalse(mangleClass);
  1430                     emit(smapper, this, "var @2 = @1.fld_@4_@3 || @5.call(@1);",
  1431                          smapper.popA(), smapper.pushT(type), fi[1], mangleClass,
  1432                          accessField(mangleClassAccess, "_" + fi[1], fi)
  1433                     );
  1434                     i += 2;
  1435                     addReference(fi[0]);
  1436                     break;
  1437                 }
  1438                 case opc_putfield: {
  1439                     int indx = readUShortArg(byteCodes, i);
  1440                     String[] fi = jc.getFieldInfoName(indx);
  1441                     final int type = VarType.fromFieldType(fi[2].charAt(0));
  1442                     final String mangleClass = mangleClassName(fi[0]);
  1443                     final String mangleClassAccess = accessClassFalse(mangleClass);
  1444                     emit(smapper, this, "@3.call(@2, @1);",
  1445                          smapper.popT(type),
  1446                          smapper.popA(),
  1447                          accessField(mangleClassAccess,
  1448                                      "_" + fi[1], fi));
  1449                     i += 2;
  1450                     addReference(fi[0]);
  1451                     break;
  1452                 }
  1453                 case opc_getstatic: {
  1454                     int indx = readUShortArg(byteCodes, i);
  1455                     String[] fi = jc.getFieldInfoName(indx);
  1456                     final int type = VarType.fromFieldType(fi[2].charAt(0));
  1457                     String ac = accessClassFalse(mangleClassName(fi[0]));
  1458                     String af = accessField(ac, "_" + fi[1], fi);
  1459                     smapper.assign(this, type, af + "()");
  1460                     i += 2;
  1461                     addReference(fi[0]);
  1462                     break;
  1463                 }
  1464                 case opc_putstatic: {
  1465                     int indx = readUShortArg(byteCodes, i);
  1466                     String[] fi = jc.getFieldInfoName(indx);
  1467                     final int type = VarType.fromFieldType(fi[2].charAt(0));
  1468                     emit(smapper, this, "@1._@2(@3);",
  1469                          accessClassFalse(mangleClassName(fi[0])), fi[1],
  1470                          smapper.popT(type));
  1471                     i += 2;
  1472                     addReference(fi[0]);
  1473                     break;
  1474                 }
  1475                 case opc_checkcast: {
  1476                     int indx = readUShortArg(byteCodes, i);
  1477                     generateCheckcast(indx, smapper);
  1478                     i += 2;
  1479                     break;
  1480                 }
  1481                 case opc_instanceof: {
  1482                     int indx = readUShortArg(byteCodes, i);
  1483                     generateInstanceOf(indx, smapper);
  1484                     i += 2;
  1485                     break;
  1486                 }
  1487                 case opc_athrow: {
  1488                     final CharSequence v = smapper.popA();
  1489                     smapper.clear();
  1490 
  1491                     emit(smapper, this, "{ var @1 = @2; throw @2; }",
  1492                          smapper.pushA(), v);
  1493                     break;
  1494                 }
  1495 
  1496                 case opc_monitorenter: {
  1497                     debug("/* monitor enter */");
  1498                     smapper.popA();
  1499                     break;
  1500                 }
  1501 
  1502                 case opc_monitorexit: {
  1503                     debug("/* monitor exit */");
  1504                     smapper.popA();
  1505                     break;
  1506                 }
  1507 
  1508                 case opc_wide:
  1509                     wide = true;
  1510                     break;
  1511 
  1512                 default: {
  1513                     wide = false;
  1514                     emit(smapper, this, "throw 'unknown bytecode @1';",
  1515                          Integer.toString(c));
  1516                 }
  1517             }
  1518             if (debug(" //")) {
  1519                 generateByteCodeComment(prev, i, byteCodes);
  1520             }
  1521             if (outChanged) {
  1522                 append("\n");
  1523             }
  1524         }
  1525         if (previousTrap != null) {
  1526             generateCatch(previousTrap, byteCodes.length, topMostLabel);
  1527         }
  1528         if (didBranches) {
  1529             append("\n    }\n");
  1530         }
  1531         while (openBraces-- > 0) {
  1532             append('}');
  1533         }
  1534         if (defineProp) {
  1535             append("\n}});");
  1536         } else {
  1537             append("\n};");
  1538         }
  1539         return defineProp;
  1540     }
  1541 
  1542     private int generateIf(StackMapper mapper, byte[] byteCodes, 
  1543         int i, final CharSequence v2, final CharSequence v1, 
  1544         final String test, int topMostLabel
  1545     ) throws IOException {
  1546         mapper.flush(this);
  1547         int indx = i + readShortArg(byteCodes, i);
  1548         append("if ((").append(v1)
  1549            .append(") ").append(test).append(" (")
  1550            .append(v2).append(")) ");
  1551         goTo(this, i, indx, topMostLabel);
  1552         return i + 2;
  1553     }
  1554     
  1555     private int readInt4(byte[] byteCodes, int offset) {
  1556         final int d = byteCodes[offset + 0] << 24;
  1557         final int c = byteCodes[offset + 1] << 16;
  1558         final int b = byteCodes[offset + 2] << 8;
  1559         final int a = byteCodes[offset + 3];
  1560         return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
  1561     }
  1562     private static int readUByte(byte[] byteCodes, int offset) {
  1563         return byteCodes[offset] & 0xff;
  1564     }
  1565 
  1566     private static int readUShort(byte[] byteCodes, int offset) {
  1567         return ((byteCodes[offset] & 0xff) << 8)
  1568                     | (byteCodes[offset + 1] & 0xff);
  1569     }
  1570     private static int readUShortArg(byte[] byteCodes, int offsetInstruction) {
  1571         return readUShort(byteCodes, offsetInstruction + 1);
  1572     }
  1573 
  1574     private static int readShort(byte[] byteCodes, int offset) {
  1575         int signed = byteCodes[offset];
  1576         byte b0 = (byte)signed;
  1577         return (b0 << 8) | (byteCodes[offset + 1] & 0xff);
  1578     }
  1579     private static int readShortArg(byte[] byteCodes, int offsetInstruction) {
  1580         return readShort(byteCodes, offsetInstruction + 1);
  1581     }
  1582 
  1583     private static void countArgs(String descriptor, char[] returnType, StringBuilder sig, StringBuilder cnt) {
  1584         int i = 0;
  1585         Boolean count = null;
  1586         boolean array = false;
  1587         sig.append("__");
  1588         int firstPos = sig.length();
  1589         while (i < descriptor.length()) {
  1590             char ch = descriptor.charAt(i++);
  1591             switch (ch) {
  1592                 case '(':
  1593                     count = true;
  1594                     continue;
  1595                 case ')':
  1596                     count = false;
  1597                     continue;
  1598                 case 'B': 
  1599                 case 'C': 
  1600                 case 'D': 
  1601                 case 'F': 
  1602                 case 'I': 
  1603                 case 'J': 
  1604                 case 'S': 
  1605                 case 'Z': 
  1606                     if (count) {
  1607                         if (array) {
  1608                             sig.append("_3");
  1609                         }
  1610                         sig.append(ch);
  1611                         if (ch == 'J' || ch == 'D') {
  1612                             cnt.append('1');
  1613                         } else {
  1614                             cnt.append('0');
  1615                         }
  1616                     } else {
  1617                         sig.insert(firstPos, ch);
  1618                         if (array) {
  1619                             returnType[0] = '[';
  1620                             sig.insert(firstPos, "_3");
  1621                         } else {
  1622                             returnType[0] = ch;
  1623                         }
  1624                     }
  1625                     array = false;
  1626                     continue;
  1627                 case 'V': 
  1628                     assert !count;
  1629                     returnType[0] = 'V';
  1630                     sig.insert(firstPos, 'V');
  1631                     continue;
  1632                 case 'L':
  1633                     int next = descriptor.indexOf(';', i);
  1634                     String realSig = mangleSig(descriptor, i - 1, next + 1);
  1635                     if (count) {
  1636                         if (array) {
  1637                             sig.append("_3");
  1638                         }
  1639                         sig.append(realSig);
  1640                         cnt.append('0');
  1641                     } else {
  1642                         sig.insert(firstPos, realSig);
  1643                         if (array) {
  1644                             sig.insert(firstPos, "_3");
  1645                         }
  1646                         returnType[0] = 'L';
  1647                     }
  1648                     i = next + 1;
  1649                     array = false;
  1650                     continue;
  1651                 case '[':
  1652                     array = true;
  1653                     continue;
  1654                 default:
  1655                     throw new IllegalStateException("Invalid char: " + ch);
  1656             }
  1657         }
  1658     }
  1659     
  1660     static String mangleSig(String sig) {
  1661         return mangleSig(sig, 0, sig.length());
  1662     }
  1663     
  1664     private static String mangleMethodName(String name) {
  1665         StringBuilder sb = new StringBuilder(name.length() * 2);
  1666         int last = name.length();
  1667         for (int i = 0; i < last; i++) {
  1668             final char ch = name.charAt(i);
  1669             switch (ch) {
  1670                 case '_': sb.append("_1"); break;
  1671                 default: sb.append(ch); break;
  1672             }
  1673         }
  1674         return sb.toString();
  1675     }
  1676     private static String mangleSig(String txt, int first, int last) {
  1677         StringBuilder sb = new StringBuilder((last - first) * 2);
  1678         for (int i = first; i < last; i++) {
  1679             final char ch = txt.charAt(i);
  1680             switch (ch) {
  1681                 case '/': sb.append('_'); break;
  1682                 case '_': sb.append("_1"); break;
  1683                 case ';': sb.append("_2"); break;
  1684                 case '[': sb.append("_3"); break;
  1685                 default: 
  1686                     if (Character.isJavaIdentifierPart(ch)) {
  1687                         sb.append(ch);
  1688                     } else {
  1689                         sb.append("_0");
  1690                         String hex = Integer.toHexString(ch).toLowerCase();
  1691                         for (int m = hex.length(); m < 4; m++) {
  1692                             sb.append("0");
  1693                         }
  1694                         sb.append(hex);
  1695                     }
  1696                 break;
  1697             }
  1698         }
  1699         return sb.toString();
  1700     }
  1701     
  1702     private static String mangleClassName(String name) {
  1703         return mangleSig(name);
  1704     }
  1705 
  1706     private static String findMethodName(MethodData m, StringBuilder cnt) {
  1707         StringBuilder name = new StringBuilder();
  1708         if ("<init>".equals(m.getName())) { // NOI18N
  1709             name.append("cons"); // NOI18N
  1710         } else if ("<clinit>".equals(m.getName())) { // NOI18N
  1711             name.append("class"); // NOI18N
  1712         } else {
  1713             name.append(mangleMethodName(m.getName()));
  1714         } 
  1715         
  1716         countArgs(m.getInternalSig(), new char[1], name, cnt);
  1717         return name.toString();
  1718     }
  1719 
  1720     static String findMethodName(String[] mi, StringBuilder cnt, char[] returnType) {
  1721         StringBuilder name = new StringBuilder();
  1722         String descr = mi[2];//mi.getDescriptor();
  1723         String nm= mi[1];
  1724         if ("<init>".equals(nm)) { // NOI18N
  1725             name.append("cons"); // NOI18N
  1726         } else {
  1727             name.append(mangleMethodName(nm));
  1728         }
  1729         countArgs(descr, returnType, name, cnt);
  1730         return name.toString();
  1731     }
  1732 
  1733     private int invokeStaticMethod(byte[] byteCodes, int i, final StackMapper mapper, boolean isStatic)
  1734     throws IOException {
  1735         int methodIndex = readUShortArg(byteCodes, i);
  1736         String[] mi = jc.getFieldInfoName(methodIndex);
  1737         char[] returnType = { 'V' };
  1738         StringBuilder cnt = new StringBuilder();
  1739         String mn = findMethodName(mi, cnt, returnType);
  1740         
  1741         final int numArguments = isStatic ? cnt.length() : cnt.length() + 1;
  1742         final CharSequence[] vars = new CharSequence[numArguments];
  1743 
  1744         for (int j = numArguments - 1; j >= 0; --j) {
  1745             vars[j] = mapper.popValue();
  1746         }
  1747 
  1748         if ((
  1749             "newUpdater__Ljava_util_concurrent_atomic_AtomicIntegerFieldUpdater_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
  1750             && "java/util/concurrent/atomic/AtomicIntegerFieldUpdater".equals(mi[0])
  1751         ) || (
  1752             "newUpdater__Ljava_util_concurrent_atomic_AtomicLongFieldUpdater_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
  1753             && "java/util/concurrent/atomic/AtomicLongFieldUpdater".equals(mi[0])
  1754         )) {
  1755             if (vars[1] instanceof String) {
  1756                 String field = vars[1].toString();
  1757                 if (field.length() > 2 && field.charAt(0) == '"' && field.charAt(field.length() - 1) == '"') {
  1758                     vars[1] = "c._" + field.substring(1, field.length() - 1);
  1759                 }
  1760             }
  1761         }
  1762         if (
  1763             "newUpdater__Ljava_util_concurrent_atomic_AtomicReferenceFieldUpdater_2Ljava_lang_Class_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
  1764             && "java/util/concurrent/atomic/AtomicReferenceFieldUpdater".equals(mi[0])
  1765         ) {
  1766             if (vars[1] instanceof String) {
  1767                 String field = vars[2].toString();
  1768                 if (field.length() > 2 && field.charAt(0) == '"' && field.charAt(field.length() - 1) == '"') {
  1769                     vars[2] = "c._" + field.substring(1, field.length() - 1);
  1770                 }
  1771             }
  1772         }
  1773 
  1774         if (returnType[0] != 'V') {
  1775             mapper.flush(this);
  1776             append("var ")
  1777                .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
  1778                .append(" = ");
  1779         }
  1780 
  1781         final String in = mi[0];
  1782         String mcn;
  1783         if (callbacks && (
  1784             in.equals("org/apidesign/html/boot/spi/Fn") ||
  1785             in.equals("org/netbeans/html/boot/spi/Fn")
  1786         )) {
  1787             mcn = "java_lang_Class";
  1788         } else {
  1789             mcn = mangleClassName(in);
  1790         }
  1791         String object = accessClassFalse(mcn);
  1792         if (mn.startsWith("cons_")) {
  1793             object += ".constructor";
  1794         }
  1795         append(accessStaticMethod(object, mn, mi));
  1796         if (isStatic) {
  1797             append('(');
  1798         } else {
  1799             append(".call(");
  1800         }
  1801         if (numArguments > 0) {
  1802             append(vars[0]);
  1803             for (int j = 1; j < numArguments; ++j) {
  1804                 append(", ");
  1805                 append(vars[j]);
  1806             }
  1807         }
  1808         append(");");
  1809         i += 2;
  1810         addReference(in);
  1811         return i;
  1812     }
  1813     private int invokeVirtualMethod(byte[] byteCodes, int i, final StackMapper mapper)
  1814     throws IOException {
  1815         int methodIndex = readUShortArg(byteCodes, i);
  1816         String[] mi = jc.getFieldInfoName(methodIndex);
  1817         char[] returnType = { 'V' };
  1818         StringBuilder cnt = new StringBuilder();
  1819         String mn = findMethodName(mi, cnt, returnType);
  1820 
  1821         final int numArguments = cnt.length() + 1;
  1822         final CharSequence[] vars =  new CharSequence[numArguments];
  1823 
  1824         for (int j = numArguments - 1; j >= 0; --j) {
  1825             vars[j] = mapper.popValue();
  1826         }
  1827 
  1828         if (returnType[0] != 'V') {
  1829             mapper.flush(this);
  1830             append("var ")
  1831                .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
  1832                .append(" = ");
  1833         }
  1834 
  1835         append(accessVirtualMethod(vars[0].toString(), mn, mi, numArguments));
  1836         String sep = "";
  1837         for (int j = 1; j < numArguments; ++j) {
  1838             append(sep);
  1839             append(vars[j]);
  1840             sep = ", ";
  1841         }
  1842         append(");");
  1843         i += 2;
  1844         return i;
  1845     }
  1846 
  1847     private void addReference(String cn) throws IOException {
  1848         if (requireReference(cn)) {
  1849             debug(" /* needs " + cn + " */");
  1850         }
  1851     }
  1852 
  1853     private void outType(String d, StringBuilder out) {
  1854         int arr = 0;
  1855         while (d.charAt(0) == '[') {
  1856             out.append('A');
  1857             d = d.substring(1);
  1858         }
  1859         if (d.charAt(0) == 'L') {
  1860             assert d.charAt(d.length() - 1) == ';';
  1861             out.append(mangleClassName(d).substring(0, d.length() - 1));
  1862         } else {
  1863             out.append(d);
  1864         }
  1865     }
  1866 
  1867     private String encodeConstant(int entryIndex) throws IOException {
  1868         String[] classRef = { null };
  1869         String s = jc.stringValue(entryIndex, classRef);
  1870         if (classRef[0] != null) {
  1871             if (classRef[0].startsWith("[")) {
  1872                 s = accessClass("java_lang_Class") + "(false)['forName__Ljava_lang_Class_2Ljava_lang_String_2']('" + classRef[0] + "')";
  1873             } else {
  1874                 addReference(classRef[0]);
  1875                 s = accessClassFalse(mangleClassName(s)) + ".constructor.$class";
  1876             }
  1877         }
  1878         return s;
  1879     }
  1880 
  1881     private String javaScriptBody(String destObject, MethodData m, boolean isStatic) throws IOException {
  1882         byte[] arr = m.findAnnotationData(true);
  1883         if (arr == null) {
  1884             return null;
  1885         }
  1886         final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
  1887         final String htmlType = "Lnet/java/html/js/JavaScriptBody;";
  1888         class P extends AnnotationParser {
  1889             public P() {
  1890                 super(false, true);
  1891             }
  1892             
  1893             int cnt;
  1894             String[] args = new String[30];
  1895             String body;
  1896             boolean javacall;
  1897             boolean html4j;
  1898             
  1899             @Override
  1900             protected void visitAttr(String type, String attr, String at, String value) {
  1901                 if (type.equals(jvmType)) {
  1902                     if ("body".equals(attr)) {
  1903                         body = value;
  1904                     } else if ("args".equals(attr)) {
  1905                         args[cnt++] = value;
  1906                     } else {
  1907                         throw new IllegalArgumentException(attr);
  1908                     }
  1909                 }
  1910                 if (type.equals(htmlType)) {
  1911                     html4j = true;
  1912                     if ("body".equals(attr)) {
  1913                         body = value;
  1914                     } else if ("args".equals(attr)) {
  1915                         args[cnt++] = value;
  1916                     } else if ("javacall".equals(attr)) {
  1917                         javacall = "1".equals(value);
  1918                     } else if ("wait4js".equals(attr)) {
  1919                         // ignore, we always invoke synchronously
  1920                     } else {
  1921                         throw new IllegalArgumentException(attr);
  1922                     }
  1923                 }
  1924             }
  1925         }
  1926         P p = new P();
  1927         p.parse(arr, jc);
  1928         if (p.body == null) {
  1929             return null;
  1930         }
  1931         StringBuilder cnt = new StringBuilder();
  1932         final String mn = findMethodName(m, cnt);
  1933         append("m = ").append(destObject).append(".").append(mn);
  1934         append(" = function(");
  1935         String space = "";
  1936         int index = 0;
  1937         StringBuilder toValue = new StringBuilder();
  1938         for (int i = 0; i < cnt.length(); i++) {
  1939             append(space);
  1940             space = outputArg(this, p.args, index);
  1941             if (p.html4j && space.length() > 0) {
  1942                 toValue.append("\n  ").append(p.args[index]).append(" = ")
  1943                     .append(accessClass("java_lang_Class")).append("(false).toJS(").
  1944                     append(p.args[index]).append(");");
  1945             }
  1946             index++;
  1947         }
  1948         append(") {").append("\n");
  1949         append(toValue.toString());
  1950         if (p.javacall) {
  1951             int lastSlash = jc.getClassName().lastIndexOf('/');
  1952             final String pkg = jc.getClassName().substring(0, lastSlash);
  1953             append(mangleCallbacks(pkg, p.body));
  1954             requireReference(pkg + "/$JsCallbacks$");
  1955         } else {
  1956             append(p.body);
  1957         }
  1958         append("\n}\n");
  1959         return mn;
  1960     }
  1961     
  1962     private static CharSequence mangleCallbacks(String pkgName, String body) {
  1963         StringBuilder sb = new StringBuilder();
  1964         int pos = 0;
  1965         for (;;) {
  1966             int next = body.indexOf(".@", pos);
  1967             if (next == -1) {
  1968                 sb.append(body.substring(pos));
  1969                 body = sb.toString();
  1970                 break;
  1971             }
  1972             int ident = next;
  1973             while (ident > 0) {
  1974                 if (!Character.isJavaIdentifierPart(body.charAt(--ident))) {
  1975                     ident++;
  1976                     break;
  1977                 }
  1978             }
  1979             String refId = body.substring(ident, next);
  1980 
  1981             sb.append(body.substring(pos, ident));
  1982 
  1983             int sigBeg = body.indexOf('(', next);
  1984             int sigEnd = body.indexOf(')', sigBeg);
  1985             int colon4 = body.indexOf("::", next);
  1986             if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
  1987                 throw new IllegalStateException("Malformed body " + body);
  1988             }
  1989             String fqn = body.substring(next + 2, colon4);
  1990             String method = body.substring(colon4 + 2, sigBeg);
  1991             String params = body.substring(sigBeg, sigEnd + 1);
  1992 
  1993             int paramBeg = body.indexOf('(', sigEnd + 1);
  1994             
  1995             sb.append("vm.").append(mangleClassName(pkgName)).append("_$JsCallbacks$(false)._VM().");
  1996             sb.append(mangleJsCallbacks(fqn, method, params, false));
  1997             sb.append("(").append(refId);
  1998             if (body.charAt(paramBeg + 1) != ')') {
  1999                 sb.append(",");
  2000             }
  2001             pos = paramBeg + 1;
  2002         }
  2003         sb = null;
  2004         pos = 0;
  2005         for (;;) {
  2006             int next = body.indexOf("@", pos);
  2007             if (next == -1) {
  2008                 if (sb == null) {
  2009                     return body;
  2010                 }
  2011                 sb.append(body.substring(pos));
  2012                 return sb;
  2013             }
  2014             if (sb == null) {
  2015                 sb = new StringBuilder();
  2016             }
  2017 
  2018             sb.append(body.substring(pos, next));
  2019 
  2020             int sigBeg = body.indexOf('(', next);
  2021             int sigEnd = body.indexOf(')', sigBeg);
  2022             int colon4 = body.indexOf("::", next);
  2023             if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
  2024                 throw new IllegalStateException("Malformed body " + body);
  2025             }
  2026             String fqn = body.substring(next + 1, colon4);
  2027             String method = body.substring(colon4 + 2, sigBeg);
  2028             String params = body.substring(sigBeg, sigEnd + 1);
  2029 
  2030             int paramBeg = body.indexOf('(', sigEnd + 1);
  2031             
  2032             sb.append("vm.").append(mangleClassName(pkgName)).append("_$JsCallbacks$(false)._VM().");
  2033             sb.append(mangleJsCallbacks(fqn, method, params, true));
  2034             sb.append("(");
  2035             pos = paramBeg + 1;
  2036         }
  2037     }
  2038 
  2039     static String mangleJsCallbacks(String fqn, String method, String params, boolean isStatic) {
  2040         if (params.startsWith("(")) {
  2041             params = params.substring(1);
  2042         }
  2043         if (params.endsWith(")")) {
  2044             params = params.substring(0, params.length() - 1);
  2045         }
  2046         StringBuilder sb = new StringBuilder();
  2047         final String fqnu = fqn.replace('.', '_');
  2048         final String rfqn = mangleClassName(fqnu);
  2049         final String rm = mangleMethodName(method);
  2050         final String srp;
  2051         {
  2052             StringBuilder pb = new StringBuilder();
  2053             int len = params.length();
  2054             int indx = 0;
  2055             while (indx < len) {
  2056                 char ch = params.charAt(indx);
  2057                 if (ch == '[' || ch == 'L') {
  2058                     int column = params.indexOf(';', indx) + 1;
  2059                     if (column > indx) {
  2060                         String real = params.substring(indx, column);
  2061                         if ("Ljava/lang/String;".equals(real)) {
  2062                             pb.append("Ljava/lang/String;");
  2063                             indx = column;
  2064                             continue;
  2065                         }
  2066                     }
  2067                     pb.append("Ljava/lang/Object;");
  2068                     indx = column;
  2069                 } else {
  2070                     pb.append(ch);
  2071                     indx++;
  2072                 }
  2073             }
  2074             srp = mangleSig(pb.toString());
  2075         }
  2076         final String rp = mangleSig(params);
  2077         final String mrp = mangleMethodName(rp);
  2078         sb.append(rfqn).append("$").append(rm).
  2079             append('$').append(mrp).append("__Ljava_lang_Object_2");
  2080         if (!isStatic) {
  2081             sb.append('L').append(fqnu).append("_2");
  2082         }
  2083         sb.append(srp);
  2084         return sb.toString();
  2085     }
  2086 
  2087     private static String className(ClassData jc) {
  2088         //return jc.getName().getInternalName().replace('/', '_');
  2089         return mangleClassName(jc.getClassName());
  2090     }
  2091     
  2092     private static String[] findAnnotation(
  2093         byte[] arr, ClassData cd, final String className, 
  2094         final String... attrNames
  2095     ) throws IOException {
  2096         if (arr == null) {
  2097             return null;
  2098         }
  2099         final String[] values = new String[attrNames.length];
  2100         final boolean[] found = { false };
  2101         final String jvmType = "L" + className.replace('.', '/') + ";";
  2102         AnnotationParser ap = new AnnotationParser(false, true) {
  2103             @Override
  2104             protected void visitAttr(String type, String attr, String at, String value) {
  2105                 if (type.equals(jvmType)) {
  2106                     found[0] = true;
  2107                     for (int i = 0; i < attrNames.length; i++) {
  2108                         if (attrNames[i].equals(attr)) {
  2109                             values[i] = value;
  2110                         }
  2111                     }
  2112                 }
  2113             }
  2114             
  2115         };
  2116         ap.parse(arr, cd);
  2117         return found[0] ? values : null;
  2118     }
  2119 
  2120     private CharSequence initField(FieldData v) {
  2121         final String is = v.getInternalSig();
  2122         if (is.length() == 1) {
  2123             switch (is.charAt(0)) {
  2124                 case 'S':
  2125                 case 'J':
  2126                 case 'B':
  2127                 case 'Z':
  2128                 case 'C':
  2129                 case 'I': return " = 0;";
  2130                 case 'F': 
  2131                 case 'D': return " = 0.0;";
  2132                 default:
  2133                     throw new IllegalStateException(is);
  2134             }
  2135         }
  2136         return " = null;";
  2137     }
  2138 
  2139     private void generateAnno(ClassData cd, byte[] data) throws IOException {
  2140         AnnotationParser ap = new AnnotationParser(true, false) {
  2141             int[] cnt = new int[32];
  2142             int depth;
  2143             
  2144             @Override
  2145             protected void visitAnnotationStart(String attrType, boolean top) throws IOException {
  2146                 final String slashType = attrType.substring(1, attrType.length() - 1);
  2147                 requireReference(slashType);
  2148                 
  2149                 if (cnt[depth]++ > 0) {
  2150                     append(",");
  2151                 }
  2152                 if (top) {
  2153                     append('"').append(attrType).append("\" : ");
  2154                 }
  2155                 append("{\n");
  2156                 cnt[++depth] = 0;
  2157             }
  2158 
  2159             @Override
  2160             protected void visitAnnotationEnd(String type, boolean top) throws IOException {
  2161                 append("\n}\n");
  2162                 depth--;
  2163             }
  2164 
  2165             @Override
  2166             protected void visitValueStart(String attrName, char type) throws IOException {
  2167                 if (cnt[depth]++ > 0) {
  2168                     append(",\n");
  2169                 }
  2170                 cnt[++depth] = 0;
  2171                 if (attrName != null) {
  2172                     append('"').append(attrName).append("\" : ");
  2173                 }
  2174                 if (type == '[') {
  2175                     append("[");
  2176                 }
  2177             }
  2178 
  2179             @Override
  2180             protected void visitValueEnd(String attrName, char type) throws IOException {
  2181                 if (type == '[') {
  2182                     append("]");
  2183                 }
  2184                 depth--;
  2185             }
  2186             
  2187             @Override
  2188             protected void visitAttr(String type, String attr, String attrType, String value) 
  2189             throws IOException {
  2190                 if (attr == null && value == null) {
  2191                     return;
  2192                 }
  2193                 append(value);
  2194             }
  2195 
  2196             @Override
  2197             protected void visitEnumAttr(String type, String attr, String attrType, String value) 
  2198             throws IOException {
  2199                 final String slashType = attrType.substring(1, attrType.length() - 1);
  2200                 requireReference(slashType);
  2201                 
  2202                 final String cn = mangleClassName(slashType);
  2203                 append(accessClassFalse(cn))
  2204                    .append("['valueOf__L").
  2205                     append(cn).
  2206                     append("_2Ljava_lang_String_2']('").
  2207                     append(value).
  2208                     append("')");
  2209             }
  2210         };
  2211         ap.parse(data, cd);
  2212     }
  2213 
  2214     private static String outputArg(Appendable out, String[] args, int indx) throws IOException {
  2215         final String name = args[indx];
  2216         if (name == null) {
  2217             return "";
  2218         }
  2219         if (name.contains(",")) {
  2220             throw new IOException("Wrong parameter with ',': " + name);
  2221         }
  2222         out.append(name);
  2223         return ",";
  2224     }
  2225 
  2226     final void emitNoFlush(
  2227         StackMapper sm, 
  2228         final String format, final CharSequence... params
  2229     ) throws IOException {
  2230         emitImpl(this, format, params);
  2231     }
  2232     static final void emit(
  2233         StackMapper sm, 
  2234         final Appendable out, 
  2235         final String format, final CharSequence... params
  2236     ) throws IOException {
  2237         sm.flush(out);
  2238         emitImpl(out, format, params);
  2239     }
  2240     static void emitImpl(final Appendable out,
  2241                              final String format,
  2242                              final CharSequence... params) throws IOException {
  2243         final int length = format.length();
  2244 
  2245         int processed = 0;
  2246         int paramOffset = format.indexOf('@');
  2247         while ((paramOffset != -1) && (paramOffset < (length - 1))) {
  2248             final char paramChar = format.charAt(paramOffset + 1);
  2249             if ((paramChar >= '1') && (paramChar <= '9')) {
  2250                 final int paramIndex = paramChar - '0' - 1;
  2251 
  2252                 out.append(format, processed, paramOffset);
  2253                 out.append(params[paramIndex]);
  2254 
  2255                 ++paramOffset;
  2256                 processed = paramOffset + 1;
  2257             }
  2258 
  2259             paramOffset = format.indexOf('@', paramOffset + 1);
  2260         }
  2261 
  2262         out.append(format, processed, length);
  2263     }
  2264 
  2265     private void generateCatch(TrapData[] traps, int current, int topMostLabel) throws IOException {
  2266         append("} catch (e) {\n");
  2267         int finallyPC = -1;
  2268         for (TrapData e : traps) {
  2269             if (e == null) {
  2270                 break;
  2271             }
  2272             if (e.catch_cpx != 0) { //not finally
  2273                 final String classInternalName = jc.getClassName(e.catch_cpx);
  2274                 addReference(classInternalName);
  2275                 append("e = vm.java_lang_Class(false).bck2BrwsrThrwrbl(e);");
  2276                 append("if (e['$instOf_" + mangleClassName(classInternalName) + "']) {");
  2277                 append("var stA0 = e;");
  2278                 goTo(this, current, e.handler_pc, topMostLabel);
  2279                 append("}\n");
  2280             } else {
  2281                 finallyPC = e.handler_pc;
  2282             }
  2283         }
  2284         if (finallyPC == -1) {
  2285             append("throw e;");
  2286         } else {
  2287             append("var stA0 = e;");
  2288             goTo(this, current, finallyPC, topMostLabel);
  2289         }
  2290         append("\n}");
  2291     }
  2292 
  2293     private static void goTo(Appendable out, int current, int to, int canBack) throws IOException {
  2294         if (to < current) {
  2295             if (canBack < to) {
  2296                 out.append("{ gt = 0; continue X_" + to + "; }");
  2297             } else {
  2298                 out.append("{ gt = " + to + "; continue X_0; }");
  2299             }
  2300         } else {
  2301             out.append("{ gt = " + to + "; break IF; }");
  2302         }
  2303     }
  2304 
  2305     private static void emitIf(
  2306         StackMapper sm, 
  2307         Appendable out, String pattern, 
  2308         CharSequence param, 
  2309         int current, int to, int canBack
  2310     ) throws IOException {
  2311         sm.flush(out);
  2312         emitImpl(out, pattern, param);
  2313         goTo(out, current, to, canBack);
  2314     }
  2315 
  2316     private void generateNewArray(int atype, final StackMapper smapper) throws IOException, IllegalStateException {
  2317         String jvmType;
  2318         switch (atype) {
  2319             case 4: jvmType = "[Z"; break;
  2320             case 5: jvmType = "[C"; break;
  2321             case 6: jvmType = "[F"; break;
  2322             case 7: jvmType = "[D"; break;
  2323             case 8: jvmType = "[B"; break;
  2324             case 9: jvmType = "[S"; break;
  2325             case 10: jvmType = "[I"; break;
  2326             case 11: jvmType = "[J"; break;
  2327             default: throw new IllegalStateException("Array type: " + atype);
  2328         }
  2329         emit(smapper, this, 
  2330             "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](true, '@3', null, @1);",
  2331              smapper.popI(), smapper.pushA(), jvmType);
  2332     }
  2333 
  2334     private void generateANewArray(int type, final StackMapper smapper) throws IOException {
  2335         String typeName = jc.getClassName(type);
  2336         String ref = "null";
  2337         if (typeName.startsWith("[")) {
  2338             typeName = "'[" + typeName + "'";
  2339         } else {
  2340             ref = "vm." + mangleClassName(typeName);
  2341             typeName = "'[L" + typeName + ";'";
  2342         }
  2343         emit(smapper, this,
  2344             "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](false, @3, @4, @1);",
  2345              smapper.popI(), smapper.pushA(), typeName, ref);
  2346     }
  2347 
  2348     private int generateMultiANewArray(int type, final byte[] byteCodes, int i, final StackMapper smapper) throws IOException {
  2349         String typeName = jc.getClassName(type);
  2350         int dim = readUByte(byteCodes, ++i);
  2351         StringBuilder dims = new StringBuilder();
  2352         dims.append('[');
  2353         for (int d = 0; d < dim; d++) {
  2354             if (d != 0) {
  2355                 dims.insert(1, ",");
  2356             }
  2357             dims.insert(1, smapper.popI());
  2358         }
  2359         dims.append(']');
  2360         String fn = "null";
  2361         if (typeName.charAt(dim) == 'L') {
  2362             fn = "vm." + mangleClassName(typeName.substring(dim + 1, typeName.length() - 1));
  2363         }
  2364         emit(smapper, this, 
  2365             "var @2 = Array.prototype['multiNewArray__Ljava_lang_Object_2Ljava_lang_String_2_3ILjava_lang_Object_2']('@3', @1, @4);",
  2366              dims.toString(), smapper.pushA(), typeName, fn
  2367         );
  2368         return i;
  2369     }
  2370 
  2371     private int generateTableSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
  2372         int table = i / 4 * 4 + 4;
  2373         int dflt = i + readInt4(byteCodes, table);
  2374         table += 4;
  2375         int low = readInt4(byteCodes, table);
  2376         table += 4;
  2377         int high = readInt4(byteCodes, table);
  2378         table += 4;
  2379         final CharSequence swVar = smapper.popValue();
  2380         smapper.flush(this);
  2381         append("switch (").append(swVar).append(") {\n");
  2382         while (low <= high) {
  2383             int offset = i + readInt4(byteCodes, table);
  2384             table += 4;
  2385             append("  case " + low).append(":"); goTo(this, i, offset, topMostLabel); append('\n');
  2386             low++;
  2387         }
  2388         append("  default: ");
  2389         goTo(this, i, dflt, topMostLabel);
  2390         append("\n}");
  2391         i = table - 1;
  2392         return i;
  2393     }
  2394 
  2395     private int generateLookupSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
  2396         int table = i / 4 * 4 + 4;
  2397         int dflt = i + readInt4(byteCodes, table);
  2398         table += 4;
  2399         int n = readInt4(byteCodes, table);
  2400         table += 4;
  2401         final CharSequence swVar = smapper.popValue();
  2402         smapper.flush(this);
  2403         append("switch (").append(swVar).append(") {\n");
  2404         while (n-- > 0) {
  2405             int cnstnt = readInt4(byteCodes, table);
  2406             table += 4;
  2407             int offset = i + readInt4(byteCodes, table);
  2408             table += 4;
  2409             append("  case " + cnstnt).append(": "); goTo(this, i, offset, topMostLabel); append('\n');
  2410         }
  2411         append("  default: ");
  2412         goTo(this, i, dflt, topMostLabel);
  2413         append("\n}");
  2414         i = table - 1;
  2415         return i;
  2416     }
  2417 
  2418     private void generateInstanceOf(int indx, final StackMapper smapper) throws IOException {
  2419         String type = jc.getClassName(indx);
  2420         if (!type.startsWith("[")) {
  2421             emit(smapper, this, 
  2422                     "var @2 = @1 != null && @1['$instOf_@3'] ? 1 : 0;",
  2423                  smapper.popA(), smapper.pushI(),
  2424                  mangleClassName(type));
  2425         } else {
  2426             int cnt = 0;
  2427             while (type.charAt(cnt) == '[') {
  2428                 cnt++;
  2429             }
  2430             if (type.charAt(cnt) == 'L') {
  2431                 String component = type.substring(cnt + 1, type.length() - 1);
  2432                 requireReference(component);
  2433                 type = "vm." + mangleClassName(component);
  2434                 emit(smapper, this, 
  2435                     "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @4, @3);",
  2436                     smapper.popA(), smapper.pushI(),
  2437                     type, "" + cnt
  2438                 );
  2439             } else {
  2440                 emit(smapper, this, 
  2441                     "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@3');",
  2442                     smapper.popA(), smapper.pushI(), type
  2443                 );
  2444             }
  2445         }
  2446     }
  2447 
  2448     private void generateCheckcast(int indx, final StackMapper smapper) throws IOException {
  2449         String type = jc.getClassName(indx);
  2450         if (!type.startsWith("[")) {
  2451             emitNoFlush(smapper, 
  2452                  "if (@1 !== null && !@1['$instOf_@2']) vm.java_lang_Class(false).castEx();",
  2453                  smapper.getT(0, VarType.REFERENCE, false), mangleClassName(type));
  2454         } else {
  2455             int cnt = 0;
  2456             while (type.charAt(cnt) == '[') {
  2457                 cnt++;
  2458             }
  2459             if (type.charAt(cnt) == 'L') {
  2460                 String component = type.substring(cnt + 1, type.length() - 1);
  2461                 requireReference(component);
  2462                 type = "vm." + mangleClassName(component);
  2463                 emitNoFlush(smapper, 
  2464                     "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @3, @2)) vm.java_lang_Class(false).castEx();",
  2465                      smapper.getT(0, VarType.REFERENCE, false), type, "" + cnt
  2466                 );
  2467             } else {
  2468                 emitNoFlush(smapper, 
  2469                     "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@2')) vm.java_lang_Class(false).castEx();",
  2470                      smapper.getT(0, VarType.REFERENCE, false), type
  2471                 );
  2472             }
  2473         }
  2474     }
  2475 
  2476     private void generateByteCodeComment(int prev, int i, final byte[] byteCodes) throws IOException {
  2477         for (int j = prev; j <= i; j++) {
  2478             append(" ");
  2479             final int cc = readUByte(byteCodes, j);
  2480             append(Integer.toString(cc));
  2481         }
  2482     }
  2483     
  2484     @JavaScriptBody(args = "msg", body = "")
  2485     private static void println(String msg) {
  2486         System.err.println(msg);
  2487     }
  2488 }