rt/vm/src/main/java/org/apidesign/vm4brwsr/ByteCodeToJavaScript.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Wed, 02 Sep 2015 23:20:01 +0200
changeset 1840 9d011ab3c192
parent 1823 999cf0169156
child 1855 34efbdde4eca
child 1950 71e5cd5b29bc
permissions -rw-r--r--
Consistent mangling of names with underscore
     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                     smapper.replace(this, VarType.INTEGER, "(@1).mod32(@2)",
   779                          smapper.getI(1), smapper.popI());
   780                     break;
   781                 case opc_lrem:
   782                     smapper.replace(this, VarType.LONG, "(@1).mod64(@2)",
   783                          smapper.getL(1), smapper.popL());
   784                     break;
   785                 case opc_frem:
   786                     smapper.replace(this, VarType.FLOAT, "(@1 % @2)", smapper.getF(1), smapper.popF());
   787                     break;
   788                 case opc_drem:
   789                     smapper.replace(this, VarType.DOUBLE, "(@1 % @2)", smapper.getD(1), smapper.popD());
   790                     break;
   791                 case opc_iand:
   792                     smapper.replace(this, VarType.INTEGER, "(@1 & @2)", smapper.getI(1), smapper.popI());
   793                     break;
   794                 case opc_land:
   795                     smapper.replace(this, VarType.LONG, "(@1).and64(@2)", smapper.getL(1), smapper.popL());
   796                     break;
   797                 case opc_ior:
   798                     smapper.replace(this, VarType.INTEGER, "(@1 | @2)", smapper.getI(1), smapper.popI());
   799                     break;
   800                 case opc_lor:
   801                     smapper.replace(this, VarType.LONG, "(@1).or64(@2)", smapper.getL(1), smapper.popL());
   802                     break;
   803                 case opc_ixor:
   804                     smapper.replace(this, VarType.INTEGER, "(@1 ^ @2)", smapper.getI(1), smapper.popI());
   805                     break;
   806                 case opc_lxor:
   807                     smapper.replace(this, VarType.LONG, "(@1).xor64(@2)", smapper.getL(1), smapper.popL());
   808                     break;
   809                 case opc_ineg:
   810                     smapper.replace(this, VarType.INTEGER, "(@1).neg32()", smapper.getI(0));
   811                     break;
   812                 case opc_lneg:
   813                     smapper.replace(this, VarType.LONG, "(@1).neg64()", smapper.getL(0));
   814                     break;
   815                 case opc_fneg:
   816                     smapper.replace(this, VarType.FLOAT, "(-@1)", smapper.getF(0));
   817                     break;
   818                 case opc_dneg:
   819                     smapper.replace(this, VarType.DOUBLE, "(-@1)", smapper.getD(0));
   820                     break;
   821                 case opc_ishl:
   822                     smapper.replace(this, VarType.INTEGER, "(@1 << @2)", smapper.getI(1), smapper.popI());
   823                     break;
   824                 case opc_lshl:
   825                     smapper.replace(this, VarType.LONG, "(@1).shl64(@2)", smapper.getL(1), smapper.popI());
   826                     break;
   827                 case opc_ishr:
   828                     smapper.replace(this, VarType.INTEGER, "(@1 >> @2)", smapper.getI(1), smapper.popI());
   829                     break;
   830                 case opc_lshr:
   831                     smapper.replace(this, VarType.LONG, "(@1).shr64(@2)", smapper.getL(1), smapper.popI());
   832                     break;
   833                 case opc_iushr:
   834                     smapper.replace(this, VarType.INTEGER, "(@1 >>> @2)", smapper.getI(1), smapper.popI());
   835                     break;
   836                 case opc_lushr:
   837                     smapper.replace(this, VarType.LONG, "(@1).ushr64(@2)", smapper.getL(1), smapper.popI());
   838                     break;
   839                 case opc_iinc: {
   840                     ++i;
   841                     final int varIndx = wide ? readUShort(byteCodes, i++)
   842                                              : readUByte(byteCodes, i);
   843                     ++i;
   844                     final int incrBy = wide ? readShort(byteCodes, i++)
   845                                             : byteCodes[i];
   846                     wide = false;
   847                     if (incrBy == 1) {
   848                         emit(smapper, this, "@1++;", lmapper.getI(varIndx));
   849                     } else {
   850                         emit(smapper, this, "@1 += @2;",
   851                              lmapper.getI(varIndx),
   852                              Integer.toString(incrBy));
   853                     }
   854                     break;
   855                 }
   856                 case opc_return:
   857                     emit(smapper, this, "return;");
   858                     break;
   859                 case opc_ireturn:
   860                     emit(smapper, this, "return @1;", smapper.popI());
   861                     break;
   862                 case opc_lreturn:
   863                     emit(smapper, this, "return @1;", smapper.popL());
   864                     break;
   865                 case opc_freturn:
   866                     emit(smapper, this, "return @1;", smapper.popF());
   867                     break;
   868                 case opc_dreturn:
   869                     emit(smapper, this, "return @1;", smapper.popD());
   870                     break;
   871                 case opc_areturn:
   872                     emit(smapper, this, "return @1;", smapper.popA());
   873                     break;
   874                 case opc_i2l:
   875                     smapper.replace(this, VarType.LONG, "@1", smapper.getI(0));
   876                     break;
   877                 case opc_i2f:
   878                     smapper.replace(this, VarType.FLOAT, "@1", smapper.getI(0));
   879                     break;
   880                 case opc_i2d:
   881                     smapper.replace(this, VarType.DOUBLE, "@1", smapper.getI(0));
   882                     break;
   883                 case opc_l2i:
   884                     smapper.replace(this, VarType.INTEGER, "(@1).toInt32()", smapper.getL(0));
   885                     break;
   886                     // max int check?
   887                 case opc_l2f:
   888                     smapper.replace(this, VarType.FLOAT, "(@1).toFP()", smapper.getL(0));
   889                     break;
   890                 case opc_l2d:
   891                     smapper.replace(this, VarType.DOUBLE, "(@1).toFP()", smapper.getL(0));
   892                     break;
   893                 case opc_f2d:
   894                     smapper.replace(this, VarType.DOUBLE, "@1",
   895                          smapper.getF(0));
   896                     break;
   897                 case opc_d2f:
   898                     smapper.replace(this, VarType.FLOAT, "@1",
   899                          smapper.getD(0));
   900                     break;
   901                 case opc_f2i:
   902                     smapper.replace(this, VarType.INTEGER, "(@1).toInt32()",
   903                          smapper.getF(0));
   904                     break;
   905                 case opc_f2l:
   906                     smapper.replace(this, VarType.LONG, "(@1).toLong()",
   907                          smapper.getF(0));
   908                     break;
   909                 case opc_d2i:
   910                     smapper.replace(this, VarType.INTEGER, "(@1).toInt32()",
   911                          smapper.getD(0));
   912                     break;
   913                 case opc_d2l:
   914                     smapper.replace(this, VarType.LONG, "(@1).toLong()", smapper.getD(0));
   915                     break;
   916                 case opc_i2b:
   917                     smapper.replace(this, VarType.INTEGER, "(@1).toInt8()", smapper.getI(0));
   918                     break;
   919                 case opc_i2c:
   920                 case opc_i2s:
   921                     smapper.replace(this, VarType.INTEGER, "(@1).toInt16()", smapper.getI(0));
   922                     break;
   923                 case opc_aconst_null:
   924                     smapper.assign(this, VarType.REFERENCE, "null");
   925                     break;
   926                 case opc_iconst_m1:
   927                     smapper.assign(this, VarType.INTEGER, "-1");
   928                     break;
   929                 case opc_iconst_0:
   930                     smapper.assign(this, VarType.INTEGER, "0");
   931                     break;
   932                 case opc_dconst_0:
   933                     smapper.assign(this, VarType.DOUBLE, "0");
   934                     break;
   935                 case opc_lconst_0:
   936                     smapper.assign(this, VarType.LONG, "0");
   937                     break;
   938                 case opc_fconst_0:
   939                     smapper.assign(this, VarType.FLOAT, "0");
   940                     break;
   941                 case opc_iconst_1:
   942                     smapper.assign(this, VarType.INTEGER, "1");
   943                     break;
   944                 case opc_lconst_1:
   945                     smapper.assign(this, VarType.LONG, "1");
   946                     break;
   947                 case opc_fconst_1:
   948                     smapper.assign(this, VarType.FLOAT, "1");
   949                     break;
   950                 case opc_dconst_1:
   951                     smapper.assign(this, VarType.DOUBLE, "1");
   952                     break;
   953                 case opc_iconst_2:
   954                     smapper.assign(this, VarType.INTEGER, "2");
   955                     break;
   956                 case opc_fconst_2:
   957                     smapper.assign(this, VarType.FLOAT, "2");
   958                     break;
   959                 case opc_iconst_3:
   960                     smapper.assign(this, VarType.INTEGER, "3");
   961                     break;
   962                 case opc_iconst_4:
   963                     smapper.assign(this, VarType.INTEGER, "4");
   964                     break;
   965                 case opc_iconst_5:
   966                     smapper.assign(this, VarType.INTEGER, "5");
   967                     break;
   968                 case opc_ldc: {
   969                     int indx = readUByte(byteCodes, ++i);
   970                     String v = encodeConstant(indx);
   971                     int type = VarType.fromConstantType(jc.getTag(indx));
   972                     smapper.assign(this, type, v);
   973                     break;
   974                 }
   975                 case opc_ldc_w:
   976                 case opc_ldc2_w: {
   977                     int indx = readUShortArg(byteCodes, i);
   978                     i += 2;
   979                     String v = encodeConstant(indx);
   980                     int type = VarType.fromConstantType(jc.getTag(indx));
   981                     if (type == VarType.LONG) {
   982                         final Long lv = new Long(v);
   983                         final int low = (int)(lv.longValue() & 0xFFFFFFFF);
   984                         final int hi = (int)(lv.longValue() >> 32);
   985                         if (hi == 0) {
   986                             smapper.assign(this, VarType.LONG, "0x" + Integer.toHexString(low));
   987                         } else {
   988                             smapper.assign(this, VarType.LONG,
   989                                 "0x" + Integer.toHexString(hi) + ".next32(0x" + 
   990                                     Integer.toHexString(low) + ")"
   991                             );
   992                         }
   993                     } else {
   994                         smapper.assign(this, type, v);
   995                     }
   996                     break;
   997                 }
   998                 case opc_lcmp:
   999                     smapper.replace(this, VarType.INTEGER, "(@2).compare64(@1)", smapper.popL(), smapper.getL(0));
  1000                     break;
  1001                 case opc_fcmpl:
  1002                 case opc_fcmpg:
  1003                     emit(smapper, this, "var @3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
  1004                          smapper.popF(), smapper.popF(), smapper.pushI());
  1005                     break;
  1006                 case opc_dcmpl:
  1007                 case opc_dcmpg:
  1008                     emit(smapper, this, "var @3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
  1009                          smapper.popD(), smapper.popD(), smapper.pushI());
  1010                     break;
  1011                 case opc_if_acmpeq:
  1012                     i = generateIf(smapper, byteCodes, i, smapper.popA(), smapper.popA(),
  1013                                    "===", topMostLabel);
  1014                     break;
  1015                 case opc_if_acmpne:
  1016                     i = generateIf(smapper, byteCodes, i, smapper.popA(), smapper.popA(),
  1017                                    "!==", topMostLabel);
  1018                     break;
  1019                 case opc_if_icmpeq:
  1020                     i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
  1021                                    "==", topMostLabel);
  1022                     break;
  1023                 case opc_ifeq: {
  1024                     int indx = i + readShortArg(byteCodes, i);
  1025                     emitIf(smapper, this, "if ((@1) == 0) ",
  1026                          smapper.popI(), i, indx, topMostLabel);
  1027                     i += 2;
  1028                     break;
  1029                 }
  1030                 case opc_ifne: {
  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_iflt: {
  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_ifle: {
  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_ifgt: {
  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_ifge: {
  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_ifnonnull: {
  1066                     int indx = i + readShortArg(byteCodes, i);
  1067                     emitIf(smapper, this, "if ((@1) !== null) ",
  1068                          smapper.popA(), i, indx, topMostLabel);
  1069                     i += 2;
  1070                     break;
  1071                 }
  1072                 case opc_ifnull: {
  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_if_icmpne:
  1080                     i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
  1081                                    "!=", topMostLabel);
  1082                     break;
  1083                 case opc_if_icmplt:
  1084                     i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
  1085                                    "<", topMostLabel);
  1086                     break;
  1087                 case opc_if_icmple:
  1088                     i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
  1089                                    "<=", topMostLabel);
  1090                     break;
  1091                 case opc_if_icmpgt:
  1092                     i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
  1093                                    ">", topMostLabel);
  1094                     break;
  1095                 case opc_if_icmpge:
  1096                     i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
  1097                                    ">=", topMostLabel);
  1098                     break;
  1099                 case opc_goto: {
  1100                     smapper.flush(this);
  1101                     int indx = i + readShortArg(byteCodes, i);
  1102                     goTo(this, i, indx, topMostLabel);
  1103                     i += 2;
  1104                     break;
  1105                 }
  1106                 case opc_lookupswitch: {
  1107                     i = generateLookupSwitch(i, byteCodes, smapper, topMostLabel);
  1108                     break;
  1109                 }
  1110                 case opc_tableswitch: {
  1111                     i = generateTableSwitch(i, byteCodes, smapper, topMostLabel);
  1112                     break;
  1113                 }
  1114                 case opc_invokeinterface: {
  1115                     i = invokeVirtualMethod(byteCodes, i, smapper) + 2;
  1116                     break;
  1117                 }
  1118                 case opc_invokevirtual:
  1119                     i = invokeVirtualMethod(byteCodes, i, smapper);
  1120                     break;
  1121                 case opc_invokespecial:
  1122                     i = invokeStaticMethod(byteCodes, i, smapper, false);
  1123                     break;
  1124                 case opc_invokestatic:
  1125                     i = invokeStaticMethod(byteCodes, i, smapper, true);
  1126                     break;
  1127                 case opc_invokedynamic: {
  1128                     int indx = readUShortArg(byteCodes, i);
  1129                     println("invoke dynamic: " + indx);
  1130                     ByteCodeParser.CPX2 c2 = jc.getCpoolEntry(indx);
  1131                     BootMethodData bm = jc.getBootMethod(c2.cpx1);
  1132                     CPX2 methodHandle = jc.getCpoolEntry(bm.method);
  1133                     println("  type: " + methodHandle.cpx1);
  1134                     String[] mi = jc.getFieldInfoName(methodHandle.cpx2);
  1135                     String mcn = mangleClassName(mi[0]);
  1136                     char[] returnType = {'V'};
  1137                     StringBuilder cnt = new StringBuilder();
  1138                     String mn = findMethodName(mi, cnt, returnType);
  1139                     StringBuilder sb = new StringBuilder();
  1140                     sb.append("We don't handle invokedynamic, need to preprocess ahead-of-time:\n");
  1141                     sb.append("  mi[0]: ").append(mi[0]).append("\n");
  1142                     sb.append("  mi[1]: ").append(mi[1]).append("\n");
  1143                     sb.append("  mi[2]: ").append(mi[2]).append("\n");
  1144                     sb.append("  mn   : ").append(mn).append("\n");
  1145                     sb.append("  name and type: ").append(jc.stringValue(c2.cpx2, true)).append("\n");
  1146                     throw new IOException(sb.toString());
  1147                     /*
  1148                     CPX2 nameAndType = jc.getCpoolEntry(c2.cpx2);
  1149                     String type = jc.StringValue(nameAndType.cpx2);
  1150                     String object = accessClass(mcn) + "(false)";
  1151                     if (mn.startsWith("cons_")) {
  1152                         object += ".constructor";
  1153                     }
  1154                     append("var metHan = ");
  1155                     append(accessStaticMethod(object, mn, mi));
  1156                     append('(');
  1157                     String lookup = accessClass("java_lang_invoke_MethodHandles") + "(false).findFor__Ljava_lang_invoke_MethodHandles$Lookup_2Ljava_lang_Class_2(CLS.$class)";
  1158                     append(lookup);
  1159                     append(", '").append(mi[1]).append("', ");
  1160                     String methodType = accessClass("java_lang_invoke_MethodType") + "(false).fromMethodDescriptorString__Ljava_lang_invoke_MethodType_2Ljava_lang_String_2Ljava_lang_ClassLoader_2(";
  1161                     append(methodType).append("'").append(type).append("', null)");
  1162 //                    if (numArguments > 0) {
  1163 //                        append(vars[0]);
  1164 //                        for (int j = 1; j < numArguments; ++j) {
  1165 //                            append(", ");
  1166 //                            append(vars[j]);
  1167 //                        }
  1168 //                    }
  1169                     append(");");
  1170                     emit(smapper, this, "throw 'Invoke dynamic: ' + @1 + ': ' + metHan;", "" + indx);
  1171                     i += 4;
  1172                     break;
  1173                     */
  1174                 }
  1175                 case opc_new: {
  1176                     int indx = readUShortArg(byteCodes, i);
  1177                     String ci = jc.getClassName(indx);
  1178                     emit(smapper, this, "var @1 = new @2;",
  1179                          smapper.pushA(), accessClass(mangleClassName(ci)));
  1180                     addReference(ci);
  1181                     i += 2;
  1182                     break;
  1183                 }
  1184                 case opc_newarray:
  1185                     int atype = readUByte(byteCodes, ++i);
  1186                     generateNewArray(atype, smapper);
  1187                     break;
  1188                 case opc_anewarray: {
  1189                     int type = readUShortArg(byteCodes, i);
  1190                     i += 2;
  1191                     generateANewArray(type, smapper);
  1192                     break;
  1193                 }
  1194                 case opc_multianewarray: {
  1195                     int type = readUShortArg(byteCodes, i);
  1196                     i += 2;
  1197                     i = generateMultiANewArray(type, byteCodes, i, smapper);
  1198                     break;
  1199                 }
  1200                 case opc_arraylength:
  1201                     smapper.replace(this, VarType.INTEGER, "(@1).length", smapper.getA(0));
  1202                     break;
  1203                 case opc_lastore:
  1204                     emit(smapper, this, "Array.at(@3, @2, @1);",
  1205                          smapper.popL(), smapper.popI(), smapper.popA());
  1206                     break;
  1207                 case opc_fastore:
  1208                     emit(smapper, this, "Array.at(@3, @2, @1);",
  1209                          smapper.popF(), smapper.popI(), smapper.popA());
  1210                     break;
  1211                 case opc_dastore:
  1212                     emit(smapper, this, "Array.at(@3, @2, @1);",
  1213                          smapper.popD(), smapper.popI(), smapper.popA());
  1214                     break;
  1215                 case opc_aastore:
  1216                     emit(smapper, this, "Array.at(@3, @2, @1);",
  1217                          smapper.popA(), smapper.popI(), smapper.popA());
  1218                     break;
  1219                 case opc_iastore:
  1220                 case opc_bastore:
  1221                 case opc_castore:
  1222                 case opc_sastore:
  1223                     emit(smapper, this, "Array.at(@3, @2, @1);",
  1224                          smapper.popI(), smapper.popI(), smapper.popA());
  1225                     break;
  1226                 case opc_laload:
  1227                     smapper.replace(this, VarType.LONG, "Array.at(@2, @1)",
  1228                          smapper.popI(), smapper.getA(0));
  1229                     break;
  1230                 case opc_faload:
  1231                     smapper.replace(this, VarType.FLOAT, "Array.at(@2, @1)",
  1232                          smapper.popI(), smapper.getA(0));
  1233                     break;
  1234                 case opc_daload:
  1235                     smapper.replace(this, VarType.DOUBLE, "Array.at(@2, @1)",
  1236                          smapper.popI(), smapper.getA(0));
  1237                     break;
  1238                 case opc_aaload:
  1239                     smapper.replace(this, VarType.REFERENCE, "Array.at(@2, @1)",
  1240                          smapper.popI(), smapper.getA(0));
  1241                     break;
  1242                 case opc_iaload:
  1243                 case opc_baload:
  1244                 case opc_caload:
  1245                 case opc_saload:
  1246                     smapper.replace(this, VarType.INTEGER, "Array.at(@2, @1)",
  1247                          smapper.popI(), smapper.getA(0));
  1248                     break;
  1249                 case opc_pop:
  1250                 case opc_pop2:
  1251                     smapper.pop(1);
  1252                     debug("/* pop */");
  1253                     break;
  1254                 case opc_dup: {
  1255                     final Variable v = smapper.get(0);
  1256                     if (smapper.isDirty()) {
  1257                         emit(smapper, this, "var @1 = @2;", smapper.pushT(v.getType()), v);
  1258                     } else {
  1259                         smapper.assign(this, v.getType(), v);
  1260                     }   
  1261                     break;
  1262                 }
  1263                 case opc_dup2: {
  1264                     final Variable vi1 = smapper.get(0);
  1265 
  1266                     if (vi1.isCategory2()) {
  1267                         emit(smapper, this, "var @1 = @2;",
  1268                              smapper.pushT(vi1.getType()), vi1);
  1269                     } else {
  1270                         final Variable vi2 = smapper.get(1);
  1271                         emit(smapper, this, "var @1 = @2, @3 = @4;",
  1272                              smapper.pushT(vi2.getType()), vi2,
  1273                              smapper.pushT(vi1.getType()), vi1);
  1274                     }
  1275                     break;
  1276                 }
  1277                 case opc_dup_x1: {
  1278                     final Variable vi1 = smapper.pop(this);
  1279                     final Variable vi2 = smapper.pop(this);
  1280                     final Variable vo3 = smapper.pushT(vi1.getType());
  1281                     final Variable vo2 = smapper.pushT(vi2.getType());
  1282                     final Variable vo1 = smapper.pushT(vi1.getType());
  1283 
  1284                     emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
  1285                          vo1, vi1, vo2, vi2, vo3, vo1);
  1286                     break;
  1287                 }
  1288                 case opc_dup2_x1: {
  1289                     final Variable vi1 = smapper.pop(this);
  1290                     final Variable vi2 = smapper.pop(this);
  1291 
  1292                     if (vi1.isCategory2()) {
  1293                         final Variable vo3 = smapper.pushT(vi1.getType());
  1294                         final Variable vo2 = smapper.pushT(vi2.getType());
  1295                         final Variable vo1 = smapper.pushT(vi1.getType());
  1296 
  1297                         emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
  1298                              vo1, vi1, vo2, vi2, vo3, vo1);
  1299                     } else {
  1300                         final Variable vi3 = smapper.pop(this);
  1301                         final Variable vo5 = smapper.pushT(vi2.getType());
  1302                         final Variable vo4 = smapper.pushT(vi1.getType());
  1303                         final Variable vo3 = smapper.pushT(vi3.getType());
  1304                         final Variable vo2 = smapper.pushT(vi2.getType());
  1305                         final Variable vo1 = smapper.pushT(vi1.getType());
  1306 
  1307                         emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
  1308                              vo1, vi1, vo2, vi2, vo3, vi3);
  1309                         emit(smapper, this, " @1 = @2, @3 = @4;",
  1310                              vo4, vo1, vo5, vo2);
  1311                     }
  1312                     break;
  1313                 }
  1314                 case opc_dup_x2: {
  1315                     final Variable vi1 = smapper.pop(this);
  1316                     final Variable vi2 = smapper.pop(this);
  1317 
  1318                     if (vi2.isCategory2()) {
  1319                         final Variable vo3 = smapper.pushT(vi1.getType());
  1320                         final Variable vo2 = smapper.pushT(vi2.getType());
  1321                         final Variable vo1 = smapper.pushT(vi1.getType());
  1322 
  1323                         emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
  1324                              vo1, vi1, vo2, vi2, vo3, vo1);
  1325                     } else {
  1326                         final Variable vi3 = smapper.pop(this);
  1327                         final Variable vo4 = smapper.pushT(vi1.getType());
  1328                         final Variable vo3 = smapper.pushT(vi3.getType());
  1329                         final Variable vo2 = smapper.pushT(vi2.getType());
  1330                         final Variable vo1 = smapper.pushT(vi1.getType());
  1331 
  1332                         emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
  1333                              vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
  1334                     }
  1335                     break;
  1336                 }
  1337                 case opc_dup2_x2: {
  1338                     final Variable vi1 = smapper.pop(this);
  1339                     final Variable vi2 = smapper.pop(this);
  1340 
  1341                     if (vi1.isCategory2()) {
  1342                         if (vi2.isCategory2()) {
  1343                             final Variable vo3 = smapper.pushT(vi1.getType());
  1344                             final Variable vo2 = smapper.pushT(vi2.getType());
  1345                             final Variable vo1 = smapper.pushT(vi1.getType());
  1346 
  1347                             emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
  1348                                  vo1, vi1, vo2, vi2, vo3, vo1);
  1349                         } else {
  1350                             final Variable vi3 = smapper.pop(this);
  1351                             final Variable vo4 = smapper.pushT(vi1.getType());
  1352                             final Variable vo3 = smapper.pushT(vi3.getType());
  1353                             final Variable vo2 = smapper.pushT(vi2.getType());
  1354                             final Variable vo1 = smapper.pushT(vi1.getType());
  1355 
  1356                             emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
  1357                                  vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
  1358                         }
  1359                     } else {
  1360                         final Variable vi3 = smapper.pop(this);
  1361 
  1362                         if (vi3.isCategory2()) {
  1363                             final Variable vo5 = smapper.pushT(vi2.getType());
  1364                             final Variable vo4 = smapper.pushT(vi1.getType());
  1365                             final Variable vo3 = smapper.pushT(vi3.getType());
  1366                             final Variable vo2 = smapper.pushT(vi2.getType());
  1367                             final Variable vo1 = smapper.pushT(vi1.getType());
  1368 
  1369                             emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
  1370                                  vo1, vi1, vo2, vi2, vo3, vi3);
  1371                             emit(smapper, this, " @1 = @2, @3 = @4;",
  1372                                  vo4, vo1, vo5, vo2);
  1373                         } else {
  1374                             final Variable vi4 = smapper.pop(this);
  1375                             final Variable vo6 = smapper.pushT(vi2.getType());
  1376                             final Variable vo5 = smapper.pushT(vi1.getType());
  1377                             final Variable vo4 = smapper.pushT(vi4.getType());
  1378                             final Variable vo3 = smapper.pushT(vi3.getType());
  1379                             final Variable vo2 = smapper.pushT(vi2.getType());
  1380                             final Variable vo1 = smapper.pushT(vi1.getType());
  1381                             
  1382                             emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8,",
  1383                                  vo1, vi1, vo2, vi2, vo3, vi3, vo4, vi4);
  1384                             emit(smapper, this, " @1 = @2, @3 = @4;",
  1385                                  vo5, vo1, vo6, vo2);
  1386                         }
  1387                     }
  1388                     break;
  1389                 }
  1390                 case opc_swap: {
  1391                     final Variable vi1 = smapper.get(0);
  1392                     final Variable vi2 = smapper.get(1);
  1393 
  1394                     if (vi1.getType() == vi2.getType()) {
  1395                         final Variable tmp = smapper.pushT(vi1.getType());
  1396 
  1397                         emit(smapper, this, "var @1 = @2, @2 = @3, @3 = @1;",
  1398                              tmp, vi1, vi2);
  1399                         smapper.pop(1);
  1400                     } else {
  1401                         smapper.pop(2);
  1402                         smapper.pushT(vi1.getType());
  1403                         smapper.pushT(vi2.getType());
  1404                     }
  1405                     break;
  1406                 }
  1407                 case opc_bipush:
  1408                     smapper.assign(this, VarType.INTEGER, 
  1409                         "(" + Integer.toString(byteCodes[++i]) + ")");
  1410                     break;
  1411                 case opc_sipush:
  1412                     smapper.assign(this, VarType.INTEGER, 
  1413                         "(" + Integer.toString(readShortArg(byteCodes, i)) + ")"
  1414                     );
  1415                     i += 2;
  1416                     break;
  1417                 case opc_getfield: {
  1418                     int indx = readUShortArg(byteCodes, i);
  1419                     String[] fi = jc.getFieldInfoName(indx);
  1420                     final int type = VarType.fromFieldType(fi[2].charAt(0));
  1421                     final String mangleClass = mangleClassName(fi[0]);
  1422                     final String mangleClassAccess = accessClassFalse(mangleClass);
  1423                     smapper.replace(this, type, "@2.call(@1)",
  1424                          smapper.getA(0),
  1425                          accessField(mangleClassAccess,
  1426                                      "_" + fi[1], fi)
  1427                     );
  1428                     i += 2;
  1429                     addReference(fi[0]);
  1430                     break;
  1431                 }
  1432                 case opc_putfield: {
  1433                     int indx = readUShortArg(byteCodes, i);
  1434                     String[] fi = jc.getFieldInfoName(indx);
  1435                     final int type = VarType.fromFieldType(fi[2].charAt(0));
  1436                     final String mangleClass = mangleClassName(fi[0]);
  1437                     final String mangleClassAccess = accessClassFalse(mangleClass);
  1438                     emit(smapper, this, "@3.call(@2, @1);",
  1439                          smapper.popT(type),
  1440                          smapper.popA(),
  1441                          accessField(mangleClassAccess,
  1442                                      "_" + fi[1], fi));
  1443                     i += 2;
  1444                     addReference(fi[0]);
  1445                     break;
  1446                 }
  1447                 case opc_getstatic: {
  1448                     int indx = readUShortArg(byteCodes, i);
  1449                     String[] fi = jc.getFieldInfoName(indx);
  1450                     final int type = VarType.fromFieldType(fi[2].charAt(0));
  1451                     String ac = accessClassFalse(mangleClassName(fi[0]));
  1452                     String af = accessField(ac, "_" + fi[1], fi);
  1453                     smapper.assign(this, type, af + "()");
  1454                     i += 2;
  1455                     addReference(fi[0]);
  1456                     break;
  1457                 }
  1458                 case opc_putstatic: {
  1459                     int indx = readUShortArg(byteCodes, i);
  1460                     String[] fi = jc.getFieldInfoName(indx);
  1461                     final int type = VarType.fromFieldType(fi[2].charAt(0));
  1462                     emit(smapper, this, "@1._@2(@3);",
  1463                          accessClassFalse(mangleClassName(fi[0])), fi[1],
  1464                          smapper.popT(type));
  1465                     i += 2;
  1466                     addReference(fi[0]);
  1467                     break;
  1468                 }
  1469                 case opc_checkcast: {
  1470                     int indx = readUShortArg(byteCodes, i);
  1471                     generateCheckcast(indx, smapper);
  1472                     i += 2;
  1473                     break;
  1474                 }
  1475                 case opc_instanceof: {
  1476                     int indx = readUShortArg(byteCodes, i);
  1477                     generateInstanceOf(indx, smapper);
  1478                     i += 2;
  1479                     break;
  1480                 }
  1481                 case opc_athrow: {
  1482                     final CharSequence v = smapper.popA();
  1483                     smapper.clear();
  1484 
  1485                     emit(smapper, this, "{ var @1 = @2; throw @2; }",
  1486                          smapper.pushA(), v);
  1487                     break;
  1488                 }
  1489 
  1490                 case opc_monitorenter: {
  1491                     debug("/* monitor enter */");
  1492                     smapper.popA();
  1493                     break;
  1494                 }
  1495 
  1496                 case opc_monitorexit: {
  1497                     debug("/* monitor exit */");
  1498                     smapper.popA();
  1499                     break;
  1500                 }
  1501 
  1502                 case opc_wide:
  1503                     wide = true;
  1504                     break;
  1505 
  1506                 default: {
  1507                     wide = false;
  1508                     emit(smapper, this, "throw 'unknown bytecode @1';",
  1509                          Integer.toString(c));
  1510                 }
  1511             }
  1512             if (debug(" //")) {
  1513                 generateByteCodeComment(prev, i, byteCodes);
  1514             }
  1515             if (outChanged) {
  1516                 append("\n");
  1517             }
  1518         }
  1519         if (previousTrap != null) {
  1520             generateCatch(previousTrap, byteCodes.length, topMostLabel);
  1521         }
  1522         if (didBranches) {
  1523             append("\n    }\n");
  1524         }
  1525         while (openBraces-- > 0) {
  1526             append('}');
  1527         }
  1528         if (defineProp) {
  1529             append("\n}});");
  1530         } else {
  1531             append("\n};");
  1532         }
  1533         return defineProp;
  1534     }
  1535 
  1536     private int generateIf(StackMapper mapper, byte[] byteCodes, 
  1537         int i, final CharSequence v2, final CharSequence v1, 
  1538         final String test, int topMostLabel
  1539     ) throws IOException {
  1540         mapper.flush(this);
  1541         int indx = i + readShortArg(byteCodes, i);
  1542         append("if ((").append(v1)
  1543            .append(") ").append(test).append(" (")
  1544            .append(v2).append(")) ");
  1545         goTo(this, i, indx, topMostLabel);
  1546         return i + 2;
  1547     }
  1548     
  1549     private int readInt4(byte[] byteCodes, int offset) {
  1550         final int d = byteCodes[offset + 0] << 24;
  1551         final int c = byteCodes[offset + 1] << 16;
  1552         final int b = byteCodes[offset + 2] << 8;
  1553         final int a = byteCodes[offset + 3];
  1554         return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
  1555     }
  1556     private static int readUByte(byte[] byteCodes, int offset) {
  1557         return byteCodes[offset] & 0xff;
  1558     }
  1559 
  1560     private static int readUShort(byte[] byteCodes, int offset) {
  1561         return ((byteCodes[offset] & 0xff) << 8)
  1562                     | (byteCodes[offset + 1] & 0xff);
  1563     }
  1564     private static int readUShortArg(byte[] byteCodes, int offsetInstruction) {
  1565         return readUShort(byteCodes, offsetInstruction + 1);
  1566     }
  1567 
  1568     private static int readShort(byte[] byteCodes, int offset) {
  1569         int signed = byteCodes[offset];
  1570         byte b0 = (byte)signed;
  1571         return (b0 << 8) | (byteCodes[offset + 1] & 0xff);
  1572     }
  1573     private static int readShortArg(byte[] byteCodes, int offsetInstruction) {
  1574         return readShort(byteCodes, offsetInstruction + 1);
  1575     }
  1576 
  1577     private static void countArgs(String descriptor, char[] returnType, StringBuilder sig, StringBuilder cnt) {
  1578         int i = 0;
  1579         Boolean count = null;
  1580         boolean array = false;
  1581         sig.append("__");
  1582         int firstPos = sig.length();
  1583         while (i < descriptor.length()) {
  1584             char ch = descriptor.charAt(i++);
  1585             switch (ch) {
  1586                 case '(':
  1587                     count = true;
  1588                     continue;
  1589                 case ')':
  1590                     count = false;
  1591                     continue;
  1592                 case 'B': 
  1593                 case 'C': 
  1594                 case 'D': 
  1595                 case 'F': 
  1596                 case 'I': 
  1597                 case 'J': 
  1598                 case 'S': 
  1599                 case 'Z': 
  1600                     if (count) {
  1601                         if (array) {
  1602                             sig.append("_3");
  1603                         }
  1604                         sig.append(ch);
  1605                         if (ch == 'J' || ch == 'D') {
  1606                             cnt.append('1');
  1607                         } else {
  1608                             cnt.append('0');
  1609                         }
  1610                     } else {
  1611                         sig.insert(firstPos, ch);
  1612                         if (array) {
  1613                             returnType[0] = '[';
  1614                             sig.insert(firstPos, "_3");
  1615                         } else {
  1616                             returnType[0] = ch;
  1617                         }
  1618                     }
  1619                     array = false;
  1620                     continue;
  1621                 case 'V': 
  1622                     assert !count;
  1623                     returnType[0] = 'V';
  1624                     sig.insert(firstPos, 'V');
  1625                     continue;
  1626                 case 'L':
  1627                     int next = descriptor.indexOf(';', i);
  1628                     String realSig = mangleSig(descriptor, i - 1, next + 1);
  1629                     if (count) {
  1630                         if (array) {
  1631                             sig.append("_3");
  1632                         }
  1633                         sig.append(realSig);
  1634                         cnt.append('0');
  1635                     } else {
  1636                         sig.insert(firstPos, realSig);
  1637                         if (array) {
  1638                             sig.insert(firstPos, "_3");
  1639                         }
  1640                         returnType[0] = 'L';
  1641                     }
  1642                     i = next + 1;
  1643                     array = false;
  1644                     continue;
  1645                 case '[':
  1646                     array = true;
  1647                     continue;
  1648                 default:
  1649                     throw new IllegalStateException("Invalid char: " + ch);
  1650             }
  1651         }
  1652     }
  1653     
  1654     static String mangleSig(String sig) {
  1655         return mangleSig(sig, 0, sig.length());
  1656     }
  1657     
  1658     private static String mangleMethodName(String name) {
  1659         StringBuilder sb = new StringBuilder(name.length() * 2);
  1660         int last = name.length();
  1661         for (int i = 0; i < last; i++) {
  1662             final char ch = name.charAt(i);
  1663             switch (ch) {
  1664                 case '_': sb.append("_1"); break;
  1665                 default: sb.append(ch); break;
  1666             }
  1667         }
  1668         return sb.toString();
  1669     }
  1670     private static String mangleSig(String txt, int first, int last) {
  1671         StringBuilder sb = new StringBuilder((last - first) * 2);
  1672         for (int i = first; i < last; i++) {
  1673             final char ch = txt.charAt(i);
  1674             switch (ch) {
  1675                 case '/': sb.append('_'); break;
  1676                 case '_': sb.append("_1"); break;
  1677                 case ';': sb.append("_2"); break;
  1678                 case '[': sb.append("_3"); break;
  1679                 default: 
  1680                     if (Character.isJavaIdentifierPart(ch)) {
  1681                         sb.append(ch);
  1682                     } else {
  1683                         sb.append("_0");
  1684                         String hex = Integer.toHexString(ch).toLowerCase();
  1685                         for (int m = hex.length(); m < 4; m++) {
  1686                             sb.append("0");
  1687                         }
  1688                         sb.append(hex);
  1689                     }
  1690                 break;
  1691             }
  1692         }
  1693         return sb.toString();
  1694     }
  1695     
  1696     private static String mangleClassName(String name) {
  1697         return mangleSig(name);
  1698     }
  1699 
  1700     private static String findMethodName(MethodData m, StringBuilder cnt) {
  1701         StringBuilder name = new StringBuilder();
  1702         if ("<init>".equals(m.getName())) { // NOI18N
  1703             name.append("cons"); // NOI18N
  1704         } else if ("<clinit>".equals(m.getName())) { // NOI18N
  1705             name.append("class"); // NOI18N
  1706         } else {
  1707             name.append(mangleMethodName(m.getName()));
  1708         } 
  1709         
  1710         countArgs(m.getInternalSig(), new char[1], name, cnt);
  1711         return name.toString();
  1712     }
  1713 
  1714     static String findMethodName(String[] mi, StringBuilder cnt, char[] returnType) {
  1715         StringBuilder name = new StringBuilder();
  1716         String descr = mi[2];//mi.getDescriptor();
  1717         String nm= mi[1];
  1718         if ("<init>".equals(nm)) { // NOI18N
  1719             name.append("cons"); // NOI18N
  1720         } else {
  1721             name.append(mangleMethodName(nm));
  1722         }
  1723         countArgs(descr, returnType, name, cnt);
  1724         return name.toString();
  1725     }
  1726 
  1727     private int invokeStaticMethod(byte[] byteCodes, int i, final StackMapper mapper, boolean isStatic)
  1728     throws IOException {
  1729         int methodIndex = readUShortArg(byteCodes, i);
  1730         String[] mi = jc.getFieldInfoName(methodIndex);
  1731         char[] returnType = { 'V' };
  1732         StringBuilder cnt = new StringBuilder();
  1733         String mn = findMethodName(mi, cnt, returnType);
  1734         
  1735         final int numArguments = isStatic ? cnt.length() : cnt.length() + 1;
  1736         final CharSequence[] vars = new CharSequence[numArguments];
  1737 
  1738         for (int j = numArguments - 1; j >= 0; --j) {
  1739             vars[j] = mapper.popValue();
  1740         }
  1741 
  1742         if ((
  1743             "newUpdater__Ljava_util_concurrent_atomic_AtomicIntegerFieldUpdater_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
  1744             && "java/util/concurrent/atomic/AtomicIntegerFieldUpdater".equals(mi[0])
  1745         ) || (
  1746             "newUpdater__Ljava_util_concurrent_atomic_AtomicLongFieldUpdater_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
  1747             && "java/util/concurrent/atomic/AtomicLongFieldUpdater".equals(mi[0])
  1748         )) {
  1749             if (vars[1] instanceof String) {
  1750                 String field = vars[1].toString();
  1751                 if (field.length() > 2 && field.charAt(0) == '"' && field.charAt(field.length() - 1) == '"') {
  1752                     vars[1] = "c._" + field.substring(1, field.length() - 1);
  1753                 }
  1754             }
  1755         }
  1756         if (
  1757             "newUpdater__Ljava_util_concurrent_atomic_AtomicReferenceFieldUpdater_2Ljava_lang_Class_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
  1758             && "java/util/concurrent/atomic/AtomicReferenceFieldUpdater".equals(mi[0])
  1759         ) {
  1760             if (vars[1] instanceof String) {
  1761                 String field = vars[2].toString();
  1762                 if (field.length() > 2 && field.charAt(0) == '"' && field.charAt(field.length() - 1) == '"') {
  1763                     vars[2] = "c._" + field.substring(1, field.length() - 1);
  1764                 }
  1765             }
  1766         }
  1767 
  1768         if (returnType[0] != 'V') {
  1769             mapper.flush(this);
  1770             append("var ")
  1771                .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
  1772                .append(" = ");
  1773         }
  1774 
  1775         final String in = mi[0];
  1776         String mcn;
  1777         if (callbacks && (
  1778             in.equals("org/apidesign/html/boot/spi/Fn") ||
  1779             in.equals("org/netbeans/html/boot/spi/Fn")
  1780         )) {
  1781             mcn = "java_lang_Class";
  1782         } else {
  1783             mcn = mangleClassName(in);
  1784         }
  1785         String object = accessClassFalse(mcn);
  1786         if (mn.startsWith("cons_")) {
  1787             object += ".constructor";
  1788         }
  1789         append(accessStaticMethod(object, mn, mi));
  1790         if (isStatic) {
  1791             append('(');
  1792         } else {
  1793             append(".call(");
  1794         }
  1795         if (numArguments > 0) {
  1796             append(vars[0]);
  1797             for (int j = 1; j < numArguments; ++j) {
  1798                 append(", ");
  1799                 append(vars[j]);
  1800             }
  1801         }
  1802         append(");");
  1803         i += 2;
  1804         addReference(in);
  1805         return i;
  1806     }
  1807     private int invokeVirtualMethod(byte[] byteCodes, int i, final StackMapper mapper)
  1808     throws IOException {
  1809         int methodIndex = readUShortArg(byteCodes, i);
  1810         String[] mi = jc.getFieldInfoName(methodIndex);
  1811         char[] returnType = { 'V' };
  1812         StringBuilder cnt = new StringBuilder();
  1813         String mn = findMethodName(mi, cnt, returnType);
  1814 
  1815         final int numArguments = cnt.length() + 1;
  1816         final CharSequence[] vars =  new CharSequence[numArguments];
  1817 
  1818         for (int j = numArguments - 1; j >= 0; --j) {
  1819             vars[j] = mapper.popValue();
  1820         }
  1821 
  1822         if (returnType[0] != 'V') {
  1823             mapper.flush(this);
  1824             append("var ")
  1825                .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
  1826                .append(" = ");
  1827         }
  1828 
  1829         append(accessVirtualMethod(vars[0].toString(), mn, mi, numArguments));
  1830         String sep = "";
  1831         for (int j = 1; j < numArguments; ++j) {
  1832             append(sep);
  1833             append(vars[j]);
  1834             sep = ", ";
  1835         }
  1836         append(");");
  1837         i += 2;
  1838         return i;
  1839     }
  1840 
  1841     private void addReference(String cn) throws IOException {
  1842         if (requireReference(cn)) {
  1843             debug(" /* needs " + cn + " */");
  1844         }
  1845     }
  1846 
  1847     private void outType(String d, StringBuilder out) {
  1848         int arr = 0;
  1849         while (d.charAt(0) == '[') {
  1850             out.append('A');
  1851             d = d.substring(1);
  1852         }
  1853         if (d.charAt(0) == 'L') {
  1854             assert d.charAt(d.length() - 1) == ';';
  1855             out.append(mangleClassName(d).substring(0, d.length() - 1));
  1856         } else {
  1857             out.append(d);
  1858         }
  1859     }
  1860 
  1861     private String encodeConstant(int entryIndex) throws IOException {
  1862         String[] classRef = { null };
  1863         String s = jc.stringValue(entryIndex, classRef);
  1864         if (classRef[0] != null) {
  1865             if (classRef[0].startsWith("[")) {
  1866                 s = accessClass("java_lang_Class") + "(false)['forName__Ljava_lang_Class_2Ljava_lang_String_2']('" + classRef[0] + "')";
  1867             } else {
  1868                 addReference(classRef[0]);
  1869                 s = accessClassFalse(mangleClassName(s)) + ".constructor.$class";
  1870             }
  1871         }
  1872         return s;
  1873     }
  1874 
  1875     private String javaScriptBody(String destObject, MethodData m, boolean isStatic) throws IOException {
  1876         byte[] arr = m.findAnnotationData(true);
  1877         if (arr == null) {
  1878             return null;
  1879         }
  1880         final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
  1881         final String htmlType = "Lnet/java/html/js/JavaScriptBody;";
  1882         class P extends AnnotationParser {
  1883             public P() {
  1884                 super(false, true);
  1885             }
  1886             
  1887             int cnt;
  1888             String[] args = new String[30];
  1889             String body;
  1890             boolean javacall;
  1891             boolean html4j;
  1892             
  1893             @Override
  1894             protected void visitAttr(String type, String attr, String at, String value) {
  1895                 if (type.equals(jvmType)) {
  1896                     if ("body".equals(attr)) {
  1897                         body = value;
  1898                     } else if ("args".equals(attr)) {
  1899                         args[cnt++] = value;
  1900                     } else {
  1901                         throw new IllegalArgumentException(attr);
  1902                     }
  1903                 }
  1904                 if (type.equals(htmlType)) {
  1905                     html4j = true;
  1906                     if ("body".equals(attr)) {
  1907                         body = value;
  1908                     } else if ("args".equals(attr)) {
  1909                         args[cnt++] = value;
  1910                     } else if ("javacall".equals(attr)) {
  1911                         javacall = "1".equals(value);
  1912                     } else if ("wait4js".equals(attr)) {
  1913                         // ignore, we always invoke synchronously
  1914                     } else {
  1915                         throw new IllegalArgumentException(attr);
  1916                     }
  1917                 }
  1918             }
  1919         }
  1920         P p = new P();
  1921         p.parse(arr, jc);
  1922         if (p.body == null) {
  1923             return null;
  1924         }
  1925         StringBuilder cnt = new StringBuilder();
  1926         final String mn = findMethodName(m, cnt);
  1927         append("m = ").append(destObject).append(".").append(mn);
  1928         append(" = function(");
  1929         String space = "";
  1930         int index = 0;
  1931         StringBuilder toValue = new StringBuilder();
  1932         for (int i = 0; i < cnt.length(); i++) {
  1933             append(space);
  1934             space = outputArg(this, p.args, index);
  1935             if (p.html4j && space.length() > 0) {
  1936                 toValue.append("\n  ").append(p.args[index]).append(" = ")
  1937                     .append(accessClass("java_lang_Class")).append("(false).toJS(").
  1938                     append(p.args[index]).append(");");
  1939             }
  1940             index++;
  1941         }
  1942         append(") {").append("\n");
  1943         append(toValue.toString());
  1944         if (p.javacall) {
  1945             int lastSlash = jc.getClassName().lastIndexOf('/');
  1946             final String pkg = jc.getClassName().substring(0, lastSlash);
  1947             append(mangleCallbacks(pkg, p.body));
  1948             requireReference(pkg + "/$JsCallbacks$");
  1949         } else {
  1950             append(p.body);
  1951         }
  1952         append("\n}\n");
  1953         return mn;
  1954     }
  1955     
  1956     private static CharSequence mangleCallbacks(String pkgName, String body) {
  1957         StringBuilder sb = new StringBuilder();
  1958         int pos = 0;
  1959         for (;;) {
  1960             int next = body.indexOf(".@", pos);
  1961             if (next == -1) {
  1962                 sb.append(body.substring(pos));
  1963                 body = sb.toString();
  1964                 break;
  1965             }
  1966             int ident = next;
  1967             while (ident > 0) {
  1968                 if (!Character.isJavaIdentifierPart(body.charAt(--ident))) {
  1969                     ident++;
  1970                     break;
  1971                 }
  1972             }
  1973             String refId = body.substring(ident, next);
  1974 
  1975             sb.append(body.substring(pos, ident));
  1976 
  1977             int sigBeg = body.indexOf('(', next);
  1978             int sigEnd = body.indexOf(')', sigBeg);
  1979             int colon4 = body.indexOf("::", next);
  1980             if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
  1981                 throw new IllegalStateException("Malformed body " + body);
  1982             }
  1983             String fqn = body.substring(next + 2, colon4);
  1984             String method = body.substring(colon4 + 2, sigBeg);
  1985             String params = body.substring(sigBeg, sigEnd + 1);
  1986 
  1987             int paramBeg = body.indexOf('(', sigEnd + 1);
  1988             
  1989             sb.append("vm.").append(mangleClassName(pkgName)).append("_$JsCallbacks$(false)._VM().");
  1990             sb.append(mangleJsCallbacks(fqn, method, params, false));
  1991             sb.append("(").append(refId);
  1992             if (body.charAt(paramBeg + 1) != ')') {
  1993                 sb.append(",");
  1994             }
  1995             pos = paramBeg + 1;
  1996         }
  1997         sb = null;
  1998         pos = 0;
  1999         for (;;) {
  2000             int next = body.indexOf("@", pos);
  2001             if (next == -1) {
  2002                 if (sb == null) {
  2003                     return body;
  2004                 }
  2005                 sb.append(body.substring(pos));
  2006                 return sb;
  2007             }
  2008             if (sb == null) {
  2009                 sb = new StringBuilder();
  2010             }
  2011 
  2012             sb.append(body.substring(pos, next));
  2013 
  2014             int sigBeg = body.indexOf('(', next);
  2015             int sigEnd = body.indexOf(')', sigBeg);
  2016             int colon4 = body.indexOf("::", next);
  2017             if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
  2018                 throw new IllegalStateException("Malformed body " + body);
  2019             }
  2020             String fqn = body.substring(next + 1, colon4);
  2021             String method = body.substring(colon4 + 2, sigBeg);
  2022             String params = body.substring(sigBeg, sigEnd + 1);
  2023 
  2024             int paramBeg = body.indexOf('(', sigEnd + 1);
  2025             
  2026             sb.append("vm.").append(mangleClassName(pkgName)).append("_$JsCallbacks$(false)._VM().");
  2027             sb.append(mangleJsCallbacks(fqn, method, params, true));
  2028             sb.append("(");
  2029             pos = paramBeg + 1;
  2030         }
  2031     }
  2032 
  2033     static String mangleJsCallbacks(String fqn, String method, String params, boolean isStatic) {
  2034         if (params.startsWith("(")) {
  2035             params = params.substring(1);
  2036         }
  2037         if (params.endsWith(")")) {
  2038             params = params.substring(0, params.length() - 1);
  2039         }
  2040         StringBuilder sb = new StringBuilder();
  2041         final String fqnu = fqn.replace('.', '_');
  2042         final String rfqn = mangleClassName(fqnu);
  2043         final String rm = mangleMethodName(method);
  2044         final String srp;
  2045         {
  2046             StringBuilder pb = new StringBuilder();
  2047             int len = params.length();
  2048             int indx = 0;
  2049             while (indx < len) {
  2050                 char ch = params.charAt(indx);
  2051                 if (ch == '[' || ch == 'L') {
  2052                     int column = params.indexOf(';', indx) + 1;
  2053                     if (column > indx) {
  2054                         String real = params.substring(indx, column);
  2055                         if ("Ljava/lang/String;".equals(real)) {
  2056                             pb.append("Ljava/lang/String;");
  2057                             indx = column;
  2058                             continue;
  2059                         }
  2060                     }
  2061                     pb.append("Ljava/lang/Object;");
  2062                     indx = column;
  2063                 } else {
  2064                     pb.append(ch);
  2065                     indx++;
  2066                 }
  2067             }
  2068             srp = mangleSig(pb.toString());
  2069         }
  2070         final String rp = mangleSig(params);
  2071         final String mrp = mangleMethodName(rp);
  2072         sb.append(rfqn).append("$").append(rm).
  2073             append('$').append(mrp).append("__Ljava_lang_Object_2");
  2074         if (!isStatic) {
  2075             sb.append('L').append(fqnu).append("_2");
  2076         }
  2077         sb.append(srp);
  2078         return sb.toString();
  2079     }
  2080 
  2081     private static String className(ClassData jc) {
  2082         //return jc.getName().getInternalName().replace('/', '_');
  2083         return mangleClassName(jc.getClassName());
  2084     }
  2085     
  2086     private static String[] findAnnotation(
  2087         byte[] arr, ClassData cd, final String className, 
  2088         final String... attrNames
  2089     ) throws IOException {
  2090         if (arr == null) {
  2091             return null;
  2092         }
  2093         final String[] values = new String[attrNames.length];
  2094         final boolean[] found = { false };
  2095         final String jvmType = "L" + className.replace('.', '/') + ";";
  2096         AnnotationParser ap = new AnnotationParser(false, true) {
  2097             @Override
  2098             protected void visitAttr(String type, String attr, String at, String value) {
  2099                 if (type.equals(jvmType)) {
  2100                     found[0] = true;
  2101                     for (int i = 0; i < attrNames.length; i++) {
  2102                         if (attrNames[i].equals(attr)) {
  2103                             values[i] = value;
  2104                         }
  2105                     }
  2106                 }
  2107             }
  2108             
  2109         };
  2110         ap.parse(arr, cd);
  2111         return found[0] ? values : null;
  2112     }
  2113 
  2114     private CharSequence initField(FieldData v) {
  2115         final String is = v.getInternalSig();
  2116         if (is.length() == 1) {
  2117             switch (is.charAt(0)) {
  2118                 case 'S':
  2119                 case 'J':
  2120                 case 'B':
  2121                 case 'Z':
  2122                 case 'C':
  2123                 case 'I': return " = 0;";
  2124                 case 'F': 
  2125                 case 'D': return " = 0.0;";
  2126                 default:
  2127                     throw new IllegalStateException(is);
  2128             }
  2129         }
  2130         return " = null;";
  2131     }
  2132 
  2133     private void generateAnno(ClassData cd, byte[] data) throws IOException {
  2134         AnnotationParser ap = new AnnotationParser(true, false) {
  2135             int[] cnt = new int[32];
  2136             int depth;
  2137             
  2138             @Override
  2139             protected void visitAnnotationStart(String attrType, boolean top) throws IOException {
  2140                 final String slashType = attrType.substring(1, attrType.length() - 1);
  2141                 requireReference(slashType);
  2142                 
  2143                 if (cnt[depth]++ > 0) {
  2144                     append(",");
  2145                 }
  2146                 if (top) {
  2147                     append('"').append(attrType).append("\" : ");
  2148                 }
  2149                 append("{\n");
  2150                 cnt[++depth] = 0;
  2151             }
  2152 
  2153             @Override
  2154             protected void visitAnnotationEnd(String type, boolean top) throws IOException {
  2155                 append("\n}\n");
  2156                 depth--;
  2157             }
  2158 
  2159             @Override
  2160             protected void visitValueStart(String attrName, char type) throws IOException {
  2161                 if (cnt[depth]++ > 0) {
  2162                     append(",\n");
  2163                 }
  2164                 cnt[++depth] = 0;
  2165                 if (attrName != null) {
  2166                     append('"').append(attrName).append("\" : ");
  2167                 }
  2168                 if (type == '[') {
  2169                     append("[");
  2170                 }
  2171             }
  2172 
  2173             @Override
  2174             protected void visitValueEnd(String attrName, char type) throws IOException {
  2175                 if (type == '[') {
  2176                     append("]");
  2177                 }
  2178                 depth--;
  2179             }
  2180             
  2181             @Override
  2182             protected void visitAttr(String type, String attr, String attrType, String value) 
  2183             throws IOException {
  2184                 if (attr == null && value == null) {
  2185                     return;
  2186                 }
  2187                 append(value);
  2188             }
  2189 
  2190             @Override
  2191             protected void visitEnumAttr(String type, String attr, String attrType, String value) 
  2192             throws IOException {
  2193                 final String slashType = attrType.substring(1, attrType.length() - 1);
  2194                 requireReference(slashType);
  2195                 
  2196                 final String cn = mangleClassName(slashType);
  2197                 append(accessClassFalse(cn))
  2198                    .append("['valueOf__L").
  2199                     append(cn).
  2200                     append("_2Ljava_lang_String_2']('").
  2201                     append(value).
  2202                     append("')");
  2203             }
  2204         };
  2205         ap.parse(data, cd);
  2206     }
  2207 
  2208     private static String outputArg(Appendable out, String[] args, int indx) throws IOException {
  2209         final String name = args[indx];
  2210         if (name == null) {
  2211             return "";
  2212         }
  2213         if (name.contains(",")) {
  2214             throw new IOException("Wrong parameter with ',': " + name);
  2215         }
  2216         out.append(name);
  2217         return ",";
  2218     }
  2219 
  2220     final void emitNoFlush(
  2221         StackMapper sm, 
  2222         final String format, final CharSequence... params
  2223     ) throws IOException {
  2224         emitImpl(this, format, params);
  2225     }
  2226     static final void emit(
  2227         StackMapper sm, 
  2228         final Appendable out, 
  2229         final String format, final CharSequence... params
  2230     ) throws IOException {
  2231         sm.flush(out);
  2232         emitImpl(out, format, params);
  2233     }
  2234     static void emitImpl(final Appendable out,
  2235                              final String format,
  2236                              final CharSequence... params) throws IOException {
  2237         final int length = format.length();
  2238 
  2239         int processed = 0;
  2240         int paramOffset = format.indexOf('@');
  2241         while ((paramOffset != -1) && (paramOffset < (length - 1))) {
  2242             final char paramChar = format.charAt(paramOffset + 1);
  2243             if ((paramChar >= '1') && (paramChar <= '9')) {
  2244                 final int paramIndex = paramChar - '0' - 1;
  2245 
  2246                 out.append(format, processed, paramOffset);
  2247                 out.append(params[paramIndex]);
  2248 
  2249                 ++paramOffset;
  2250                 processed = paramOffset + 1;
  2251             }
  2252 
  2253             paramOffset = format.indexOf('@', paramOffset + 1);
  2254         }
  2255 
  2256         out.append(format, processed, length);
  2257     }
  2258 
  2259     private void generateCatch(TrapData[] traps, int current, int topMostLabel) throws IOException {
  2260         append("} catch (e) {\n");
  2261         int finallyPC = -1;
  2262         for (TrapData e : traps) {
  2263             if (e == null) {
  2264                 break;
  2265             }
  2266             if (e.catch_cpx != 0) { //not finally
  2267                 final String classInternalName = jc.getClassName(e.catch_cpx);
  2268                 addReference(classInternalName);
  2269                 append("e = vm.java_lang_Class(false).bck2BrwsrThrwrbl(e);");
  2270                 append("if (e['$instOf_" + mangleClassName(classInternalName) + "']) {");
  2271                 append("var stA0 = e;");
  2272                 goTo(this, current, e.handler_pc, topMostLabel);
  2273                 append("}\n");
  2274             } else {
  2275                 finallyPC = e.handler_pc;
  2276             }
  2277         }
  2278         if (finallyPC == -1) {
  2279             append("throw e;");
  2280         } else {
  2281             append("var stA0 = e;");
  2282             goTo(this, current, finallyPC, topMostLabel);
  2283         }
  2284         append("\n}");
  2285     }
  2286 
  2287     private static void goTo(Appendable out, int current, int to, int canBack) throws IOException {
  2288         if (to < current) {
  2289             if (canBack < to) {
  2290                 out.append("{ gt = 0; continue X_" + to + "; }");
  2291             } else {
  2292                 out.append("{ gt = " + to + "; continue X_0; }");
  2293             }
  2294         } else {
  2295             out.append("{ gt = " + to + "; break IF; }");
  2296         }
  2297     }
  2298 
  2299     private static void emitIf(
  2300         StackMapper sm, 
  2301         Appendable out, String pattern, 
  2302         CharSequence param, 
  2303         int current, int to, int canBack
  2304     ) throws IOException {
  2305         sm.flush(out);
  2306         emitImpl(out, pattern, param);
  2307         goTo(out, current, to, canBack);
  2308     }
  2309 
  2310     private void generateNewArray(int atype, final StackMapper smapper) throws IOException, IllegalStateException {
  2311         String jvmType;
  2312         switch (atype) {
  2313             case 4: jvmType = "[Z"; break;
  2314             case 5: jvmType = "[C"; break;
  2315             case 6: jvmType = "[F"; break;
  2316             case 7: jvmType = "[D"; break;
  2317             case 8: jvmType = "[B"; break;
  2318             case 9: jvmType = "[S"; break;
  2319             case 10: jvmType = "[I"; break;
  2320             case 11: jvmType = "[J"; break;
  2321             default: throw new IllegalStateException("Array type: " + atype);
  2322         }
  2323         emit(smapper, this, 
  2324             "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](true, '@3', null, @1);",
  2325              smapper.popI(), smapper.pushA(), jvmType);
  2326     }
  2327 
  2328     private void generateANewArray(int type, final StackMapper smapper) throws IOException {
  2329         String typeName = jc.getClassName(type);
  2330         String ref = "null";
  2331         if (typeName.startsWith("[")) {
  2332             typeName = "'[" + typeName + "'";
  2333         } else {
  2334             ref = "vm." + mangleClassName(typeName);
  2335             typeName = "'[L" + typeName + ";'";
  2336         }
  2337         emit(smapper, this,
  2338             "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](false, @3, @4, @1);",
  2339              smapper.popI(), smapper.pushA(), typeName, ref);
  2340     }
  2341 
  2342     private int generateMultiANewArray(int type, final byte[] byteCodes, int i, final StackMapper smapper) throws IOException {
  2343         String typeName = jc.getClassName(type);
  2344         int dim = readUByte(byteCodes, ++i);
  2345         StringBuilder dims = new StringBuilder();
  2346         dims.append('[');
  2347         for (int d = 0; d < dim; d++) {
  2348             if (d != 0) {
  2349                 dims.insert(1, ",");
  2350             }
  2351             dims.insert(1, smapper.popI());
  2352         }
  2353         dims.append(']');
  2354         String fn = "null";
  2355         if (typeName.charAt(dim) == 'L') {
  2356             fn = "vm." + mangleClassName(typeName.substring(dim + 1, typeName.length() - 1));
  2357         }
  2358         emit(smapper, this, 
  2359             "var @2 = Array.prototype['multiNewArray__Ljava_lang_Object_2Ljava_lang_String_2_3ILjava_lang_Object_2']('@3', @1, @4);",
  2360              dims.toString(), smapper.pushA(), typeName, fn
  2361         );
  2362         return i;
  2363     }
  2364 
  2365     private int generateTableSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
  2366         int table = i / 4 * 4 + 4;
  2367         int dflt = i + readInt4(byteCodes, table);
  2368         table += 4;
  2369         int low = readInt4(byteCodes, table);
  2370         table += 4;
  2371         int high = readInt4(byteCodes, table);
  2372         table += 4;
  2373         final CharSequence swVar = smapper.popValue();
  2374         smapper.flush(this);
  2375         append("switch (").append(swVar).append(") {\n");
  2376         while (low <= high) {
  2377             int offset = i + readInt4(byteCodes, table);
  2378             table += 4;
  2379             append("  case " + low).append(":"); goTo(this, i, offset, topMostLabel); append('\n');
  2380             low++;
  2381         }
  2382         append("  default: ");
  2383         goTo(this, i, dflt, topMostLabel);
  2384         append("\n}");
  2385         i = table - 1;
  2386         return i;
  2387     }
  2388 
  2389     private int generateLookupSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
  2390         int table = i / 4 * 4 + 4;
  2391         int dflt = i + readInt4(byteCodes, table);
  2392         table += 4;
  2393         int n = readInt4(byteCodes, table);
  2394         table += 4;
  2395         final CharSequence swVar = smapper.popValue();
  2396         smapper.flush(this);
  2397         append("switch (").append(swVar).append(") {\n");
  2398         while (n-- > 0) {
  2399             int cnstnt = readInt4(byteCodes, table);
  2400             table += 4;
  2401             int offset = i + readInt4(byteCodes, table);
  2402             table += 4;
  2403             append("  case " + cnstnt).append(": "); goTo(this, i, offset, topMostLabel); append('\n');
  2404         }
  2405         append("  default: ");
  2406         goTo(this, i, dflt, topMostLabel);
  2407         append("\n}");
  2408         i = table - 1;
  2409         return i;
  2410     }
  2411 
  2412     private void generateInstanceOf(int indx, final StackMapper smapper) throws IOException {
  2413         String type = jc.getClassName(indx);
  2414         if (!type.startsWith("[")) {
  2415             emit(smapper, this, 
  2416                     "var @2 = @1 != null && @1['$instOf_@3'] ? 1 : 0;",
  2417                  smapper.popA(), smapper.pushI(),
  2418                  mangleClassName(type));
  2419         } else {
  2420             int cnt = 0;
  2421             while (type.charAt(cnt) == '[') {
  2422                 cnt++;
  2423             }
  2424             if (type.charAt(cnt) == 'L') {
  2425                 String component = type.substring(cnt + 1, type.length() - 1);
  2426                 requireReference(component);
  2427                 type = "vm." + mangleClassName(component);
  2428                 emit(smapper, this, 
  2429                     "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @4, @3);",
  2430                     smapper.popA(), smapper.pushI(),
  2431                     type, "" + cnt
  2432                 );
  2433             } else {
  2434                 emit(smapper, this, 
  2435                     "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@3');",
  2436                     smapper.popA(), smapper.pushI(), type
  2437                 );
  2438             }
  2439         }
  2440     }
  2441 
  2442     private void generateCheckcast(int indx, final StackMapper smapper) throws IOException {
  2443         String type = jc.getClassName(indx);
  2444         if (!type.startsWith("[")) {
  2445             emitNoFlush(smapper, 
  2446                  "if (@1 !== null && !@1['$instOf_@2']) vm.java_lang_Class(false).castEx();",
  2447                  smapper.getT(0, VarType.REFERENCE, false), mangleClassName(type));
  2448         } else {
  2449             int cnt = 0;
  2450             while (type.charAt(cnt) == '[') {
  2451                 cnt++;
  2452             }
  2453             if (type.charAt(cnt) == 'L') {
  2454                 String component = type.substring(cnt + 1, type.length() - 1);
  2455                 requireReference(component);
  2456                 type = "vm." + mangleClassName(component);
  2457                 emitNoFlush(smapper, 
  2458                     "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @3, @2)) vm.java_lang_Class(false).castEx();",
  2459                      smapper.getT(0, VarType.REFERENCE, false), type, "" + cnt
  2460                 );
  2461             } else {
  2462                 emitNoFlush(smapper, 
  2463                     "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@2')) vm.java_lang_Class(false).castEx();",
  2464                      smapper.getT(0, VarType.REFERENCE, false), type
  2465                 );
  2466             }
  2467         }
  2468     }
  2469 
  2470     private void generateByteCodeComment(int prev, int i, final byte[] byteCodes) throws IOException {
  2471         for (int j = prev; j <= i; j++) {
  2472             append(" ");
  2473             final int cc = readUByte(byteCodes, j);
  2474             append(Integer.toString(cc));
  2475         }
  2476     }
  2477     
  2478     @JavaScriptBody(args = "msg", body = "")
  2479     private static void println(String msg) {
  2480         System.err.println(msg);
  2481     }
  2482 }