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