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