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