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