rt/vm/src/main/java/org/apidesign/vm4brwsr/ByteCodeToJavaScript.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Tue, 14 Jun 2016 05:44:20 +0200
branchLibraries
changeset 1976 9d33c9507806
parent 1975 0e230308c26f
permissions -rw-r--r--
Hardcoding that Array.push is using varargs
     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                     if (DirectlLibraries.isScriptLibrary(fi[0])) {
  1456                         smapper.replace(this, type, "@1['@2']",
  1457                              smapper.getA(0),
  1458                              fi[1]
  1459                         );
  1460                     } else {
  1461                         FieldData field = findField(fi);
  1462                         if (field == null) {
  1463                             final String mangleClass = mangleClassName(fi[0]);
  1464                             final String mangleClassAccess = accessClassFalse(mangleClass);
  1465                             smapper.replace(this, type, "@2.call(@1)",
  1466                                  smapper.getA(0),
  1467                                  accessField(mangleClassAccess, null, fi)
  1468                             );
  1469                         } else {
  1470                             final String fieldOwner = mangleClassName(field.cls.getClassName());
  1471                             smapper.replace(this, type, "@1@2",
  1472                                  smapper.getA(0),
  1473                                  accessField(fieldOwner, field, fi)
  1474                             );
  1475                         }
  1476                         addReference(fi[0]);
  1477                     }
  1478                     i += 2;
  1479                     break;
  1480                 }
  1481                 case opc_putfield: {
  1482                     int indx = readUShortArg(byteCodes, i);
  1483                     String[] fi = jc.getFieldInfoName(indx);
  1484                     final int type = VarType.fromFieldType(fi[2].charAt(0));
  1485                     FieldData field = findField(fi);
  1486                     if (field == null) {
  1487                         final String mangleClass = mangleClassName(fi[0]);
  1488                         final String mangleClassAccess = accessClassFalse(mangleClass);
  1489                         emit(smapper, this, "@3.call(@2, @1);",
  1490                              smapper.popT(type),
  1491                              smapper.popA(),
  1492                              accessField(mangleClassAccess, null, fi)
  1493                         );
  1494                     } else {
  1495                         final String fieldOwner = mangleClassName(field.cls.getClassName());
  1496                         emit(smapper, this, "@2@3 = @1;",
  1497                              smapper.popT(type),
  1498                              smapper.popA(),
  1499                              accessField(fieldOwner, field, fi)
  1500                         );
  1501                     }
  1502                     i += 2;
  1503                     addReference(fi[0]);
  1504                     break;
  1505                 }
  1506                 case opc_getstatic: {
  1507                     int indx = readUShortArg(byteCodes, i);
  1508                     String[] fi = jc.getFieldInfoName(indx);
  1509                     final int type = VarType.fromFieldType(fi[2].charAt(0));
  1510                     if (DirectlLibraries.isScriptLibrary(fi[0]) && fi[0].endsWith("/Exports")) {
  1511                         smapper.assign(this, type, fi[1]);
  1512                     } else {
  1513                         String ac = accessClassFalse(mangleClassName(fi[0]));
  1514                         FieldData field = findField(fi);
  1515                         String af = accessField(ac, field, fi);
  1516                         smapper.assign(this, type, af + "()");
  1517                         addReference(fi[0]);
  1518                     }
  1519                     i += 2;
  1520                     break;
  1521                 }
  1522                 case opc_putstatic: {
  1523                     int indx = readUShortArg(byteCodes, i);
  1524                     String[] fi = jc.getFieldInfoName(indx);
  1525                     final int type = VarType.fromFieldType(fi[2].charAt(0));
  1526                     emit(smapper, this, "@1._@2(@3);",
  1527                          accessClassFalse(mangleClassName(fi[0])), fi[1],
  1528                          smapper.popT(type));
  1529                     i += 2;
  1530                     addReference(fi[0]);
  1531                     break;
  1532                 }
  1533                 case opc_checkcast: {
  1534                     int indx = readUShortArg(byteCodes, i);
  1535                     generateCheckcast(indx, smapper);
  1536                     i += 2;
  1537                     break;
  1538                 }
  1539                 case opc_instanceof: {
  1540                     int indx = readUShortArg(byteCodes, i);
  1541                     generateInstanceOf(indx, smapper);
  1542                     i += 2;
  1543                     break;
  1544                 }
  1545                 case opc_athrow: {
  1546                     final CharSequence v = smapper.popA();
  1547                     smapper.clear();
  1548 
  1549                     emit(smapper, this, "{ var @1 = @2; throw @2; }",
  1550                          smapper.pushA(), v);
  1551                     break;
  1552                 }
  1553 
  1554                 case opc_monitorenter: {
  1555                     debug("/* monitor enter */");
  1556                     smapper.popA();
  1557                     break;
  1558                 }
  1559 
  1560                 case opc_monitorexit: {
  1561                     debug("/* monitor exit */");
  1562                     smapper.popA();
  1563                     break;
  1564                 }
  1565 
  1566                 case opc_wide:
  1567                     wide = true;
  1568                     break;
  1569 
  1570                 default: {
  1571                     wide = false;
  1572                     emit(smapper, this, "throw 'unknown bytecode @1';",
  1573                          Integer.toString(c));
  1574                 }
  1575             }
  1576             if (debug(" //")) {
  1577                 generateByteCodeComment(prev, i, byteCodes);
  1578             }
  1579             if (outChanged) {
  1580                 append("\n");
  1581             }
  1582         }
  1583         if (previousTrap != null) {
  1584             generateCatch(previousTrap, byteCodes.length, topMostLabel);
  1585         }
  1586         if (didBranches) {
  1587             append("\n    }\n");
  1588         }
  1589         while (openBraces-- > 0) {
  1590             append('}');
  1591         }
  1592         if (defineProp) {
  1593             append("\n}});");
  1594         } else {
  1595             append("\n};");
  1596         }
  1597         return defineProp;
  1598     }
  1599 
  1600     private int generateIf(StackMapper mapper, byte[] byteCodes, 
  1601         int i, final CharSequence v2, final CharSequence v1, 
  1602         final String test, int topMostLabel
  1603     ) throws IOException {
  1604         mapper.flush(this);
  1605         int indx = i + readShortArg(byteCodes, i);
  1606         append("if ((").append(v1)
  1607            .append(") ").append(test).append(" (")
  1608            .append(v2).append(")) ");
  1609         goTo(this, i, indx, topMostLabel);
  1610         return i + 2;
  1611     }
  1612     
  1613     private int readInt4(byte[] byteCodes, int offset) {
  1614         final int d = byteCodes[offset + 0] << 24;
  1615         final int c = byteCodes[offset + 1] << 16;
  1616         final int b = byteCodes[offset + 2] << 8;
  1617         final int a = byteCodes[offset + 3];
  1618         return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
  1619     }
  1620     private static int readUByte(byte[] byteCodes, int offset) {
  1621         return byteCodes[offset] & 0xff;
  1622     }
  1623 
  1624     private static int readUShort(byte[] byteCodes, int offset) {
  1625         return ((byteCodes[offset] & 0xff) << 8)
  1626                     | (byteCodes[offset + 1] & 0xff);
  1627     }
  1628     private static int readUShortArg(byte[] byteCodes, int offsetInstruction) {
  1629         return readUShort(byteCodes, offsetInstruction + 1);
  1630     }
  1631 
  1632     private static int readShort(byte[] byteCodes, int offset) {
  1633         int signed = byteCodes[offset];
  1634         byte b0 = (byte)signed;
  1635         return (b0 << 8) | (byteCodes[offset + 1] & 0xff);
  1636     }
  1637     private static int readShortArg(byte[] byteCodes, int offsetInstruction) {
  1638         return readShort(byteCodes, offsetInstruction + 1);
  1639     }
  1640 
  1641     private static void countArgs(String descriptor, char[] returnType, StringBuilder sig, StringBuilder cnt) {
  1642         int i = 0;
  1643         Boolean count = null;
  1644         boolean array = false;
  1645         sig.append("__");
  1646         int firstPos = sig.length();
  1647         while (i < descriptor.length()) {
  1648             char ch = descriptor.charAt(i++);
  1649             switch (ch) {
  1650                 case '(':
  1651                     count = true;
  1652                     continue;
  1653                 case ')':
  1654                     count = false;
  1655                     continue;
  1656                 case 'B': 
  1657                 case 'C': 
  1658                 case 'D': 
  1659                 case 'F': 
  1660                 case 'I': 
  1661                 case 'J': 
  1662                 case 'S': 
  1663                 case 'Z': 
  1664                     if (count) {
  1665                         if (array) {
  1666                             sig.append("_3");
  1667                         }
  1668                         sig.append(ch);
  1669                         if (ch == 'J' || ch == 'D') {
  1670                             cnt.append('1');
  1671                         } else {
  1672                             cnt.append('0');
  1673                         }
  1674                     } else {
  1675                         sig.insert(firstPos, ch);
  1676                         if (array) {
  1677                             returnType[0] = '[';
  1678                             sig.insert(firstPos, "_3");
  1679                         } else {
  1680                             returnType[0] = ch;
  1681                         }
  1682                     }
  1683                     array = false;
  1684                     continue;
  1685                 case 'V': 
  1686                     assert !count;
  1687                     returnType[0] = 'V';
  1688                     sig.insert(firstPos, 'V');
  1689                     continue;
  1690                 case 'L':
  1691                     int next = descriptor.indexOf(';', i);
  1692                     String realSig = mangleSig(descriptor, i - 1, next + 1);
  1693                     if (count) {
  1694                         if (array) {
  1695                             sig.append("_3");
  1696                         }
  1697                         sig.append(realSig);
  1698                         cnt.append('0');
  1699                     } else {
  1700                         sig.insert(firstPos, realSig);
  1701                         if (array) {
  1702                             sig.insert(firstPos, "_3");
  1703                         }
  1704                         returnType[0] = 'L';
  1705                     }
  1706                     i = next + 1;
  1707                     array = false;
  1708                     continue;
  1709                 case '[':
  1710                     array = true;
  1711                     continue;
  1712                 default:
  1713                     throw new IllegalStateException("Invalid char: " + ch);
  1714             }
  1715         }
  1716     }
  1717     
  1718     static String mangleSig(String sig) {
  1719         return mangleSig(sig, 0, sig.length());
  1720     }
  1721     
  1722     private static String mangleMethodName(String name) {
  1723         StringBuilder sb = new StringBuilder(name.length() * 2);
  1724         int last = name.length();
  1725         for (int i = 0; i < last; i++) {
  1726             final char ch = name.charAt(i);
  1727             switch (ch) {
  1728                 case '_': sb.append("_1"); break;
  1729                 default: sb.append(ch); break;
  1730             }
  1731         }
  1732         return sb.toString();
  1733     }
  1734     private static String mangleSig(String txt, int first, int last) {
  1735         StringBuilder sb = new StringBuilder((last - first) * 2);
  1736         for (int i = first; i < last; i++) {
  1737             final char ch = txt.charAt(i);
  1738             switch (ch) {
  1739                 case '/': sb.append('_'); break;
  1740                 case '_': sb.append("_1"); break;
  1741                 case ';': sb.append("_2"); break;
  1742                 case '[': sb.append("_3"); break;
  1743                 default: 
  1744                     if (Character.isJavaIdentifierPart(ch)) {
  1745                         sb.append(ch);
  1746                     } else {
  1747                         sb.append("_0");
  1748                         String hex = Integer.toHexString(ch).toLowerCase();
  1749                         for (int m = hex.length(); m < 4; m++) {
  1750                             sb.append("0");
  1751                         }
  1752                         sb.append(hex);
  1753                     }
  1754                 break;
  1755             }
  1756         }
  1757         return sb.toString();
  1758     }
  1759     
  1760     private static String mangleClassName(String name) {
  1761         return mangleSig(name);
  1762     }
  1763 
  1764     private static String findMethodName(MethodData m, StringBuilder cnt) {
  1765         StringBuilder name = new StringBuilder();
  1766         if ("<init>".equals(m.getName())) { // NOI18N
  1767             name.append("cons"); // NOI18N
  1768         } else if ("<clinit>".equals(m.getName())) { // NOI18N
  1769             name.append("class"); // NOI18N
  1770         } else {
  1771             name.append(mangleMethodName(m.getName()));
  1772         } 
  1773         
  1774         countArgs(m.getInternalSig(), new char[1], name, cnt);
  1775         return name.toString();
  1776     }
  1777 
  1778     static String findMethodName(String[] mi, StringBuilder cnt, char[] returnType) {
  1779         StringBuilder name = new StringBuilder();
  1780         String descr = mi[2];//mi.getDescriptor();
  1781         String nm= mi[1];
  1782         if ("<init>".equals(nm)) { // NOI18N
  1783             name.append("cons"); // NOI18N
  1784         } else {
  1785             name.append(mangleMethodName(nm));
  1786         }
  1787         countArgs(descr, returnType, name, cnt);
  1788         return name.toString();
  1789     }
  1790 
  1791     private int invokeStaticMethod(byte[] byteCodes, int i, final StackMapper mapper, boolean isStatic)
  1792     throws IOException {
  1793         int methodIndex = readUShortArg(byteCodes, i);
  1794         String[] mi = jc.getFieldInfoName(methodIndex);
  1795         char[] returnType = { 'V' };
  1796         StringBuilder cnt = new StringBuilder();
  1797         String mn = findMethodName(mi, cnt, returnType);
  1798         
  1799         final int numArguments = isStatic ? cnt.length() : cnt.length() + 1;
  1800         final CharSequence[] vars = new CharSequence[numArguments];
  1801 
  1802         for (int j = numArguments - 1; j >= 0; --j) {
  1803             vars[j] = mapper.popValue();
  1804         }
  1805 
  1806         if ((
  1807             "newUpdater__Ljava_util_concurrent_atomic_AtomicIntegerFieldUpdater_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
  1808             && "java/util/concurrent/atomic/AtomicIntegerFieldUpdater".equals(mi[0])
  1809         ) || (
  1810             "newUpdater__Ljava_util_concurrent_atomic_AtomicLongFieldUpdater_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
  1811             && "java/util/concurrent/atomic/AtomicLongFieldUpdater".equals(mi[0])
  1812         )) {
  1813             if (vars[1] instanceof String) {
  1814                 String field = vars[1].toString();
  1815                 if (field.length() > 2 && field.charAt(0) == '"' && field.charAt(field.length() - 1) == '"') {
  1816                     vars[1] = "c._" + field.substring(1, field.length() - 1);
  1817                 }
  1818             }
  1819         }
  1820         if (
  1821             "newUpdater__Ljava_util_concurrent_atomic_AtomicReferenceFieldUpdater_2Ljava_lang_Class_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
  1822             && "java/util/concurrent/atomic/AtomicReferenceFieldUpdater".equals(mi[0])
  1823         ) {
  1824             if (vars[1] instanceof String) {
  1825                 String field = vars[2].toString();
  1826                 if (field.length() > 2 && field.charAt(0) == '"' && field.charAt(field.length() - 1) == '"') {
  1827                     vars[2] = "c._" + field.substring(1, field.length() - 1);
  1828                 }
  1829             }
  1830         }
  1831 
  1832         if (returnType[0] != 'V') {
  1833             mapper.flush(this);
  1834             append("var ")
  1835                .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
  1836                .append(" = ");
  1837         }
  1838 
  1839         final String in = mi[0];
  1840         String mcn;
  1841         final boolean direct = DirectlLibraries.isScriptLibrary(in);
  1842         boolean skipThis = false;
  1843         if (callbacks && (
  1844             in.equals("org/apidesign/html/boot/spi/Fn") ||
  1845             in.equals("org/netbeans/html/boot/spi/Fn")
  1846         )) {
  1847             mcn = "java_lang_Class";
  1848         } else if (direct) {
  1849             if (in.endsWith("/Exports")) {
  1850                 append(mi[1]);
  1851                 append('(');
  1852                 mcn = null;
  1853             } else if (mn.startsWith("cons_")) {
  1854                 append('(');
  1855                 mcn = null;
  1856                 skipThis = true;
  1857             } else {
  1858                 mcn = mangleClassName(in);
  1859             }
  1860         } else {
  1861             mcn = mangleClassName(in);
  1862         }
  1863         if (mcn != null) {
  1864             String object = accessClassFalse(mcn);
  1865             if (mn.startsWith("cons_")) {
  1866                 object += ".constructor";
  1867             }
  1868             append(accessStaticMethod(object, mn, mi));
  1869             if (isStatic) {
  1870                 append('(');
  1871             } else {
  1872                 append(".call(");
  1873             }
  1874             addReference(in);
  1875         }
  1876         if (numArguments > 0) {
  1877             String sep;
  1878             if (!skipThis) {
  1879                 append(vars[0]);
  1880                 sep = ", ";
  1881             } else {
  1882                 sep = "";
  1883             }
  1884             for (int j = 1; j < numArguments; ++j) {
  1885                 append(sep);
  1886                 append(vars[j]);
  1887                 sep = ", ";
  1888             }
  1889         }
  1890         append(");");
  1891         i += 2;
  1892         return i;
  1893     }
  1894     private int invokeVirtualMethod(byte[] byteCodes, int i, final StackMapper mapper)
  1895     throws IOException {
  1896         int methodIndex = readUShortArg(byteCodes, i);
  1897         String[] mi = jc.getFieldInfoName(methodIndex);
  1898         char[] returnType = { 'V' };
  1899         StringBuilder cnt = new StringBuilder();
  1900         String mn = findMethodName(mi, cnt, returnType);
  1901 
  1902         final int numArguments = cnt.length() + 1;
  1903         final CharSequence[] vars =  new CharSequence[numArguments];
  1904 
  1905         for (int j = numArguments - 1; j >= 0; --j) {
  1906             vars[j] = mapper.popValue();
  1907         }
  1908 
  1909         if (returnType[0] != 'V') {
  1910             mapper.flush(this);
  1911             append("var ")
  1912                .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
  1913                .append(" = ");
  1914         }
  1915 
  1916         i += 2;
  1917         if (DirectlLibraries.isScriptLibrary(mi[0])) {
  1918             if (
  1919                 "$get__Ljava_lang_Object_2Ljava_lang_String_2".equals(mn) ||
  1920                 "$get__Ljava_lang_Object_2D".equals(mn)
  1921             ) {
  1922                 append(vars[0].toString())
  1923                     .append('[')
  1924                     .append(vars[1])
  1925                     .append("];");
  1926                 return i;
  1927             }
  1928             if (
  1929                 "$set__VLjava_lang_String_2Ljava_lang_Object_2".equals(mn) ||
  1930                 "$set__VDLjava_lang_Object_2".equals(mn)
  1931             ) {
  1932                 append(vars[0].toString())
  1933                     .append('[')
  1934                     .append(vars[1])
  1935                     .append("] = ")
  1936                     .append(vars[2])
  1937                     .append(';');
  1938                 return i;
  1939             }
  1940             if (
  1941                 mi[0].equals("net/java/html/lib/Objs$Property") &&
  1942                 mi[1].equals("get")
  1943             ) {
  1944                 // virtual get = property read
  1945                 append(vars[0].toString()).append(';');
  1946                 return i;
  1947             }
  1948             if (mi[1].equals("push") && mi[0].equals("net/java/html/lib/Array")) {
  1949                 append(vars[0].toString()).append("['").append(mi[1]).append("'].apply(").append(vars[0].toString()).append(",");
  1950             } else {
  1951                 append(vars[0].toString()).append("['").append(mi[1]).append("'](");
  1952             }
  1953         } else {
  1954             append(accessVirtualMethod(vars[0].toString(), mn, mi, numArguments));
  1955         }
  1956         String sep = "";
  1957         for (int j = 1; j < numArguments; ++j) {
  1958             append(sep);
  1959             append(vars[j]);
  1960             sep = ", ";
  1961         }
  1962         append(");");
  1963         return i;
  1964     }
  1965 
  1966     private void addReference(String cn) throws IOException {
  1967         if (requireReference(cn)) {
  1968             debug(" /* needs " + cn + " */");
  1969         }
  1970     }
  1971 
  1972     private void outType(String d, StringBuilder out) {
  1973         int arr = 0;
  1974         while (d.charAt(0) == '[') {
  1975             out.append('A');
  1976             d = d.substring(1);
  1977         }
  1978         if (d.charAt(0) == 'L') {
  1979             assert d.charAt(d.length() - 1) == ';';
  1980             out.append(mangleClassName(d).substring(0, d.length() - 1));
  1981         } else {
  1982             out.append(d);
  1983         }
  1984     }
  1985 
  1986     private String encodeConstant(int entryIndex) throws IOException {
  1987         String[] classRef = { null };
  1988         String s = jc.stringValue(entryIndex, classRef);
  1989         if (classRef[0] != null) {
  1990             if (classRef[0].startsWith("[")) {
  1991                 s = accessClass("java_lang_Class") + "(false)['forName__Ljava_lang_Class_2Ljava_lang_String_2']('" + classRef[0] + "')";
  1992             } else {
  1993                 addReference(classRef[0]);
  1994                 s = accessClassFalse(mangleClassName(s)) + ".constructor.$class";
  1995             }
  1996         }
  1997         return s;
  1998     }
  1999 
  2000     private String javaScriptBody(String destObject, MethodData m, boolean isStatic) throws IOException {
  2001         byte[] arr = m.findAnnotationData(true);
  2002         if (arr == null) {
  2003             return null;
  2004         }
  2005         final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
  2006         final String htmlType = "Lnet/java/html/js/JavaScriptBody;";
  2007         class P extends AnnotationParser {
  2008             public P() {
  2009                 super(false, true);
  2010             }
  2011             
  2012             int cnt;
  2013             String[] args = new String[30];
  2014             String body;
  2015             boolean javacall;
  2016             boolean html4j;
  2017             
  2018             @Override
  2019             protected void visitAttr(String type, String attr, String at, String value) {
  2020                 if (type.equals(jvmType)) {
  2021                     if ("body".equals(attr)) {
  2022                         body = value;
  2023                     } else if ("args".equals(attr)) {
  2024                         args[cnt++] = value;
  2025                     } else {
  2026                         throw new IllegalArgumentException(attr);
  2027                     }
  2028                 }
  2029                 if (type.equals(htmlType)) {
  2030                     html4j = true;
  2031                     if ("body".equals(attr)) {
  2032                         body = value;
  2033                     } else if ("args".equals(attr)) {
  2034                         args[cnt++] = value;
  2035                     } else if ("javacall".equals(attr)) {
  2036                         javacall = "1".equals(value);
  2037                     } else if ("wait4js".equals(attr)) {
  2038                         // ignore, we always invoke synchronously
  2039                     } else {
  2040                         throw new IllegalArgumentException(attr);
  2041                     }
  2042                 }
  2043             }
  2044         }
  2045         P p = new P();
  2046         p.parse(arr, jc);
  2047         if (p.body == null) {
  2048             return null;
  2049         }
  2050         StringBuilder cnt = new StringBuilder();
  2051         final String mn = findMethodName(m, cnt);
  2052         append("m = ").append(destObject).append(".").append(mn);
  2053         append(" = function(");
  2054         String space = "";
  2055         int index = 0;
  2056         StringBuilder toValue = new StringBuilder();
  2057         for (int i = 0; i < cnt.length(); i++) {
  2058             append(space);
  2059             space = outputArg(this, p.args, index);
  2060             if (p.html4j && space.length() > 0) {
  2061                 toValue.append("\n  ").append(p.args[index]).append(" = ")
  2062                     .append(accessClass("java_lang_Class")).append("(false).toJS(").
  2063                     append(p.args[index]).append(");");
  2064             }
  2065             index++;
  2066         }
  2067         append(") {").append("\n");
  2068         append(toValue.toString());
  2069         if (p.javacall) {
  2070             int lastSlash = jc.getClassName().lastIndexOf('/');
  2071             final String pkg = jc.getClassName().substring(0, lastSlash);
  2072             append(mangleCallbacks(pkg, p.body));
  2073             requireReference(pkg + "/$JsCallbacks$");
  2074         } else {
  2075             append(p.body);
  2076         }
  2077         append("\n}\n");
  2078         return mn;
  2079     }
  2080     
  2081     private CharSequence mangleCallbacks(String pkgName, String body) {
  2082         StringBuilder sb = new StringBuilder();
  2083         int pos = 0;
  2084         for (;;) {
  2085             int next = body.indexOf(".@", pos);
  2086             if (next == -1) {
  2087                 sb.append(body.substring(pos));
  2088                 body = sb.toString();
  2089                 break;
  2090             }
  2091             int ident = next;
  2092             while (ident > 0) {
  2093                 if (!Character.isJavaIdentifierPart(body.charAt(--ident))) {
  2094                     ident++;
  2095                     break;
  2096                 }
  2097             }
  2098             String refId = body.substring(ident, next);
  2099 
  2100             sb.append(body.substring(pos, ident));
  2101 
  2102             int sigBeg = body.indexOf('(', next);
  2103             int sigEnd = body.indexOf(')', sigBeg);
  2104             int colon4 = body.indexOf("::", next);
  2105             if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
  2106                 throw new IllegalStateException("Malformed body " + body);
  2107             }
  2108             String fqn = body.substring(next + 2, colon4);
  2109             String method = body.substring(colon4 + 2, sigBeg);
  2110             String params = body.substring(sigBeg, sigEnd + 1);
  2111 
  2112             int paramBeg = body.indexOf('(', sigEnd + 1);
  2113             int paramEnd = closingParenthesis(body, paramBeg);
  2114 
  2115             sb.append(accessClass("java_lang_Class")).append("(false).toJS(");
  2116             sb.append("vm.").append(mangleClassName(pkgName)).append("_$JsCallbacks$(false)._VM().");
  2117             sb.append(mangleJsCallbacks(fqn, method, params, false));
  2118             sb.append("(").append(refId);
  2119             if (body.charAt(paramBeg + 1) != ')') {
  2120                 sb.append(",");
  2121             }
  2122             sb.append(body.substring(paramBeg + 1, paramEnd));
  2123             sb.append(")");
  2124             pos = paramEnd;
  2125         }
  2126         sb = null;
  2127         pos = 0;
  2128         for (;;) {
  2129             int next = body.indexOf("@", pos);
  2130             if (next == -1) {
  2131                 if (sb == null) {
  2132                     return body;
  2133                 }
  2134                 sb.append(body.substring(pos));
  2135                 return sb;
  2136             }
  2137             if (sb == null) {
  2138                 sb = new StringBuilder();
  2139             }
  2140 
  2141             sb.append(body.substring(pos, next));
  2142 
  2143             int sigBeg = body.indexOf('(', next);
  2144             int sigEnd = body.indexOf(')', sigBeg);
  2145             int colon4 = body.indexOf("::", next);
  2146             if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
  2147                 throw new IllegalStateException("Malformed body " + body);
  2148             }
  2149             String fqn = body.substring(next + 1, colon4);
  2150             String method = body.substring(colon4 + 2, sigBeg);
  2151             String params = body.substring(sigBeg, sigEnd + 1);
  2152 
  2153             int paramBeg = body.indexOf('(', sigEnd + 1);
  2154             int paramEnd = closingParenthesis(body, paramBeg);
  2155 
  2156             sb.append(accessClass("java_lang_Class")).append("(false).toJS(");
  2157             sb.append("vm.").append(mangleClassName(pkgName)).append("_$JsCallbacks$(false)._VM().");
  2158             sb.append(mangleJsCallbacks(fqn, method, params, true));
  2159             sb.append("(");
  2160             sb.append(body.substring(paramBeg + 1, paramEnd));
  2161             sb.append(")");
  2162             pos = paramEnd;
  2163         }
  2164     }
  2165 
  2166     static String mangleJsCallbacks(String fqn, String method, String params, boolean isStatic) {
  2167         if (params.startsWith("(")) {
  2168             params = params.substring(1);
  2169         }
  2170         if (params.endsWith(")")) {
  2171             params = params.substring(0, params.length() - 1);
  2172         }
  2173         StringBuilder sb = new StringBuilder();
  2174         final String fqnu = fqn.replace('.', '_');
  2175         final String rfqn = mangleClassName(fqnu);
  2176         final String rm = mangleMethodName(method);
  2177         final String srp;
  2178         {
  2179             StringBuilder pb = new StringBuilder();
  2180             int len = params.length();
  2181             int indx = 0;
  2182             while (indx < len) {
  2183                 char ch = params.charAt(indx);
  2184                 if (ch == '[' || ch == 'L') {
  2185                     int column = params.indexOf(';', indx) + 1;
  2186                     if (column > indx) {
  2187                         String real = params.substring(indx, column);
  2188                         if ("Ljava/lang/String;".equals(real)) {
  2189                             pb.append("Ljava/lang/String;");
  2190                             indx = column;
  2191                             continue;
  2192                         }
  2193                     }
  2194                     pb.append("Ljava/lang/Object;");
  2195                     indx = column;
  2196                 } else {
  2197                     pb.append(ch);
  2198                     indx++;
  2199                 }
  2200             }
  2201             srp = mangleSig(pb.toString());
  2202         }
  2203         final String rp = mangleSig(params);
  2204         final String mrp = mangleMethodName(rp);
  2205         sb.append(rfqn).append("$").append(rm).
  2206             append('$').append(mrp).append("__Ljava_lang_Object_2");
  2207         if (!isStatic) {
  2208             sb.append('L').append(fqnu).append("_2");
  2209         }
  2210         sb.append(srp);
  2211         return sb.toString();
  2212     }
  2213 
  2214     private static String className(ClassData jc) {
  2215         //return jc.getName().getInternalName().replace('/', '_');
  2216         return mangleClassName(jc.getClassName());
  2217     }
  2218     
  2219     private static String[] findAnnotation(
  2220         byte[] arr, ClassData cd, final String className, 
  2221         final String... attrNames
  2222     ) throws IOException {
  2223         if (arr == null) {
  2224             return null;
  2225         }
  2226         final String[] values = new String[attrNames.length];
  2227         final boolean[] found = { false };
  2228         final String jvmType = "L" + className.replace('.', '/') + ";";
  2229         AnnotationParser ap = new AnnotationParser(false, true) {
  2230             @Override
  2231             protected void visitAttr(String type, String attr, String at, String value) {
  2232                 if (type.equals(jvmType)) {
  2233                     found[0] = true;
  2234                     for (int i = 0; i < attrNames.length; i++) {
  2235                         if (attrNames[i].equals(attr)) {
  2236                             values[i] = value;
  2237                         }
  2238                     }
  2239                 }
  2240             }
  2241             
  2242         };
  2243         ap.parse(arr, cd);
  2244         return found[0] ? values : null;
  2245     }
  2246 
  2247     private CharSequence initField(FieldData v) {
  2248         final String is = v.getInternalSig();
  2249         if (is.length() == 1) {
  2250             switch (is.charAt(0)) {
  2251                 case 'S':
  2252                 case 'J':
  2253                 case 'B':
  2254                 case 'Z':
  2255                 case 'C':
  2256                 case 'I': return " = 0;";
  2257                 case 'F': 
  2258                 case 'D': return " = 0.0;";
  2259                 default:
  2260                     throw new IllegalStateException(is);
  2261             }
  2262         }
  2263         return " = null;";
  2264     }
  2265 
  2266     private static String outputArg(Appendable out, String[] args, int indx) throws IOException {
  2267         final String name = args[indx];
  2268         if (name == null) {
  2269             return "";
  2270         }
  2271         if (name.contains(",")) {
  2272             throw new IOException("Wrong parameter with ',': " + name);
  2273         }
  2274         out.append(name);
  2275         return ",";
  2276     }
  2277 
  2278     final void emitNoFlush(
  2279         StackMapper sm, 
  2280         final String format, final CharSequence... params
  2281     ) throws IOException {
  2282         emitImpl(this, format, params);
  2283     }
  2284     static final void emit(
  2285         StackMapper sm, 
  2286         final Appendable out, 
  2287         final String format, final CharSequence... params
  2288     ) throws IOException {
  2289         sm.flush(out);
  2290         emitImpl(out, format, params);
  2291     }
  2292     static void emitImpl(final Appendable out,
  2293                              final String format,
  2294                              final CharSequence... params) throws IOException {
  2295         final int length = format.length();
  2296 
  2297         int processed = 0;
  2298         int paramOffset = format.indexOf('@');
  2299         while ((paramOffset != -1) && (paramOffset < (length - 1))) {
  2300             final char paramChar = format.charAt(paramOffset + 1);
  2301             if ((paramChar >= '1') && (paramChar <= '9')) {
  2302                 final int paramIndex = paramChar - '0' - 1;
  2303 
  2304                 out.append(format, processed, paramOffset);
  2305                 out.append(params[paramIndex]);
  2306 
  2307                 ++paramOffset;
  2308                 processed = paramOffset + 1;
  2309             }
  2310 
  2311             paramOffset = format.indexOf('@', paramOffset + 1);
  2312         }
  2313 
  2314         out.append(format, processed, length);
  2315     }
  2316 
  2317     private void generateCatch(TrapData[] traps, int current, int topMostLabel) throws IOException {
  2318         append("} catch (e) {\n");
  2319         int finallyPC = -1;
  2320         for (TrapData e : traps) {
  2321             if (e == null) {
  2322                 break;
  2323             }
  2324             if (e.catch_cpx != 0) { //not finally
  2325                 final String classInternalName = jc.getClassName(e.catch_cpx);
  2326                 addReference(classInternalName);
  2327                 append("e = vm.java_lang_Class(false).bck2BrwsrThrwrbl(e);");
  2328                 append("if (e['$instOf_" + mangleClassName(classInternalName) + "']) {");
  2329                 append("var stA0 = e;");
  2330                 goTo(this, current, e.handler_pc, topMostLabel);
  2331                 append("}\n");
  2332             } else {
  2333                 finallyPC = e.handler_pc;
  2334             }
  2335         }
  2336         if (finallyPC == -1) {
  2337             append("throw e;");
  2338         } else {
  2339             append("var stA0 = e;");
  2340             goTo(this, current, finallyPC, topMostLabel);
  2341         }
  2342         append("\n}");
  2343     }
  2344 
  2345     private static void goTo(Appendable out, int current, int to, int canBack) throws IOException {
  2346         if (to < current) {
  2347             if (canBack < to) {
  2348                 out.append("{ gt = 0; continue X_" + to + "; }");
  2349             } else {
  2350                 out.append("{ gt = " + to + "; continue X_0; }");
  2351             }
  2352         } else {
  2353             out.append("{ gt = " + to + "; break IF; }");
  2354         }
  2355     }
  2356 
  2357     private static void emitIf(
  2358         StackMapper sm, 
  2359         Appendable out, String pattern, 
  2360         CharSequence param, 
  2361         int current, int to, int canBack
  2362     ) throws IOException {
  2363         sm.flush(out);
  2364         emitImpl(out, pattern, param);
  2365         goTo(out, current, to, canBack);
  2366     }
  2367 
  2368     private void generateNewArray(int atype, final StackMapper smapper) throws IOException, IllegalStateException {
  2369         String jvmType;
  2370         switch (atype) {
  2371             case 4: jvmType = "[Z"; break;
  2372             case 5: jvmType = "[C"; break;
  2373             case 6: jvmType = "[F"; break;
  2374             case 7: jvmType = "[D"; break;
  2375             case 8: jvmType = "[B"; break;
  2376             case 9: jvmType = "[S"; break;
  2377             case 10: jvmType = "[I"; break;
  2378             case 11: jvmType = "[J"; break;
  2379             default: throw new IllegalStateException("Array type: " + atype);
  2380         }
  2381         emit(smapper, this, 
  2382             "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](true, '@3', null, @1);",
  2383              smapper.popI(), smapper.pushA(), jvmType);
  2384     }
  2385 
  2386     private void generateANewArray(int type, final StackMapper smapper) throws IOException {
  2387         String typeName = jc.getClassName(type);
  2388         String ref = "null";
  2389         if (typeName.startsWith("[")) {
  2390             typeName = "'[" + typeName + "'";
  2391         } else {
  2392             ref = "vm." + mangleClassName(typeName);
  2393             typeName = "'[L" + typeName + ";'";
  2394         }
  2395         emit(smapper, this,
  2396             "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](false, @3, @4, @1);",
  2397              smapper.popI(), smapper.pushA(), typeName, ref);
  2398     }
  2399 
  2400     private int generateMultiANewArray(int type, final byte[] byteCodes, int i, final StackMapper smapper) throws IOException {
  2401         String typeName = jc.getClassName(type);
  2402         int dim = readUByte(byteCodes, ++i);
  2403         StringBuilder dims = new StringBuilder();
  2404         dims.append('[');
  2405         for (int d = 0; d < dim; d++) {
  2406             if (d != 0) {
  2407                 dims.insert(1, ",");
  2408             }
  2409             dims.insert(1, smapper.popI());
  2410         }
  2411         dims.append(']');
  2412         String fn = "null";
  2413         if (typeName.charAt(dim) == 'L') {
  2414             fn = "vm." + mangleClassName(typeName.substring(dim + 1, typeName.length() - 1));
  2415         }
  2416         emit(smapper, this, 
  2417             "var @2 = Array.prototype['multiNewArray__Ljava_lang_Object_2Ljava_lang_String_2_3ILjava_lang_Object_2']('@3', @1, @4);",
  2418              dims.toString(), smapper.pushA(), typeName, fn
  2419         );
  2420         return i;
  2421     }
  2422 
  2423     private int generateTableSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
  2424         int table = i / 4 * 4 + 4;
  2425         int dflt = i + readInt4(byteCodes, table);
  2426         table += 4;
  2427         int low = readInt4(byteCodes, table);
  2428         table += 4;
  2429         int high = readInt4(byteCodes, table);
  2430         table += 4;
  2431         final CharSequence swVar = smapper.popValue();
  2432         smapper.flush(this);
  2433         append("switch (").append(swVar).append(") {\n");
  2434         while (low <= high) {
  2435             int offset = i + readInt4(byteCodes, table);
  2436             table += 4;
  2437             append("  case " + low).append(":"); goTo(this, i, offset, topMostLabel); append('\n');
  2438             low++;
  2439         }
  2440         append("  default: ");
  2441         goTo(this, i, dflt, topMostLabel);
  2442         append("\n}");
  2443         i = table - 1;
  2444         return i;
  2445     }
  2446 
  2447     private int generateLookupSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
  2448         int table = i / 4 * 4 + 4;
  2449         int dflt = i + readInt4(byteCodes, table);
  2450         table += 4;
  2451         int n = readInt4(byteCodes, table);
  2452         table += 4;
  2453         final CharSequence swVar = smapper.popValue();
  2454         smapper.flush(this);
  2455         append("switch (").append(swVar).append(") {\n");
  2456         while (n-- > 0) {
  2457             int cnstnt = readInt4(byteCodes, table);
  2458             table += 4;
  2459             int offset = i + readInt4(byteCodes, table);
  2460             table += 4;
  2461             append("  case " + cnstnt).append(": "); goTo(this, i, offset, topMostLabel); append('\n');
  2462         }
  2463         append("  default: ");
  2464         goTo(this, i, dflt, topMostLabel);
  2465         append("\n}");
  2466         i = table - 1;
  2467         return i;
  2468     }
  2469 
  2470     private void generateInstanceOf(int indx, final StackMapper smapper) throws IOException {
  2471         String type = jc.getClassName(indx);
  2472         if (DirectlLibraries.isScriptLibrary(type)) {
  2473             emit(smapper, this,
  2474                     "var @2 = @1 !== null && @1 !== undefined;",
  2475                  smapper.popA(), smapper.pushI(),
  2476                  mangleClassName(type));
  2477             return;
  2478         }
  2479         if (!type.startsWith("[")) {
  2480             emit(smapper, this, 
  2481                     "var @2 = @1 != null && @1['$instOf_@3'] ? 1 : 0;",
  2482                  smapper.popA(), smapper.pushI(),
  2483                  mangleClassName(type));
  2484         } else {
  2485             int cnt = 0;
  2486             while (type.charAt(cnt) == '[') {
  2487                 cnt++;
  2488             }
  2489             if (type.charAt(cnt) == 'L') {
  2490                 String component = type.substring(cnt + 1, type.length() - 1);
  2491                 requireReference(component);
  2492                 type = "vm." + mangleClassName(component);
  2493                 emit(smapper, this, 
  2494                     "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @4, @3);",
  2495                     smapper.popA(), smapper.pushI(),
  2496                     type, "" + cnt
  2497                 );
  2498             } else {
  2499                 emit(smapper, this, 
  2500                     "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@3');",
  2501                     smapper.popA(), smapper.pushI(), type
  2502                 );
  2503             }
  2504         }
  2505     }
  2506 
  2507     private void generateCheckcast(int indx, final StackMapper smapper) throws IOException {
  2508         String type = jc.getClassName(indx);
  2509         if (DirectlLibraries.isScriptLibrary(type)) {
  2510             emitNoFlush(smapper,
  2511                  "",
  2512                  smapper.getT(0, VarType.REFERENCE, false), mangleClassName(type), type.replace('/', '.'));
  2513             return;
  2514         }
  2515         if (!type.startsWith("[")) {
  2516             emitNoFlush(smapper, 
  2517                  "if (@1 !== null && !@1['$instOf_@2']) vm.java_lang_Class(false).castEx(@1, '@3');",
  2518                  smapper.getT(0, VarType.REFERENCE, false), mangleClassName(type), type.replace('/', '.'));
  2519         } else {
  2520             int cnt = 0;
  2521             while (type.charAt(cnt) == '[') {
  2522                 cnt++;
  2523             }
  2524             if (type.charAt(cnt) == 'L') {
  2525                 String component = type.substring(cnt + 1, type.length() - 1);
  2526                 requireReference(component);
  2527                 type = "vm." + mangleClassName(component);
  2528                 emitNoFlush(smapper, 
  2529                     "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @3, @2)) vm.java_lang_Class(false).castEx(@1, '');",
  2530                      smapper.getT(0, VarType.REFERENCE, false), type, "" + cnt
  2531                 );
  2532             } else {
  2533                 emitNoFlush(smapper, 
  2534                     "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@2')) vm.java_lang_Class(false).castEx(@1, '');",
  2535                      smapper.getT(0, VarType.REFERENCE, false), type
  2536                 );
  2537             }
  2538         }
  2539     }
  2540 
  2541     private void generateByteCodeComment(int prev, int i, final byte[] byteCodes) throws IOException {
  2542         for (int j = prev; j <= i; j++) {
  2543             append(" ");
  2544             final int cc = readUByte(byteCodes, j);
  2545             append(Integer.toString(cc));
  2546         }
  2547     }
  2548     
  2549     @JavaScriptBody(args = "msg", body = "")
  2550     private static void println(String msg) {
  2551         System.err.println(msg);
  2552     }
  2553 
  2554     private static int closingParenthesis(String body, int at) {
  2555         int cnt = 0;
  2556         for (;;) {
  2557             switch (body.charAt(at++)) {
  2558                 case '(': cnt++; break;
  2559                 case ')': cnt--; break;
  2560             }
  2561             if (cnt == 0) {
  2562                 return at;
  2563             }
  2564         }
  2565     }
  2566 
  2567     private class GenerateAnno extends AnnotationParser {
  2568         public GenerateAnno(boolean textual, boolean iterateArray) {
  2569             super(textual, iterateArray);
  2570         }
  2571         int[] cnt = new int[32];
  2572         int depth;
  2573 
  2574         @Override
  2575         protected void visitAnnotationStart(String attrType, boolean top) throws IOException {
  2576             final String slashType = attrType.substring(1, attrType.length() - 1);
  2577             requireReference(slashType);
  2578 
  2579             if (cnt[depth]++ > 0) {
  2580                 append(",");
  2581             }
  2582             if (top) {
  2583                 append('"').append(attrType).append("\" : ");
  2584             }
  2585             append("{\n");
  2586             cnt[++depth] = 0;
  2587         }
  2588 
  2589         @Override
  2590         protected void visitAnnotationEnd(String type, boolean top) throws IOException {
  2591             append("\n}\n");
  2592             depth--;
  2593         }
  2594 
  2595         @Override
  2596         protected void visitValueStart(String attrName, char type) throws IOException {
  2597             if (cnt[depth]++ > 0) {
  2598                 append(",\n");
  2599             }
  2600             cnt[++depth] = 0;
  2601             if (attrName != null) {
  2602                 append('"').append(attrName).append("\" : ");
  2603             }
  2604             if (type == '[') {
  2605                 append("[");
  2606             }
  2607         }
  2608 
  2609         @Override
  2610         protected void visitValueEnd(String attrName, char type) throws IOException {
  2611             if (type == '[') {
  2612                 append("]");
  2613             }
  2614             depth--;
  2615         }
  2616 
  2617         @Override
  2618         protected void visitAttr(String type, String attr, String attrType, String value)
  2619             throws IOException {
  2620             if (attr == null && value == null) {
  2621                 return;
  2622             }
  2623             append(value);
  2624         }
  2625 
  2626         @Override
  2627         protected void visitEnumAttr(String type, String attr, String attrType, String value)
  2628             throws IOException {
  2629             final String slashType = attrType.substring(1, attrType.length() - 1);
  2630             requireReference(slashType);
  2631 
  2632             final String cn = mangleClassName(slashType);
  2633             append(accessClassFalse(cn))
  2634                 .append("['valueOf__L").
  2635                 append(cn).
  2636                 append("_2Ljava_lang_String_2']('").
  2637                 append(value).
  2638                 append("')");
  2639         }
  2640 
  2641         @Override
  2642         protected void visitClassAttr(String annoType, String attr, String className) throws IOException {
  2643             final String slashType = className.substring(1, className.length() - 1);
  2644             requireReference(slashType);
  2645 
  2646             final String cn = mangleClassName(slashType);
  2647             append(accessClassFalse(cn)).append(".constructor.$class");
  2648         }
  2649     }
  2650 }