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