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