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