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