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