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