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