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