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