rt/vm/src/main/java/org/apidesign/vm4brwsr/ByteCodeToJavaScript.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sun, 24 Jan 2016 14:31:36 +0100
branchFasterSieve
changeset 1950 71e5cd5b29bc
parent 1840 9d011ab3c192
child 1951 3781fd782472
permissions -rw-r--r--
Frequent access to mod32 operation defined on the Number.prototype is slowing things down significanty.
     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                     smapper.replace(this, type, "@2.call(@1)",
  1431                          smapper.getA(0),
  1432                          accessField(mangleClassAccess,
  1433                                      "_" + fi[1], fi)
  1434                     );
  1435                     i += 2;
  1436                     addReference(fi[0]);
  1437                     break;
  1438                 }
  1439                 case opc_putfield: {
  1440                     int indx = readUShortArg(byteCodes, i);
  1441                     String[] fi = jc.getFieldInfoName(indx);
  1442                     final int type = VarType.fromFieldType(fi[2].charAt(0));
  1443                     final String mangleClass = mangleClassName(fi[0]);
  1444                     final String mangleClassAccess = accessClassFalse(mangleClass);
  1445                     emit(smapper, this, "@3.call(@2, @1);",
  1446                          smapper.popT(type),
  1447                          smapper.popA(),
  1448                          accessField(mangleClassAccess,
  1449                                      "_" + fi[1], fi));
  1450                     i += 2;
  1451                     addReference(fi[0]);
  1452                     break;
  1453                 }
  1454                 case opc_getstatic: {
  1455                     int indx = readUShortArg(byteCodes, i);
  1456                     String[] fi = jc.getFieldInfoName(indx);
  1457                     final int type = VarType.fromFieldType(fi[2].charAt(0));
  1458                     String ac = accessClassFalse(mangleClassName(fi[0]));
  1459                     String af = accessField(ac, "_" + fi[1], fi);
  1460                     smapper.assign(this, type, af + "()");
  1461                     i += 2;
  1462                     addReference(fi[0]);
  1463                     break;
  1464                 }
  1465                 case opc_putstatic: {
  1466                     int indx = readUShortArg(byteCodes, i);
  1467                     String[] fi = jc.getFieldInfoName(indx);
  1468                     final int type = VarType.fromFieldType(fi[2].charAt(0));
  1469                     emit(smapper, this, "@1._@2(@3);",
  1470                          accessClassFalse(mangleClassName(fi[0])), fi[1],
  1471                          smapper.popT(type));
  1472                     i += 2;
  1473                     addReference(fi[0]);
  1474                     break;
  1475                 }
  1476                 case opc_checkcast: {
  1477                     int indx = readUShortArg(byteCodes, i);
  1478                     generateCheckcast(indx, smapper);
  1479                     i += 2;
  1480                     break;
  1481                 }
  1482                 case opc_instanceof: {
  1483                     int indx = readUShortArg(byteCodes, i);
  1484                     generateInstanceOf(indx, smapper);
  1485                     i += 2;
  1486                     break;
  1487                 }
  1488                 case opc_athrow: {
  1489                     final CharSequence v = smapper.popA();
  1490                     smapper.clear();
  1491 
  1492                     emit(smapper, this, "{ var @1 = @2; throw @2; }",
  1493                          smapper.pushA(), v);
  1494                     break;
  1495                 }
  1496 
  1497                 case opc_monitorenter: {
  1498                     debug("/* monitor enter */");
  1499                     smapper.popA();
  1500                     break;
  1501                 }
  1502 
  1503                 case opc_monitorexit: {
  1504                     debug("/* monitor exit */");
  1505                     smapper.popA();
  1506                     break;
  1507                 }
  1508 
  1509                 case opc_wide:
  1510                     wide = true;
  1511                     break;
  1512 
  1513                 default: {
  1514                     wide = false;
  1515                     emit(smapper, this, "throw 'unknown bytecode @1';",
  1516                          Integer.toString(c));
  1517                 }
  1518             }
  1519             if (debug(" //")) {
  1520                 generateByteCodeComment(prev, i, byteCodes);
  1521             }
  1522             if (outChanged) {
  1523                 append("\n");
  1524             }
  1525         }
  1526         if (previousTrap != null) {
  1527             generateCatch(previousTrap, byteCodes.length, topMostLabel);
  1528         }
  1529         if (didBranches) {
  1530             append("\n    }\n");
  1531         }
  1532         while (openBraces-- > 0) {
  1533             append('}');
  1534         }
  1535         if (defineProp) {
  1536             append("\n}});");
  1537         } else {
  1538             append("\n};");
  1539         }
  1540         return defineProp;
  1541     }
  1542 
  1543     private int generateIf(StackMapper mapper, byte[] byteCodes, 
  1544         int i, final CharSequence v2, final CharSequence v1, 
  1545         final String test, int topMostLabel
  1546     ) throws IOException {
  1547         mapper.flush(this);
  1548         int indx = i + readShortArg(byteCodes, i);
  1549         append("if ((").append(v1)
  1550            .append(") ").append(test).append(" (")
  1551            .append(v2).append(")) ");
  1552         goTo(this, i, indx, topMostLabel);
  1553         return i + 2;
  1554     }
  1555     
  1556     private int readInt4(byte[] byteCodes, int offset) {
  1557         final int d = byteCodes[offset + 0] << 24;
  1558         final int c = byteCodes[offset + 1] << 16;
  1559         final int b = byteCodes[offset + 2] << 8;
  1560         final int a = byteCodes[offset + 3];
  1561         return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
  1562     }
  1563     private static int readUByte(byte[] byteCodes, int offset) {
  1564         return byteCodes[offset] & 0xff;
  1565     }
  1566 
  1567     private static int readUShort(byte[] byteCodes, int offset) {
  1568         return ((byteCodes[offset] & 0xff) << 8)
  1569                     | (byteCodes[offset + 1] & 0xff);
  1570     }
  1571     private static int readUShortArg(byte[] byteCodes, int offsetInstruction) {
  1572         return readUShort(byteCodes, offsetInstruction + 1);
  1573     }
  1574 
  1575     private static int readShort(byte[] byteCodes, int offset) {
  1576         int signed = byteCodes[offset];
  1577         byte b0 = (byte)signed;
  1578         return (b0 << 8) | (byteCodes[offset + 1] & 0xff);
  1579     }
  1580     private static int readShortArg(byte[] byteCodes, int offsetInstruction) {
  1581         return readShort(byteCodes, offsetInstruction + 1);
  1582     }
  1583 
  1584     private static void countArgs(String descriptor, char[] returnType, StringBuilder sig, StringBuilder cnt) {
  1585         int i = 0;
  1586         Boolean count = null;
  1587         boolean array = false;
  1588         sig.append("__");
  1589         int firstPos = sig.length();
  1590         while (i < descriptor.length()) {
  1591             char ch = descriptor.charAt(i++);
  1592             switch (ch) {
  1593                 case '(':
  1594                     count = true;
  1595                     continue;
  1596                 case ')':
  1597                     count = false;
  1598                     continue;
  1599                 case 'B': 
  1600                 case 'C': 
  1601                 case 'D': 
  1602                 case 'F': 
  1603                 case 'I': 
  1604                 case 'J': 
  1605                 case 'S': 
  1606                 case 'Z': 
  1607                     if (count) {
  1608                         if (array) {
  1609                             sig.append("_3");
  1610                         }
  1611                         sig.append(ch);
  1612                         if (ch == 'J' || ch == 'D') {
  1613                             cnt.append('1');
  1614                         } else {
  1615                             cnt.append('0');
  1616                         }
  1617                     } else {
  1618                         sig.insert(firstPos, ch);
  1619                         if (array) {
  1620                             returnType[0] = '[';
  1621                             sig.insert(firstPos, "_3");
  1622                         } else {
  1623                             returnType[0] = ch;
  1624                         }
  1625                     }
  1626                     array = false;
  1627                     continue;
  1628                 case 'V': 
  1629                     assert !count;
  1630                     returnType[0] = 'V';
  1631                     sig.insert(firstPos, 'V');
  1632                     continue;
  1633                 case 'L':
  1634                     int next = descriptor.indexOf(';', i);
  1635                     String realSig = mangleSig(descriptor, i - 1, next + 1);
  1636                     if (count) {
  1637                         if (array) {
  1638                             sig.append("_3");
  1639                         }
  1640                         sig.append(realSig);
  1641                         cnt.append('0');
  1642                     } else {
  1643                         sig.insert(firstPos, realSig);
  1644                         if (array) {
  1645                             sig.insert(firstPos, "_3");
  1646                         }
  1647                         returnType[0] = 'L';
  1648                     }
  1649                     i = next + 1;
  1650                     array = false;
  1651                     continue;
  1652                 case '[':
  1653                     array = true;
  1654                     continue;
  1655                 default:
  1656                     throw new IllegalStateException("Invalid char: " + ch);
  1657             }
  1658         }
  1659     }
  1660     
  1661     static String mangleSig(String sig) {
  1662         return mangleSig(sig, 0, sig.length());
  1663     }
  1664     
  1665     private static String mangleMethodName(String name) {
  1666         StringBuilder sb = new StringBuilder(name.length() * 2);
  1667         int last = name.length();
  1668         for (int i = 0; i < last; i++) {
  1669             final char ch = name.charAt(i);
  1670             switch (ch) {
  1671                 case '_': sb.append("_1"); break;
  1672                 default: sb.append(ch); break;
  1673             }
  1674         }
  1675         return sb.toString();
  1676     }
  1677     private static String mangleSig(String txt, int first, int last) {
  1678         StringBuilder sb = new StringBuilder((last - first) * 2);
  1679         for (int i = first; i < last; i++) {
  1680             final char ch = txt.charAt(i);
  1681             switch (ch) {
  1682                 case '/': sb.append('_'); break;
  1683                 case '_': sb.append("_1"); break;
  1684                 case ';': sb.append("_2"); break;
  1685                 case '[': sb.append("_3"); break;
  1686                 default: 
  1687                     if (Character.isJavaIdentifierPart(ch)) {
  1688                         sb.append(ch);
  1689                     } else {
  1690                         sb.append("_0");
  1691                         String hex = Integer.toHexString(ch).toLowerCase();
  1692                         for (int m = hex.length(); m < 4; m++) {
  1693                             sb.append("0");
  1694                         }
  1695                         sb.append(hex);
  1696                     }
  1697                 break;
  1698             }
  1699         }
  1700         return sb.toString();
  1701     }
  1702     
  1703     private static String mangleClassName(String name) {
  1704         return mangleSig(name);
  1705     }
  1706 
  1707     private static String findMethodName(MethodData m, StringBuilder cnt) {
  1708         StringBuilder name = new StringBuilder();
  1709         if ("<init>".equals(m.getName())) { // NOI18N
  1710             name.append("cons"); // NOI18N
  1711         } else if ("<clinit>".equals(m.getName())) { // NOI18N
  1712             name.append("class"); // NOI18N
  1713         } else {
  1714             name.append(mangleMethodName(m.getName()));
  1715         } 
  1716         
  1717         countArgs(m.getInternalSig(), new char[1], name, cnt);
  1718         return name.toString();
  1719     }
  1720 
  1721     static String findMethodName(String[] mi, StringBuilder cnt, char[] returnType) {
  1722         StringBuilder name = new StringBuilder();
  1723         String descr = mi[2];//mi.getDescriptor();
  1724         String nm= mi[1];
  1725         if ("<init>".equals(nm)) { // NOI18N
  1726             name.append("cons"); // NOI18N
  1727         } else {
  1728             name.append(mangleMethodName(nm));
  1729         }
  1730         countArgs(descr, returnType, name, cnt);
  1731         return name.toString();
  1732     }
  1733 
  1734     private int invokeStaticMethod(byte[] byteCodes, int i, final StackMapper mapper, boolean isStatic)
  1735     throws IOException {
  1736         int methodIndex = readUShortArg(byteCodes, i);
  1737         String[] mi = jc.getFieldInfoName(methodIndex);
  1738         char[] returnType = { 'V' };
  1739         StringBuilder cnt = new StringBuilder();
  1740         String mn = findMethodName(mi, cnt, returnType);
  1741         
  1742         final int numArguments = isStatic ? cnt.length() : cnt.length() + 1;
  1743         final CharSequence[] vars = new CharSequence[numArguments];
  1744 
  1745         for (int j = numArguments - 1; j >= 0; --j) {
  1746             vars[j] = mapper.popValue();
  1747         }
  1748 
  1749         if ((
  1750             "newUpdater__Ljava_util_concurrent_atomic_AtomicIntegerFieldUpdater_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
  1751             && "java/util/concurrent/atomic/AtomicIntegerFieldUpdater".equals(mi[0])
  1752         ) || (
  1753             "newUpdater__Ljava_util_concurrent_atomic_AtomicLongFieldUpdater_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
  1754             && "java/util/concurrent/atomic/AtomicLongFieldUpdater".equals(mi[0])
  1755         )) {
  1756             if (vars[1] instanceof String) {
  1757                 String field = vars[1].toString();
  1758                 if (field.length() > 2 && field.charAt(0) == '"' && field.charAt(field.length() - 1) == '"') {
  1759                     vars[1] = "c._" + field.substring(1, field.length() - 1);
  1760                 }
  1761             }
  1762         }
  1763         if (
  1764             "newUpdater__Ljava_util_concurrent_atomic_AtomicReferenceFieldUpdater_2Ljava_lang_Class_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
  1765             && "java/util/concurrent/atomic/AtomicReferenceFieldUpdater".equals(mi[0])
  1766         ) {
  1767             if (vars[1] instanceof String) {
  1768                 String field = vars[2].toString();
  1769                 if (field.length() > 2 && field.charAt(0) == '"' && field.charAt(field.length() - 1) == '"') {
  1770                     vars[2] = "c._" + field.substring(1, field.length() - 1);
  1771                 }
  1772             }
  1773         }
  1774 
  1775         if (returnType[0] != 'V') {
  1776             mapper.flush(this);
  1777             append("var ")
  1778                .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
  1779                .append(" = ");
  1780         }
  1781 
  1782         final String in = mi[0];
  1783         String mcn;
  1784         if (callbacks && (
  1785             in.equals("org/apidesign/html/boot/spi/Fn") ||
  1786             in.equals("org/netbeans/html/boot/spi/Fn")
  1787         )) {
  1788             mcn = "java_lang_Class";
  1789         } else {
  1790             mcn = mangleClassName(in);
  1791         }
  1792         String object = accessClassFalse(mcn);
  1793         if (mn.startsWith("cons_")) {
  1794             object += ".constructor";
  1795         }
  1796         append(accessStaticMethod(object, mn, mi));
  1797         if (isStatic) {
  1798             append('(');
  1799         } else {
  1800             append(".call(");
  1801         }
  1802         if (numArguments > 0) {
  1803             append(vars[0]);
  1804             for (int j = 1; j < numArguments; ++j) {
  1805                 append(", ");
  1806                 append(vars[j]);
  1807             }
  1808         }
  1809         append(");");
  1810         i += 2;
  1811         addReference(in);
  1812         return i;
  1813     }
  1814     private int invokeVirtualMethod(byte[] byteCodes, int i, final StackMapper mapper)
  1815     throws IOException {
  1816         int methodIndex = readUShortArg(byteCodes, i);
  1817         String[] mi = jc.getFieldInfoName(methodIndex);
  1818         char[] returnType = { 'V' };
  1819         StringBuilder cnt = new StringBuilder();
  1820         String mn = findMethodName(mi, cnt, returnType);
  1821 
  1822         final int numArguments = cnt.length() + 1;
  1823         final CharSequence[] vars =  new CharSequence[numArguments];
  1824 
  1825         for (int j = numArguments - 1; j >= 0; --j) {
  1826             vars[j] = mapper.popValue();
  1827         }
  1828 
  1829         if (returnType[0] != 'V') {
  1830             mapper.flush(this);
  1831             append("var ")
  1832                .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
  1833                .append(" = ");
  1834         }
  1835 
  1836         append(accessVirtualMethod(vars[0].toString(), mn, mi, numArguments));
  1837         String sep = "";
  1838         for (int j = 1; j < numArguments; ++j) {
  1839             append(sep);
  1840             append(vars[j]);
  1841             sep = ", ";
  1842         }
  1843         append(");");
  1844         i += 2;
  1845         return i;
  1846     }
  1847 
  1848     private void addReference(String cn) throws IOException {
  1849         if (requireReference(cn)) {
  1850             debug(" /* needs " + cn + " */");
  1851         }
  1852     }
  1853 
  1854     private void outType(String d, StringBuilder out) {
  1855         int arr = 0;
  1856         while (d.charAt(0) == '[') {
  1857             out.append('A');
  1858             d = d.substring(1);
  1859         }
  1860         if (d.charAt(0) == 'L') {
  1861             assert d.charAt(d.length() - 1) == ';';
  1862             out.append(mangleClassName(d).substring(0, d.length() - 1));
  1863         } else {
  1864             out.append(d);
  1865         }
  1866     }
  1867 
  1868     private String encodeConstant(int entryIndex) throws IOException {
  1869         String[] classRef = { null };
  1870         String s = jc.stringValue(entryIndex, classRef);
  1871         if (classRef[0] != null) {
  1872             if (classRef[0].startsWith("[")) {
  1873                 s = accessClass("java_lang_Class") + "(false)['forName__Ljava_lang_Class_2Ljava_lang_String_2']('" + classRef[0] + "')";
  1874             } else {
  1875                 addReference(classRef[0]);
  1876                 s = accessClassFalse(mangleClassName(s)) + ".constructor.$class";
  1877             }
  1878         }
  1879         return s;
  1880     }
  1881 
  1882     private String javaScriptBody(String destObject, MethodData m, boolean isStatic) throws IOException {
  1883         byte[] arr = m.findAnnotationData(true);
  1884         if (arr == null) {
  1885             return null;
  1886         }
  1887         final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
  1888         final String htmlType = "Lnet/java/html/js/JavaScriptBody;";
  1889         class P extends AnnotationParser {
  1890             public P() {
  1891                 super(false, true);
  1892             }
  1893             
  1894             int cnt;
  1895             String[] args = new String[30];
  1896             String body;
  1897             boolean javacall;
  1898             boolean html4j;
  1899             
  1900             @Override
  1901             protected void visitAttr(String type, String attr, String at, String value) {
  1902                 if (type.equals(jvmType)) {
  1903                     if ("body".equals(attr)) {
  1904                         body = value;
  1905                     } else if ("args".equals(attr)) {
  1906                         args[cnt++] = value;
  1907                     } else {
  1908                         throw new IllegalArgumentException(attr);
  1909                     }
  1910                 }
  1911                 if (type.equals(htmlType)) {
  1912                     html4j = true;
  1913                     if ("body".equals(attr)) {
  1914                         body = value;
  1915                     } else if ("args".equals(attr)) {
  1916                         args[cnt++] = value;
  1917                     } else if ("javacall".equals(attr)) {
  1918                         javacall = "1".equals(value);
  1919                     } else if ("wait4js".equals(attr)) {
  1920                         // ignore, we always invoke synchronously
  1921                     } else {
  1922                         throw new IllegalArgumentException(attr);
  1923                     }
  1924                 }
  1925             }
  1926         }
  1927         P p = new P();
  1928         p.parse(arr, jc);
  1929         if (p.body == null) {
  1930             return null;
  1931         }
  1932         StringBuilder cnt = new StringBuilder();
  1933         final String mn = findMethodName(m, cnt);
  1934         append("m = ").append(destObject).append(".").append(mn);
  1935         append(" = function(");
  1936         String space = "";
  1937         int index = 0;
  1938         StringBuilder toValue = new StringBuilder();
  1939         for (int i = 0; i < cnt.length(); i++) {
  1940             append(space);
  1941             space = outputArg(this, p.args, index);
  1942             if (p.html4j && space.length() > 0) {
  1943                 toValue.append("\n  ").append(p.args[index]).append(" = ")
  1944                     .append(accessClass("java_lang_Class")).append("(false).toJS(").
  1945                     append(p.args[index]).append(");");
  1946             }
  1947             index++;
  1948         }
  1949         append(") {").append("\n");
  1950         append(toValue.toString());
  1951         if (p.javacall) {
  1952             int lastSlash = jc.getClassName().lastIndexOf('/');
  1953             final String pkg = jc.getClassName().substring(0, lastSlash);
  1954             append(mangleCallbacks(pkg, p.body));
  1955             requireReference(pkg + "/$JsCallbacks$");
  1956         } else {
  1957             append(p.body);
  1958         }
  1959         append("\n}\n");
  1960         return mn;
  1961     }
  1962     
  1963     private static CharSequence mangleCallbacks(String pkgName, String body) {
  1964         StringBuilder sb = new StringBuilder();
  1965         int pos = 0;
  1966         for (;;) {
  1967             int next = body.indexOf(".@", pos);
  1968             if (next == -1) {
  1969                 sb.append(body.substring(pos));
  1970                 body = sb.toString();
  1971                 break;
  1972             }
  1973             int ident = next;
  1974             while (ident > 0) {
  1975                 if (!Character.isJavaIdentifierPart(body.charAt(--ident))) {
  1976                     ident++;
  1977                     break;
  1978                 }
  1979             }
  1980             String refId = body.substring(ident, next);
  1981 
  1982             sb.append(body.substring(pos, ident));
  1983 
  1984             int sigBeg = body.indexOf('(', next);
  1985             int sigEnd = body.indexOf(')', sigBeg);
  1986             int colon4 = body.indexOf("::", next);
  1987             if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
  1988                 throw new IllegalStateException("Malformed body " + body);
  1989             }
  1990             String fqn = body.substring(next + 2, colon4);
  1991             String method = body.substring(colon4 + 2, sigBeg);
  1992             String params = body.substring(sigBeg, sigEnd + 1);
  1993 
  1994             int paramBeg = body.indexOf('(', sigEnd + 1);
  1995             
  1996             sb.append("vm.").append(mangleClassName(pkgName)).append("_$JsCallbacks$(false)._VM().");
  1997             sb.append(mangleJsCallbacks(fqn, method, params, false));
  1998             sb.append("(").append(refId);
  1999             if (body.charAt(paramBeg + 1) != ')') {
  2000                 sb.append(",");
  2001             }
  2002             pos = paramBeg + 1;
  2003         }
  2004         sb = null;
  2005         pos = 0;
  2006         for (;;) {
  2007             int next = body.indexOf("@", pos);
  2008             if (next == -1) {
  2009                 if (sb == null) {
  2010                     return body;
  2011                 }
  2012                 sb.append(body.substring(pos));
  2013                 return sb;
  2014             }
  2015             if (sb == null) {
  2016                 sb = new StringBuilder();
  2017             }
  2018 
  2019             sb.append(body.substring(pos, next));
  2020 
  2021             int sigBeg = body.indexOf('(', next);
  2022             int sigEnd = body.indexOf(')', sigBeg);
  2023             int colon4 = body.indexOf("::", next);
  2024             if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
  2025                 throw new IllegalStateException("Malformed body " + body);
  2026             }
  2027             String fqn = body.substring(next + 1, colon4);
  2028             String method = body.substring(colon4 + 2, sigBeg);
  2029             String params = body.substring(sigBeg, sigEnd + 1);
  2030 
  2031             int paramBeg = body.indexOf('(', sigEnd + 1);
  2032             
  2033             sb.append("vm.").append(mangleClassName(pkgName)).append("_$JsCallbacks$(false)._VM().");
  2034             sb.append(mangleJsCallbacks(fqn, method, params, true));
  2035             sb.append("(");
  2036             pos = paramBeg + 1;
  2037         }
  2038     }
  2039 
  2040     static String mangleJsCallbacks(String fqn, String method, String params, boolean isStatic) {
  2041         if (params.startsWith("(")) {
  2042             params = params.substring(1);
  2043         }
  2044         if (params.endsWith(")")) {
  2045             params = params.substring(0, params.length() - 1);
  2046         }
  2047         StringBuilder sb = new StringBuilder();
  2048         final String fqnu = fqn.replace('.', '_');
  2049         final String rfqn = mangleClassName(fqnu);
  2050         final String rm = mangleMethodName(method);
  2051         final String srp;
  2052         {
  2053             StringBuilder pb = new StringBuilder();
  2054             int len = params.length();
  2055             int indx = 0;
  2056             while (indx < len) {
  2057                 char ch = params.charAt(indx);
  2058                 if (ch == '[' || ch == 'L') {
  2059                     int column = params.indexOf(';', indx) + 1;
  2060                     if (column > indx) {
  2061                         String real = params.substring(indx, column);
  2062                         if ("Ljava/lang/String;".equals(real)) {
  2063                             pb.append("Ljava/lang/String;");
  2064                             indx = column;
  2065                             continue;
  2066                         }
  2067                     }
  2068                     pb.append("Ljava/lang/Object;");
  2069                     indx = column;
  2070                 } else {
  2071                     pb.append(ch);
  2072                     indx++;
  2073                 }
  2074             }
  2075             srp = mangleSig(pb.toString());
  2076         }
  2077         final String rp = mangleSig(params);
  2078         final String mrp = mangleMethodName(rp);
  2079         sb.append(rfqn).append("$").append(rm).
  2080             append('$').append(mrp).append("__Ljava_lang_Object_2");
  2081         if (!isStatic) {
  2082             sb.append('L').append(fqnu).append("_2");
  2083         }
  2084         sb.append(srp);
  2085         return sb.toString();
  2086     }
  2087 
  2088     private static String className(ClassData jc) {
  2089         //return jc.getName().getInternalName().replace('/', '_');
  2090         return mangleClassName(jc.getClassName());
  2091     }
  2092     
  2093     private static String[] findAnnotation(
  2094         byte[] arr, ClassData cd, final String className, 
  2095         final String... attrNames
  2096     ) throws IOException {
  2097         if (arr == null) {
  2098             return null;
  2099         }
  2100         final String[] values = new String[attrNames.length];
  2101         final boolean[] found = { false };
  2102         final String jvmType = "L" + className.replace('.', '/') + ";";
  2103         AnnotationParser ap = new AnnotationParser(false, true) {
  2104             @Override
  2105             protected void visitAttr(String type, String attr, String at, String value) {
  2106                 if (type.equals(jvmType)) {
  2107                     found[0] = true;
  2108                     for (int i = 0; i < attrNames.length; i++) {
  2109                         if (attrNames[i].equals(attr)) {
  2110                             values[i] = value;
  2111                         }
  2112                     }
  2113                 }
  2114             }
  2115             
  2116         };
  2117         ap.parse(arr, cd);
  2118         return found[0] ? values : null;
  2119     }
  2120 
  2121     private CharSequence initField(FieldData v) {
  2122         final String is = v.getInternalSig();
  2123         if (is.length() == 1) {
  2124             switch (is.charAt(0)) {
  2125                 case 'S':
  2126                 case 'J':
  2127                 case 'B':
  2128                 case 'Z':
  2129                 case 'C':
  2130                 case 'I': return " = 0;";
  2131                 case 'F': 
  2132                 case 'D': return " = 0.0;";
  2133                 default:
  2134                     throw new IllegalStateException(is);
  2135             }
  2136         }
  2137         return " = null;";
  2138     }
  2139 
  2140     private void generateAnno(ClassData cd, byte[] data) throws IOException {
  2141         AnnotationParser ap = new AnnotationParser(true, false) {
  2142             int[] cnt = new int[32];
  2143             int depth;
  2144             
  2145             @Override
  2146             protected void visitAnnotationStart(String attrType, boolean top) throws IOException {
  2147                 final String slashType = attrType.substring(1, attrType.length() - 1);
  2148                 requireReference(slashType);
  2149                 
  2150                 if (cnt[depth]++ > 0) {
  2151                     append(",");
  2152                 }
  2153                 if (top) {
  2154                     append('"').append(attrType).append("\" : ");
  2155                 }
  2156                 append("{\n");
  2157                 cnt[++depth] = 0;
  2158             }
  2159 
  2160             @Override
  2161             protected void visitAnnotationEnd(String type, boolean top) throws IOException {
  2162                 append("\n}\n");
  2163                 depth--;
  2164             }
  2165 
  2166             @Override
  2167             protected void visitValueStart(String attrName, char type) throws IOException {
  2168                 if (cnt[depth]++ > 0) {
  2169                     append(",\n");
  2170                 }
  2171                 cnt[++depth] = 0;
  2172                 if (attrName != null) {
  2173                     append('"').append(attrName).append("\" : ");
  2174                 }
  2175                 if (type == '[') {
  2176                     append("[");
  2177                 }
  2178             }
  2179 
  2180             @Override
  2181             protected void visitValueEnd(String attrName, char type) throws IOException {
  2182                 if (type == '[') {
  2183                     append("]");
  2184                 }
  2185                 depth--;
  2186             }
  2187             
  2188             @Override
  2189             protected void visitAttr(String type, String attr, String attrType, String value) 
  2190             throws IOException {
  2191                 if (attr == null && value == null) {
  2192                     return;
  2193                 }
  2194                 append(value);
  2195             }
  2196 
  2197             @Override
  2198             protected void visitEnumAttr(String type, String attr, String attrType, String value) 
  2199             throws IOException {
  2200                 final String slashType = attrType.substring(1, attrType.length() - 1);
  2201                 requireReference(slashType);
  2202                 
  2203                 final String cn = mangleClassName(slashType);
  2204                 append(accessClassFalse(cn))
  2205                    .append("['valueOf__L").
  2206                     append(cn).
  2207                     append("_2Ljava_lang_String_2']('").
  2208                     append(value).
  2209                     append("')");
  2210             }
  2211         };
  2212         ap.parse(data, cd);
  2213     }
  2214 
  2215     private static String outputArg(Appendable out, String[] args, int indx) throws IOException {
  2216         final String name = args[indx];
  2217         if (name == null) {
  2218             return "";
  2219         }
  2220         if (name.contains(",")) {
  2221             throw new IOException("Wrong parameter with ',': " + name);
  2222         }
  2223         out.append(name);
  2224         return ",";
  2225     }
  2226 
  2227     final void emitNoFlush(
  2228         StackMapper sm, 
  2229         final String format, final CharSequence... params
  2230     ) throws IOException {
  2231         emitImpl(this, format, params);
  2232     }
  2233     static final void emit(
  2234         StackMapper sm, 
  2235         final Appendable out, 
  2236         final String format, final CharSequence... params
  2237     ) throws IOException {
  2238         sm.flush(out);
  2239         emitImpl(out, format, params);
  2240     }
  2241     static void emitImpl(final Appendable out,
  2242                              final String format,
  2243                              final CharSequence... params) throws IOException {
  2244         final int length = format.length();
  2245 
  2246         int processed = 0;
  2247         int paramOffset = format.indexOf('@');
  2248         while ((paramOffset != -1) && (paramOffset < (length - 1))) {
  2249             final char paramChar = format.charAt(paramOffset + 1);
  2250             if ((paramChar >= '1') && (paramChar <= '9')) {
  2251                 final int paramIndex = paramChar - '0' - 1;
  2252 
  2253                 out.append(format, processed, paramOffset);
  2254                 out.append(params[paramIndex]);
  2255 
  2256                 ++paramOffset;
  2257                 processed = paramOffset + 1;
  2258             }
  2259 
  2260             paramOffset = format.indexOf('@', paramOffset + 1);
  2261         }
  2262 
  2263         out.append(format, processed, length);
  2264     }
  2265 
  2266     private void generateCatch(TrapData[] traps, int current, int topMostLabel) throws IOException {
  2267         append("} catch (e) {\n");
  2268         int finallyPC = -1;
  2269         for (TrapData e : traps) {
  2270             if (e == null) {
  2271                 break;
  2272             }
  2273             if (e.catch_cpx != 0) { //not finally
  2274                 final String classInternalName = jc.getClassName(e.catch_cpx);
  2275                 addReference(classInternalName);
  2276                 append("e = vm.java_lang_Class(false).bck2BrwsrThrwrbl(e);");
  2277                 append("if (e['$instOf_" + mangleClassName(classInternalName) + "']) {");
  2278                 append("var stA0 = e;");
  2279                 goTo(this, current, e.handler_pc, topMostLabel);
  2280                 append("}\n");
  2281             } else {
  2282                 finallyPC = e.handler_pc;
  2283             }
  2284         }
  2285         if (finallyPC == -1) {
  2286             append("throw e;");
  2287         } else {
  2288             append("var stA0 = e;");
  2289             goTo(this, current, finallyPC, topMostLabel);
  2290         }
  2291         append("\n}");
  2292     }
  2293 
  2294     private static void goTo(Appendable out, int current, int to, int canBack) throws IOException {
  2295         if (to < current) {
  2296             if (canBack < to) {
  2297                 out.append("{ gt = 0; continue X_" + to + "; }");
  2298             } else {
  2299                 out.append("{ gt = " + to + "; continue X_0; }");
  2300             }
  2301         } else {
  2302             out.append("{ gt = " + to + "; break IF; }");
  2303         }
  2304     }
  2305 
  2306     private static void emitIf(
  2307         StackMapper sm, 
  2308         Appendable out, String pattern, 
  2309         CharSequence param, 
  2310         int current, int to, int canBack
  2311     ) throws IOException {
  2312         sm.flush(out);
  2313         emitImpl(out, pattern, param);
  2314         goTo(out, current, to, canBack);
  2315     }
  2316 
  2317     private void generateNewArray(int atype, final StackMapper smapper) throws IOException, IllegalStateException {
  2318         String jvmType;
  2319         switch (atype) {
  2320             case 4: jvmType = "[Z"; break;
  2321             case 5: jvmType = "[C"; break;
  2322             case 6: jvmType = "[F"; break;
  2323             case 7: jvmType = "[D"; break;
  2324             case 8: jvmType = "[B"; break;
  2325             case 9: jvmType = "[S"; break;
  2326             case 10: jvmType = "[I"; break;
  2327             case 11: jvmType = "[J"; break;
  2328             default: throw new IllegalStateException("Array type: " + atype);
  2329         }
  2330         emit(smapper, this, 
  2331             "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](true, '@3', null, @1);",
  2332              smapper.popI(), smapper.pushA(), jvmType);
  2333     }
  2334 
  2335     private void generateANewArray(int type, final StackMapper smapper) throws IOException {
  2336         String typeName = jc.getClassName(type);
  2337         String ref = "null";
  2338         if (typeName.startsWith("[")) {
  2339             typeName = "'[" + typeName + "'";
  2340         } else {
  2341             ref = "vm." + mangleClassName(typeName);
  2342             typeName = "'[L" + typeName + ";'";
  2343         }
  2344         emit(smapper, this,
  2345             "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](false, @3, @4, @1);",
  2346              smapper.popI(), smapper.pushA(), typeName, ref);
  2347     }
  2348 
  2349     private int generateMultiANewArray(int type, final byte[] byteCodes, int i, final StackMapper smapper) throws IOException {
  2350         String typeName = jc.getClassName(type);
  2351         int dim = readUByte(byteCodes, ++i);
  2352         StringBuilder dims = new StringBuilder();
  2353         dims.append('[');
  2354         for (int d = 0; d < dim; d++) {
  2355             if (d != 0) {
  2356                 dims.insert(1, ",");
  2357             }
  2358             dims.insert(1, smapper.popI());
  2359         }
  2360         dims.append(']');
  2361         String fn = "null";
  2362         if (typeName.charAt(dim) == 'L') {
  2363             fn = "vm." + mangleClassName(typeName.substring(dim + 1, typeName.length() - 1));
  2364         }
  2365         emit(smapper, this, 
  2366             "var @2 = Array.prototype['multiNewArray__Ljava_lang_Object_2Ljava_lang_String_2_3ILjava_lang_Object_2']('@3', @1, @4);",
  2367              dims.toString(), smapper.pushA(), typeName, fn
  2368         );
  2369         return i;
  2370     }
  2371 
  2372     private int generateTableSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
  2373         int table = i / 4 * 4 + 4;
  2374         int dflt = i + readInt4(byteCodes, table);
  2375         table += 4;
  2376         int low = readInt4(byteCodes, table);
  2377         table += 4;
  2378         int high = readInt4(byteCodes, table);
  2379         table += 4;
  2380         final CharSequence swVar = smapper.popValue();
  2381         smapper.flush(this);
  2382         append("switch (").append(swVar).append(") {\n");
  2383         while (low <= high) {
  2384             int offset = i + readInt4(byteCodes, table);
  2385             table += 4;
  2386             append("  case " + low).append(":"); goTo(this, i, offset, topMostLabel); append('\n');
  2387             low++;
  2388         }
  2389         append("  default: ");
  2390         goTo(this, i, dflt, topMostLabel);
  2391         append("\n}");
  2392         i = table - 1;
  2393         return i;
  2394     }
  2395 
  2396     private int generateLookupSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
  2397         int table = i / 4 * 4 + 4;
  2398         int dflt = i + readInt4(byteCodes, table);
  2399         table += 4;
  2400         int n = readInt4(byteCodes, table);
  2401         table += 4;
  2402         final CharSequence swVar = smapper.popValue();
  2403         smapper.flush(this);
  2404         append("switch (").append(swVar).append(") {\n");
  2405         while (n-- > 0) {
  2406             int cnstnt = readInt4(byteCodes, table);
  2407             table += 4;
  2408             int offset = i + readInt4(byteCodes, table);
  2409             table += 4;
  2410             append("  case " + cnstnt).append(": "); goTo(this, i, offset, topMostLabel); append('\n');
  2411         }
  2412         append("  default: ");
  2413         goTo(this, i, dflt, topMostLabel);
  2414         append("\n}");
  2415         i = table - 1;
  2416         return i;
  2417     }
  2418 
  2419     private void generateInstanceOf(int indx, final StackMapper smapper) throws IOException {
  2420         String type = jc.getClassName(indx);
  2421         if (!type.startsWith("[")) {
  2422             emit(smapper, this, 
  2423                     "var @2 = @1 != null && @1['$instOf_@3'] ? 1 : 0;",
  2424                  smapper.popA(), smapper.pushI(),
  2425                  mangleClassName(type));
  2426         } else {
  2427             int cnt = 0;
  2428             while (type.charAt(cnt) == '[') {
  2429                 cnt++;
  2430             }
  2431             if (type.charAt(cnt) == 'L') {
  2432                 String component = type.substring(cnt + 1, type.length() - 1);
  2433                 requireReference(component);
  2434                 type = "vm." + mangleClassName(component);
  2435                 emit(smapper, this, 
  2436                     "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @4, @3);",
  2437                     smapper.popA(), smapper.pushI(),
  2438                     type, "" + cnt
  2439                 );
  2440             } else {
  2441                 emit(smapper, this, 
  2442                     "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@3');",
  2443                     smapper.popA(), smapper.pushI(), type
  2444                 );
  2445             }
  2446         }
  2447     }
  2448 
  2449     private void generateCheckcast(int indx, final StackMapper smapper) throws IOException {
  2450         String type = jc.getClassName(indx);
  2451         if (!type.startsWith("[")) {
  2452             emitNoFlush(smapper, 
  2453                  "if (@1 !== null && !@1['$instOf_@2']) vm.java_lang_Class(false).castEx();",
  2454                  smapper.getT(0, VarType.REFERENCE, false), mangleClassName(type));
  2455         } else {
  2456             int cnt = 0;
  2457             while (type.charAt(cnt) == '[') {
  2458                 cnt++;
  2459             }
  2460             if (type.charAt(cnt) == 'L') {
  2461                 String component = type.substring(cnt + 1, type.length() - 1);
  2462                 requireReference(component);
  2463                 type = "vm." + mangleClassName(component);
  2464                 emitNoFlush(smapper, 
  2465                     "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @3, @2)) vm.java_lang_Class(false).castEx();",
  2466                      smapper.getT(0, VarType.REFERENCE, false), type, "" + cnt
  2467                 );
  2468             } else {
  2469                 emitNoFlush(smapper, 
  2470                     "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@2')) vm.java_lang_Class(false).castEx();",
  2471                      smapper.getT(0, VarType.REFERENCE, false), type
  2472                 );
  2473             }
  2474         }
  2475     }
  2476 
  2477     private void generateByteCodeComment(int prev, int i, final byte[] byteCodes) throws IOException {
  2478         for (int j = prev; j <= i; j++) {
  2479             append(" ");
  2480             final int cc = readUByte(byteCodes, j);
  2481             append(Integer.toString(cc));
  2482         }
  2483     }
  2484     
  2485     @JavaScriptBody(args = "msg", body = "")
  2486     private static void println(String msg) {
  2487         System.err.println(msg);
  2488     }
  2489 }