rt/vm/src/main/java/org/apidesign/vm4brwsr/ByteCodeToJavaScript.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sat, 15 Feb 2014 23:16:11 +0100
branchReducedStack
changeset 1459 6575d1848af3
parent 1458 5c8caf0ba8b8
child 1462 1e7ff3ba3666
permissions -rw-r--r--
Flush stack before performing goto
     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                         emit(smapper, out, "var @1 = 0x@3.next32(0x@2);", smapper.pushL(), 
   835                                 Integer.toHexString(low), Integer.toHexString(hi));
   836                     } else {
   837                         emit(smapper, out, "var @1 = @2;", smapper.pushT(type), v);
   838                     }
   839                     break;
   840                 }
   841                 case opc_lcmp:
   842                     emit(smapper, out, "var @3 = @2.compare64(@1);",
   843                          smapper.popL(), smapper.popL(), smapper.pushI());
   844                     break;
   845                 case opc_fcmpl:
   846                 case opc_fcmpg:
   847                     emit(smapper, out, "var @3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
   848                          smapper.popF(), smapper.popF(), smapper.pushI());
   849                     break;
   850                 case opc_dcmpl:
   851                 case opc_dcmpg:
   852                     emit(smapper, out, "var @3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
   853                          smapper.popD(), smapper.popD(), smapper.pushI());
   854                     break;
   855                 case opc_if_acmpeq:
   856                     i = generateIf(byteCodes, i, smapper.popA(), smapper.popA(),
   857                                    "===", topMostLabel);
   858                     break;
   859                 case opc_if_acmpne:
   860                     i = generateIf(byteCodes, i, smapper.popA(), smapper.popA(),
   861                                    "!==", topMostLabel);
   862                     break;
   863                 case opc_if_icmpeq:
   864                     i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
   865                                    "==", topMostLabel);
   866                     break;
   867                 case opc_ifeq: {
   868                     int indx = i + readShortArg(byteCodes, i);
   869                     emitIf(smapper, out, "if (@1 == 0) ",
   870                          smapper.popI(), i, indx, topMostLabel);
   871                     i += 2;
   872                     break;
   873                 }
   874                 case opc_ifne: {
   875                     int indx = i + readShortArg(byteCodes, i);
   876                     emitIf(smapper, out, "if (@1 != 0) ",
   877                          smapper.popI(), i, indx, topMostLabel);
   878                     i += 2;
   879                     break;
   880                 }
   881                 case opc_iflt: {
   882                     int indx = i + readShortArg(byteCodes, i);
   883                     emitIf(smapper, out, "if (@1 < 0) ",
   884                          smapper.popI(), i, indx, topMostLabel);
   885                     i += 2;
   886                     break;
   887                 }
   888                 case opc_ifle: {
   889                     int indx = i + readShortArg(byteCodes, i);
   890                     emitIf(smapper, out, "if (@1 <= 0) ",
   891                          smapper.popI(), i, indx, topMostLabel);
   892                     i += 2;
   893                     break;
   894                 }
   895                 case opc_ifgt: {
   896                     int indx = i + readShortArg(byteCodes, i);
   897                     emitIf(smapper, out, "if (@1 > 0) ",
   898                          smapper.popI(), i, indx, topMostLabel);
   899                     i += 2;
   900                     break;
   901                 }
   902                 case opc_ifge: {
   903                     int indx = i + readShortArg(byteCodes, i);
   904                     emitIf(smapper, out, "if (@1 >= 0) ",
   905                          smapper.popI(), i, indx, topMostLabel);
   906                     i += 2;
   907                     break;
   908                 }
   909                 case opc_ifnonnull: {
   910                     int indx = i + readShortArg(byteCodes, i);
   911                     emitIf(smapper, out, "if (@1 !== null) ",
   912                          smapper.popA(), i, indx, topMostLabel);
   913                     i += 2;
   914                     break;
   915                 }
   916                 case opc_ifnull: {
   917                     int indx = i + readShortArg(byteCodes, i);
   918                     emitIf(smapper, out, "if (@1 === null) ",
   919                          smapper.popA(), i, indx, topMostLabel);
   920                     i += 2;
   921                     break;
   922                 }
   923                 case opc_if_icmpne:
   924                     i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
   925                                    "!=", topMostLabel);
   926                     break;
   927                 case opc_if_icmplt:
   928                     i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
   929                                    "<", topMostLabel);
   930                     break;
   931                 case opc_if_icmple:
   932                     i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
   933                                    "<=", topMostLabel);
   934                     break;
   935                 case opc_if_icmpgt:
   936                     i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
   937                                    ">", topMostLabel);
   938                     break;
   939                 case opc_if_icmpge:
   940                     i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
   941                                    ">=", topMostLabel);
   942                     break;
   943                 case opc_goto: {
   944                     smapper.flush(out);
   945                     int indx = i + readShortArg(byteCodes, i);
   946                     goTo(out, i, indx, topMostLabel);
   947                     i += 2;
   948                     break;
   949                 }
   950                 case opc_lookupswitch: {
   951                     i = generateLookupSwitch(i, byteCodes, smapper, topMostLabel);
   952                     break;
   953                 }
   954                 case opc_tableswitch: {
   955                     i = generateTableSwitch(i, byteCodes, smapper, topMostLabel);
   956                     break;
   957                 }
   958                 case opc_invokeinterface: {
   959                     i = invokeVirtualMethod(byteCodes, i, smapper) + 2;
   960                     break;
   961                 }
   962                 case opc_invokevirtual:
   963                     i = invokeVirtualMethod(byteCodes, i, smapper);
   964                     break;
   965                 case opc_invokespecial:
   966                     i = invokeStaticMethod(byteCodes, i, smapper, false);
   967                     break;
   968                 case opc_invokestatic:
   969                     i = invokeStaticMethod(byteCodes, i, smapper, true);
   970                     break;
   971                 case opc_new: {
   972                     int indx = readUShortArg(byteCodes, i);
   973                     String ci = jc.getClassName(indx);
   974                     emit(smapper, out, "var @1 = new @2;",
   975                          smapper.pushA(), accessClass(mangleClassName(ci)));
   976                     addReference(ci);
   977                     i += 2;
   978                     break;
   979                 }
   980                 case opc_newarray:
   981                     int atype = readUByte(byteCodes, ++i);
   982                     generateNewArray(atype, smapper);
   983                     break;
   984                 case opc_anewarray: {
   985                     int type = readUShortArg(byteCodes, i);
   986                     i += 2;
   987                     generateANewArray(type, smapper);
   988                     break;
   989                 }
   990                 case opc_multianewarray: {
   991                     int type = readUShortArg(byteCodes, i);
   992                     i += 2;
   993                     i = generateMultiANewArray(type, byteCodes, i, smapper);
   994                     break;
   995                 }
   996                 case opc_arraylength:
   997                     emit(smapper, out, "var @2 = @1.length;",
   998                          smapper.popA(), smapper.pushI());
   999                     break;
  1000                 case opc_lastore:
  1001                     emit(smapper, out, "Array.at(@3, @2, @1);",
  1002                          smapper.popL(), smapper.popI(), smapper.popA());
  1003                     break;
  1004                 case opc_fastore:
  1005                     emit(smapper, out, "Array.at(@3, @2, @1);",
  1006                          smapper.popF(), smapper.popI(), smapper.popA());
  1007                     break;
  1008                 case opc_dastore:
  1009                     emit(smapper, out, "Array.at(@3, @2, @1);",
  1010                          smapper.popD(), smapper.popI(), smapper.popA());
  1011                     break;
  1012                 case opc_aastore:
  1013                     emit(smapper, out, "Array.at(@3, @2, @1);",
  1014                          smapper.popA(), smapper.popI(), smapper.popA());
  1015                     break;
  1016                 case opc_iastore:
  1017                 case opc_bastore:
  1018                 case opc_castore:
  1019                 case opc_sastore:
  1020                     emit(smapper, out, "Array.at(@3, @2, @1);",
  1021                          smapper.popI(), smapper.popI(), smapper.popA());
  1022                     break;
  1023                 case opc_laload:
  1024                     emit(smapper, out, "var @3 = Array.at(@2, @1);",
  1025                          smapper.popI(), smapper.popA(), smapper.pushL());
  1026                     break;
  1027                 case opc_faload:
  1028                     emit(smapper, out, "var @3 = Array.at(@2, @1);",
  1029                          smapper.popI(), smapper.popA(), smapper.pushF());
  1030                     break;
  1031                 case opc_daload:
  1032                     emit(smapper, out, "var @3 = Array.at(@2, @1);",
  1033                          smapper.popI(), smapper.popA(), smapper.pushD());
  1034                     break;
  1035                 case opc_aaload:
  1036                     emit(smapper, out, "var @3 = Array.at(@2, @1);",
  1037                          smapper.popI(), smapper.popA(), smapper.pushA());
  1038                     break;
  1039                 case opc_iaload:
  1040                 case opc_baload:
  1041                 case opc_caload:
  1042                 case opc_saload:
  1043                     emit(smapper, out, "var @3 = Array.at(@2, @1);",
  1044                          smapper.popI(), smapper.popA(), smapper.pushI());
  1045                     break;
  1046                 case opc_pop:
  1047                 case opc_pop2:
  1048                     smapper.pop(1);
  1049                     debug("/* pop */");
  1050                     break;
  1051                 case opc_dup: {
  1052                     final Variable v = smapper.get(0);
  1053                     emit(smapper, out, "var @1 = @2;", smapper.pushT(v.getType()), v);
  1054                     break;
  1055                 }
  1056                 case opc_dup2: {
  1057                     final Variable vi1 = smapper.get(0);
  1058 
  1059                     if (vi1.isCategory2()) {
  1060                         emit(smapper, out, "var @1 = @2;",
  1061                              smapper.pushT(vi1.getType()), vi1);
  1062                     } else {
  1063                         final Variable vi2 = smapper.get(1);
  1064                         emit(smapper, out, "var @1 = @2, @3 = @4;",
  1065                              smapper.pushT(vi2.getType()), vi2,
  1066                              smapper.pushT(vi1.getType()), vi1);
  1067                     }
  1068                     break;
  1069                 }
  1070                 case opc_dup_x1: {
  1071                     final Variable vi1 = smapper.pop(out);
  1072                     final Variable vi2 = smapper.pop(out);
  1073                     final Variable vo3 = smapper.pushT(vi1.getType());
  1074                     final Variable vo2 = smapper.pushT(vi2.getType());
  1075                     final Variable vo1 = smapper.pushT(vi1.getType());
  1076 
  1077                     emit(smapper, out, "var @1 = @2, @3 = @4, @5 = @6;",
  1078                          vo1, vi1, vo2, vi2, vo3, vo1);
  1079                     break;
  1080                 }
  1081                 case opc_dup2_x1: {
  1082                     final Variable vi1 = smapper.pop(out);
  1083                     final Variable vi2 = smapper.pop(out);
  1084 
  1085                     if (vi1.isCategory2()) {
  1086                         final Variable vo3 = smapper.pushT(vi1.getType());
  1087                         final Variable vo2 = smapper.pushT(vi2.getType());
  1088                         final Variable vo1 = smapper.pushT(vi1.getType());
  1089 
  1090                         emit(smapper, out, "var @1 = @2, @3 = @4, @5 = @6;",
  1091                              vo1, vi1, vo2, vi2, vo3, vo1);
  1092                     } else {
  1093                         final Variable vi3 = smapper.pop(out);
  1094                         final Variable vo5 = smapper.pushT(vi2.getType());
  1095                         final Variable vo4 = smapper.pushT(vi1.getType());
  1096                         final Variable vo3 = smapper.pushT(vi3.getType());
  1097                         final Variable vo2 = smapper.pushT(vi2.getType());
  1098                         final Variable vo1 = smapper.pushT(vi1.getType());
  1099 
  1100                         emit(smapper, out, "var @1 = @2, @3 = @4, @5 = @6,",
  1101                              vo1, vi1, vo2, vi2, vo3, vi3);
  1102                         emit(smapper, out, " @1 = @2, @3 = @4;",
  1103                              vo4, vo1, vo5, vo2);
  1104                     }
  1105                     break;
  1106                 }
  1107                 case opc_dup_x2: {
  1108                     final Variable vi1 = smapper.pop(out);
  1109                     final Variable vi2 = smapper.pop(out);
  1110 
  1111                     if (vi2.isCategory2()) {
  1112                         final Variable vo3 = smapper.pushT(vi1.getType());
  1113                         final Variable vo2 = smapper.pushT(vi2.getType());
  1114                         final Variable vo1 = smapper.pushT(vi1.getType());
  1115 
  1116                         emit(smapper, out, "var @1 = @2, @3 = @4, @5 = @6;",
  1117                              vo1, vi1, vo2, vi2, vo3, vo1);
  1118                     } else {
  1119                         final Variable vi3 = smapper.pop(out);
  1120                         final Variable vo4 = smapper.pushT(vi1.getType());
  1121                         final Variable vo3 = smapper.pushT(vi3.getType());
  1122                         final Variable vo2 = smapper.pushT(vi2.getType());
  1123                         final Variable vo1 = smapper.pushT(vi1.getType());
  1124 
  1125                         emit(smapper, out, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
  1126                              vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
  1127                     }
  1128                     break;
  1129                 }
  1130                 case opc_dup2_x2: {
  1131                     final Variable vi1 = smapper.pop(out);
  1132                     final Variable vi2 = smapper.pop(out);
  1133 
  1134                     if (vi1.isCategory2()) {
  1135                         if (vi2.isCategory2()) {
  1136                             final Variable vo3 = smapper.pushT(vi1.getType());
  1137                             final Variable vo2 = smapper.pushT(vi2.getType());
  1138                             final Variable vo1 = smapper.pushT(vi1.getType());
  1139 
  1140                             emit(smapper, out, "var @1 = @2, @3 = @4, @5 = @6;",
  1141                                  vo1, vi1, vo2, vi2, vo3, vo1);
  1142                         } else {
  1143                             final Variable vi3 = smapper.pop(out);
  1144                             final Variable vo4 = smapper.pushT(vi1.getType());
  1145                             final Variable vo3 = smapper.pushT(vi3.getType());
  1146                             final Variable vo2 = smapper.pushT(vi2.getType());
  1147                             final Variable vo1 = smapper.pushT(vi1.getType());
  1148 
  1149                             emit(smapper, out, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
  1150                                  vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
  1151                         }
  1152                     } else {
  1153                         final Variable vi3 = smapper.pop(out);
  1154 
  1155                         if (vi3.isCategory2()) {
  1156                             final Variable vo5 = smapper.pushT(vi2.getType());
  1157                             final Variable vo4 = smapper.pushT(vi1.getType());
  1158                             final Variable vo3 = smapper.pushT(vi3.getType());
  1159                             final Variable vo2 = smapper.pushT(vi2.getType());
  1160                             final Variable vo1 = smapper.pushT(vi1.getType());
  1161 
  1162                             emit(smapper, out, "var @1 = @2, @3 = @4, @5 = @6,",
  1163                                  vo1, vi1, vo2, vi2, vo3, vi3);
  1164                             emit(smapper, out, " @1 = @2, @3 = @4;",
  1165                                  vo4, vo1, vo5, vo2);
  1166                         } else {
  1167                             final Variable vi4 = smapper.pop(out);
  1168                             final Variable vo6 = smapper.pushT(vi2.getType());
  1169                             final Variable vo5 = smapper.pushT(vi1.getType());
  1170                             final Variable vo4 = smapper.pushT(vi4.getType());
  1171                             final Variable vo3 = smapper.pushT(vi3.getType());
  1172                             final Variable vo2 = smapper.pushT(vi2.getType());
  1173                             final Variable vo1 = smapper.pushT(vi1.getType());
  1174                             
  1175                             emit(smapper, out, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8,",
  1176                                  vo1, vi1, vo2, vi2, vo3, vi3, vo4, vi4);
  1177                             emit(smapper, out, " @1 = @2, @3 = @4;",
  1178                                  vo5, vo1, vo6, vo2);
  1179                         }
  1180                     }
  1181                     break;
  1182                 }
  1183                 case opc_swap: {
  1184                     final Variable vi1 = smapper.get(0);
  1185                     final Variable vi2 = smapper.get(1);
  1186 
  1187                     if (vi1.getType() == vi2.getType()) {
  1188                         final Variable tmp = smapper.pushT(vi1.getType());
  1189 
  1190                         emit(smapper, out, "var @1 = @2, @2 = @3, @3 = @1;",
  1191                              tmp, vi1, vi2);
  1192                         smapper.pop(1);
  1193                     } else {
  1194                         smapper.pop(2);
  1195                         smapper.pushT(vi1.getType());
  1196                         smapper.pushT(vi2.getType());
  1197                     }
  1198                     break;
  1199                 }
  1200                 case opc_bipush:
  1201                     emit(smapper, out, "var @1 = @2;",
  1202                          smapper.pushI(), Integer.toString(byteCodes[++i]));
  1203                     break;
  1204                 case opc_sipush:
  1205                     emit(smapper, out, "var @1 = @2;",
  1206                          smapper.pushI(),
  1207                          Integer.toString(readShortArg(byteCodes, i)));
  1208                     i += 2;
  1209                     break;
  1210                 case opc_getfield: {
  1211                     int indx = readUShortArg(byteCodes, i);
  1212                     String[] fi = jc.getFieldInfoName(indx);
  1213                     final int type = VarType.fromFieldType(fi[2].charAt(0));
  1214                     final String mangleClass = mangleClassName(fi[0]);
  1215                     final String mangleClassAccess = accessClass(mangleClass);
  1216                     emit(smapper, out, "var @2 = @4(false)._@3.call(@1);",
  1217                          smapper.popA(),
  1218                          smapper.pushT(type), fi[1], mangleClassAccess
  1219                     );
  1220                     i += 2;
  1221                     break;
  1222                 }
  1223                 case opc_putfield: {
  1224                     int indx = readUShortArg(byteCodes, i);
  1225                     String[] fi = jc.getFieldInfoName(indx);
  1226                     final int type = VarType.fromFieldType(fi[2].charAt(0));
  1227                     final String mangleClass = mangleClassName(fi[0]);
  1228                     final String mangleClassAccess = accessClass(mangleClass);
  1229                     emit(smapper, out, "@4(false)._@3.call(@2, @1);",
  1230                          smapper.popT(type),
  1231                          smapper.popA(), fi[1], 
  1232                          mangleClassAccess
  1233                     );
  1234                     i += 2;
  1235                     break;
  1236                 }
  1237                 case opc_getstatic: {
  1238                     int indx = readUShortArg(byteCodes, i);
  1239                     String[] fi = jc.getFieldInfoName(indx);
  1240                     final int type = VarType.fromFieldType(fi[2].charAt(0));
  1241                     emit(smapper, out, "var @1 = @2(false)._@3();",
  1242                          smapper.pushT(type),
  1243                          accessClass(mangleClassName(fi[0])), fi[1]);
  1244                     i += 2;
  1245                     addReference(fi[0]);
  1246                     break;
  1247                 }
  1248                 case opc_putstatic: {
  1249                     int indx = readUShortArg(byteCodes, i);
  1250                     String[] fi = jc.getFieldInfoName(indx);
  1251                     final int type = VarType.fromFieldType(fi[2].charAt(0));
  1252                     emit(smapper, out, "@1(false)._@2(@3);",
  1253                          accessClass(mangleClassName(fi[0])), fi[1],
  1254                          smapper.popT(type));
  1255                     i += 2;
  1256                     addReference(fi[0]);
  1257                     break;
  1258                 }
  1259                 case opc_checkcast: {
  1260                     int indx = readUShortArg(byteCodes, i);
  1261                     generateCheckcast(indx, smapper);
  1262                     i += 2;
  1263                     break;
  1264                 }
  1265                 case opc_instanceof: {
  1266                     int indx = readUShortArg(byteCodes, i);
  1267                     generateInstanceOf(indx, smapper);
  1268                     i += 2;
  1269                     break;
  1270                 }
  1271                 case opc_athrow: {
  1272                     final CharSequence v = smapper.popA();
  1273                     smapper.clear();
  1274 
  1275                     emit(smapper, out, "{ var @1 = @2; throw @2; }",
  1276                          smapper.pushA(), v);
  1277                     break;
  1278                 }
  1279 
  1280                 case opc_monitorenter: {
  1281                     out.append("/* monitor enter */");
  1282                     smapper.popA();
  1283                     break;
  1284                 }
  1285 
  1286                 case opc_monitorexit: {
  1287                     out.append("/* monitor exit */");
  1288                     smapper.popA();
  1289                     break;
  1290                 }
  1291 
  1292                 case opc_wide:
  1293                     wide = true;
  1294                     break;
  1295 
  1296                 default: {
  1297                     wide = false;
  1298                     emit(smapper, out, "throw 'unknown bytecode @1';",
  1299                          Integer.toString(c));
  1300                 }
  1301             }
  1302             if (debug(" //")) {
  1303                 generateByteCodeComment(prev, i, byteCodes);
  1304             }
  1305             out.append("\n");            
  1306         }
  1307         if (previousTrap != null) {
  1308             generateCatch(previousTrap, byteCodes.length, topMostLabel);
  1309         }
  1310         out.append("\n    }\n");
  1311         while (openBraces-- > 0) {
  1312             out.append('}');
  1313         }
  1314         out.append("\n};");
  1315     }
  1316 
  1317     private int generateIf(byte[] byteCodes, int i, final CharSequence v2, final CharSequence v1, final String test, int topMostLabel) throws IOException {
  1318         int indx = i + readShortArg(byteCodes, i);
  1319         out.append("if (").append(v1)
  1320            .append(' ').append(test).append(' ')
  1321            .append(v2).append(") ");
  1322         goTo(out, i, indx, topMostLabel);
  1323         return i + 2;
  1324     }
  1325     
  1326     private int readInt4(byte[] byteCodes, int offset) {
  1327         final int d = byteCodes[offset + 0] << 24;
  1328         final int c = byteCodes[offset + 1] << 16;
  1329         final int b = byteCodes[offset + 2] << 8;
  1330         final int a = byteCodes[offset + 3];
  1331         return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
  1332     }
  1333     private static int readUByte(byte[] byteCodes, int offset) {
  1334         return byteCodes[offset] & 0xff;
  1335     }
  1336 
  1337     private static int readUShort(byte[] byteCodes, int offset) {
  1338         return ((byteCodes[offset] & 0xff) << 8)
  1339                     | (byteCodes[offset + 1] & 0xff);
  1340     }
  1341     private static int readUShortArg(byte[] byteCodes, int offsetInstruction) {
  1342         return readUShort(byteCodes, offsetInstruction + 1);
  1343     }
  1344 
  1345     private static int readShort(byte[] byteCodes, int offset) {
  1346         int signed = byteCodes[offset];
  1347         byte b0 = (byte)signed;
  1348         return (b0 << 8) | (byteCodes[offset + 1] & 0xff);
  1349     }
  1350     private static int readShortArg(byte[] byteCodes, int offsetInstruction) {
  1351         return readShort(byteCodes, offsetInstruction + 1);
  1352     }
  1353 
  1354     private static void countArgs(String descriptor, char[] returnType, StringBuilder sig, StringBuilder cnt) {
  1355         int i = 0;
  1356         Boolean count = null;
  1357         boolean array = false;
  1358         sig.append("__");
  1359         int firstPos = sig.length();
  1360         while (i < descriptor.length()) {
  1361             char ch = descriptor.charAt(i++);
  1362             switch (ch) {
  1363                 case '(':
  1364                     count = true;
  1365                     continue;
  1366                 case ')':
  1367                     count = false;
  1368                     continue;
  1369                 case 'B': 
  1370                 case 'C': 
  1371                 case 'D': 
  1372                 case 'F': 
  1373                 case 'I': 
  1374                 case 'J': 
  1375                 case 'S': 
  1376                 case 'Z': 
  1377                     if (count) {
  1378                         if (array) {
  1379                             sig.append("_3");
  1380                         }
  1381                         sig.append(ch);
  1382                         if (ch == 'J' || ch == 'D') {
  1383                             cnt.append('1');
  1384                         } else {
  1385                             cnt.append('0');
  1386                         }
  1387                     } else {
  1388                         sig.insert(firstPos, ch);
  1389                         if (array) {
  1390                             returnType[0] = '[';
  1391                             sig.insert(firstPos, "_3");
  1392                         } else {
  1393                             returnType[0] = ch;
  1394                         }
  1395                     }
  1396                     array = false;
  1397                     continue;
  1398                 case 'V': 
  1399                     assert !count;
  1400                     returnType[0] = 'V';
  1401                     sig.insert(firstPos, 'V');
  1402                     continue;
  1403                 case 'L':
  1404                     int next = descriptor.indexOf(';', i);
  1405                     String realSig = mangleSig(descriptor, i - 1, next + 1);
  1406                     if (count) {
  1407                         if (array) {
  1408                             sig.append("_3");
  1409                         }
  1410                         sig.append(realSig);
  1411                         cnt.append('0');
  1412                     } else {
  1413                         sig.insert(firstPos, realSig);
  1414                         if (array) {
  1415                             sig.insert(firstPos, "_3");
  1416                         }
  1417                         returnType[0] = 'L';
  1418                     }
  1419                     i = next + 1;
  1420                     array = false;
  1421                     continue;
  1422                 case '[':
  1423                     array = true;
  1424                     continue;
  1425                 default:
  1426                     throw new IllegalStateException("Invalid char: " + ch);
  1427             }
  1428         }
  1429     }
  1430     
  1431     static String mangleSig(String sig) {
  1432         return mangleSig(sig, 0, sig.length());
  1433     }
  1434     
  1435     private static String mangleMethodName(String name) {
  1436         StringBuilder sb = new StringBuilder(name.length() * 2);
  1437         int last = name.length();
  1438         for (int i = 0; i < last; i++) {
  1439             final char ch = name.charAt(i);
  1440             switch (ch) {
  1441                 case '_': sb.append("_1"); break;
  1442                 default: sb.append(ch); break;
  1443             }
  1444         }
  1445         return sb.toString();
  1446     }
  1447     private static String mangleSig(String txt, int first, int last) {
  1448         StringBuilder sb = new StringBuilder((last - first) * 2);
  1449         for (int i = first; i < last; i++) {
  1450             final char ch = txt.charAt(i);
  1451             switch (ch) {
  1452                 case '/': sb.append('_'); break;
  1453                 case '_': sb.append("_1"); break;
  1454                 case ';': sb.append("_2"); break;
  1455                 case '[': sb.append("_3"); break;
  1456                 default: sb.append(ch); break;
  1457             }
  1458         }
  1459         return sb.toString();
  1460     }
  1461     
  1462     private static String mangleClassName(String name) {
  1463         return mangleSig(name);
  1464     }
  1465 
  1466     private static String findMethodName(MethodData m, StringBuilder cnt) {
  1467         StringBuilder name = new StringBuilder();
  1468         if ("<init>".equals(m.getName())) { // NOI18N
  1469             name.append("cons"); // NOI18N
  1470         } else if ("<clinit>".equals(m.getName())) { // NOI18N
  1471             name.append("class"); // NOI18N
  1472         } else {
  1473             name.append(mangleMethodName(m.getName()));
  1474         } 
  1475         
  1476         countArgs(m.getInternalSig(), new char[1], name, cnt);
  1477         return name.toString();
  1478     }
  1479 
  1480     static String findMethodName(String[] mi, StringBuilder cnt, char[] returnType) {
  1481         StringBuilder name = new StringBuilder();
  1482         String descr = mi[2];//mi.getDescriptor();
  1483         String nm= mi[1];
  1484         if ("<init>".equals(nm)) { // NOI18N
  1485             name.append("cons"); // NOI18N
  1486         } else {
  1487             name.append(mangleMethodName(nm));
  1488         }
  1489         countArgs(descr, returnType, name, cnt);
  1490         return name.toString();
  1491     }
  1492 
  1493     private int invokeStaticMethod(byte[] byteCodes, int i, final StackMapper mapper, boolean isStatic)
  1494     throws IOException {
  1495         int methodIndex = readUShortArg(byteCodes, i);
  1496         String[] mi = jc.getFieldInfoName(methodIndex);
  1497         char[] returnType = { 'V' };
  1498         StringBuilder cnt = new StringBuilder();
  1499         String mn = findMethodName(mi, cnt, returnType);
  1500 
  1501         final int numArguments = isStatic ? cnt.length() : cnt.length() + 1;
  1502         final CharSequence[] vars = new CharSequence[numArguments];
  1503 
  1504         for (int j = numArguments - 1; j >= 0; --j) {
  1505             vars[j] = mapper.popValue();
  1506         }
  1507 
  1508         if (returnType[0] != 'V') {
  1509             out.append("var ")
  1510                .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
  1511                .append(" = ");
  1512         }
  1513 
  1514         final String in = mi[0];
  1515         out.append(accessClass(mangleClassName(in)));
  1516         out.append("(false).");
  1517         if (mn.startsWith("cons_")) {
  1518             out.append("constructor.");
  1519         }
  1520         out.append(mn);
  1521         if (isStatic) {
  1522             out.append('(');
  1523         } else {
  1524             out.append(".call(");
  1525         }
  1526         if (numArguments > 0) {
  1527             out.append(vars[0]);
  1528             for (int j = 1; j < numArguments; ++j) {
  1529                 out.append(", ");
  1530                 out.append(vars[j]);
  1531             }
  1532         }
  1533         out.append(");");
  1534         i += 2;
  1535         addReference(in);
  1536         return i;
  1537     }
  1538     private int invokeVirtualMethod(byte[] byteCodes, int i, final StackMapper mapper)
  1539     throws IOException {
  1540         int methodIndex = readUShortArg(byteCodes, i);
  1541         String[] mi = jc.getFieldInfoName(methodIndex);
  1542         char[] returnType = { 'V' };
  1543         StringBuilder cnt = new StringBuilder();
  1544         String mn = findMethodName(mi, cnt, returnType);
  1545 
  1546         final int numArguments = cnt.length() + 1;
  1547         final CharSequence[] vars = new CharSequence[numArguments];
  1548 
  1549         for (int j = numArguments - 1; j >= 0; --j) {
  1550             vars[j] = mapper.popValue();
  1551         }
  1552 
  1553         if (returnType[0] != 'V') {
  1554             out.append("var ")
  1555                .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
  1556                .append(" = ");
  1557         }
  1558 
  1559         out.append(vars[0]).append('.');
  1560         out.append(mn);
  1561         out.append('(');
  1562         String sep = "";
  1563         for (int j = 1; j < numArguments; ++j) {
  1564             out.append(sep);
  1565             out.append(vars[j]);
  1566             sep = ", ";
  1567         }
  1568         out.append(");");
  1569         i += 2;
  1570         return i;
  1571     }
  1572 
  1573     private void addReference(String cn) throws IOException {
  1574         if (requireReference(cn)) {
  1575             debug(" /* needs " + cn + " */");
  1576         }
  1577     }
  1578 
  1579     private void outType(String d, StringBuilder out) {
  1580         int arr = 0;
  1581         while (d.charAt(0) == '[') {
  1582             out.append('A');
  1583             d = d.substring(1);
  1584         }
  1585         if (d.charAt(0) == 'L') {
  1586             assert d.charAt(d.length() - 1) == ';';
  1587             out.append(d.replace('/', '_').substring(0, d.length() - 1));
  1588         } else {
  1589             out.append(d);
  1590         }
  1591     }
  1592 
  1593     private String encodeConstant(int entryIndex) throws IOException {
  1594         String[] classRef = { null };
  1595         String s = jc.stringValue(entryIndex, classRef);
  1596         if (classRef[0] != null) {
  1597             if (classRef[0].startsWith("[")) {
  1598                 s = accessClass("java_lang_Class") + "(false).forName__Ljava_lang_Class_2Ljava_lang_String_2('" + classRef[0] + "');";
  1599             } else {
  1600                 addReference(classRef[0]);
  1601                 s = accessClass(mangleClassName(s)) + "(false).constructor.$class";
  1602             }
  1603         }
  1604         return s;
  1605     }
  1606 
  1607     private String javaScriptBody(String destObject, MethodData m, boolean isStatic) throws IOException {
  1608         byte[] arr = m.findAnnotationData(true);
  1609         if (arr == null) {
  1610             return null;
  1611         }
  1612         final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
  1613         final String htmlType = "Lnet/java/html/js/JavaScriptBody;";
  1614         class P extends AnnotationParser {
  1615             public P() {
  1616                 super(false, true);
  1617             }
  1618             
  1619             int cnt;
  1620             String[] args = new String[30];
  1621             String body;
  1622             boolean javacall;
  1623             boolean html4j;
  1624             
  1625             @Override
  1626             protected void visitAttr(String type, String attr, String at, String value) {
  1627                 if (type.equals(jvmType)) {
  1628                     if ("body".equals(attr)) {
  1629                         body = value;
  1630                     } else if ("args".equals(attr)) {
  1631                         args[cnt++] = value;
  1632                     } else {
  1633                         throw new IllegalArgumentException(attr);
  1634                     }
  1635                 }
  1636                 if (type.equals(htmlType)) {
  1637                     html4j = true;
  1638                     if ("body".equals(attr)) {
  1639                         body = value;
  1640                     } else if ("args".equals(attr)) {
  1641                         args[cnt++] = value;
  1642                     } else if ("javacall".equals(attr)) {
  1643                         javacall = "1".equals(value);
  1644                     } else {
  1645                         throw new IllegalArgumentException(attr);
  1646                     }
  1647                 }
  1648             }
  1649         }
  1650         P p = new P();
  1651         p.parse(arr, jc);
  1652         if (p.body == null) {
  1653             return null;
  1654         }
  1655         StringBuilder cnt = new StringBuilder();
  1656         final String mn = findMethodName(m, cnt);
  1657         out.append(destObject).append(".").append(mn);
  1658         out.append(" = function(");
  1659         String space = "";
  1660         int index = 0;
  1661         StringBuilder toValue = new StringBuilder();
  1662         for (int i = 0; i < cnt.length(); i++) {
  1663             out.append(space);
  1664             space = outputArg(out, p.args, index);
  1665             if (p.html4j && space.length() > 0) {
  1666                 toValue.append("\n  ").append(p.args[index]).append(" = vm.org_apidesign_bck2brwsr_emul_lang_System(false).toJS(").
  1667                     append(p.args[index]).append(");");
  1668             }
  1669             index++;
  1670         }
  1671         out.append(") {").append("\n");
  1672         out.append(toValue.toString());
  1673         if (p.javacall) {
  1674             int lastSlash = jc.getClassName().lastIndexOf('/');
  1675             final String pkg = jc.getClassName().substring(0, lastSlash);
  1676             out.append(mangleCallbacks(pkg, p.body));
  1677             requireReference(pkg + "/$JsCallbacks$");
  1678         } else {
  1679             out.append(p.body);
  1680         }
  1681         out.append("\n}\n");
  1682         return mn;
  1683     }
  1684     
  1685     private static CharSequence mangleCallbacks(String pkgName, String body) {
  1686         StringBuilder sb = new StringBuilder();
  1687         int pos = 0;
  1688         for (;;) {
  1689             int next = body.indexOf(".@", pos);
  1690             if (next == -1) {
  1691                 sb.append(body.substring(pos));
  1692                 body = sb.toString();
  1693                 break;
  1694             }
  1695             int ident = next;
  1696             while (ident > 0) {
  1697                 if (!Character.isJavaIdentifierPart(body.charAt(--ident))) {
  1698                     ident++;
  1699                     break;
  1700                 }
  1701             }
  1702             String refId = body.substring(ident, next);
  1703 
  1704             sb.append(body.substring(pos, ident));
  1705 
  1706             int sigBeg = body.indexOf('(', next);
  1707             int sigEnd = body.indexOf(')', sigBeg);
  1708             int colon4 = body.indexOf("::", next);
  1709             if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
  1710                 throw new IllegalStateException("Malformed body " + body);
  1711             }
  1712             String fqn = body.substring(next + 2, colon4);
  1713             String method = body.substring(colon4 + 2, sigBeg);
  1714             String params = body.substring(sigBeg, sigEnd + 1);
  1715 
  1716             int paramBeg = body.indexOf('(', sigEnd + 1);
  1717             
  1718             sb.append("vm.").append(pkgName.replace('/', '_')).append("_$JsCallbacks$(false)._VM().");
  1719             sb.append(mangleJsCallbacks(fqn, method, params, false));
  1720             sb.append("(").append(refId);
  1721             if (body.charAt(paramBeg + 1) != ')') {
  1722                 sb.append(",");
  1723             }
  1724             pos = paramBeg + 1;
  1725         }
  1726         sb = null;
  1727         pos = 0;
  1728         for (;;) {
  1729             int next = body.indexOf("@", pos);
  1730             if (next == -1) {
  1731                 if (sb == null) {
  1732                     return body;
  1733                 }
  1734                 sb.append(body.substring(pos));
  1735                 return sb;
  1736             }
  1737             if (sb == null) {
  1738                 sb = new StringBuilder();
  1739             }
  1740 
  1741             sb.append(body.substring(pos, next));
  1742 
  1743             int sigBeg = body.indexOf('(', next);
  1744             int sigEnd = body.indexOf(')', sigBeg);
  1745             int colon4 = body.indexOf("::", next);
  1746             if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
  1747                 throw new IllegalStateException("Malformed body " + body);
  1748             }
  1749             String fqn = body.substring(next + 1, colon4);
  1750             String method = body.substring(colon4 + 2, sigBeg);
  1751             String params = body.substring(sigBeg, sigEnd + 1);
  1752 
  1753             int paramBeg = body.indexOf('(', sigEnd + 1);
  1754             
  1755             sb.append("vm.").append(pkgName.replace('/', '_')).append("_$JsCallbacks$(false)._VM().");
  1756             sb.append(mangleJsCallbacks(fqn, method, params, true));
  1757             sb.append("(");
  1758             pos = paramBeg + 1;
  1759         }
  1760     }
  1761 
  1762     static String mangleJsCallbacks(String fqn, String method, String params, boolean isStatic) {
  1763         if (params.startsWith("(")) {
  1764             params = params.substring(1);
  1765         }
  1766         if (params.endsWith(")")) {
  1767             params = params.substring(0, params.length() - 1);
  1768         }
  1769         StringBuilder sb = new StringBuilder();
  1770         final String fqnu = fqn.replace('.', '_');
  1771         final String rfqn = mangleClassName(fqnu);
  1772         final String rm = mangleMethodName(method);
  1773         final String srp;
  1774         {
  1775             StringBuilder pb = new StringBuilder();
  1776             int len = params.length();
  1777             int indx = 0;
  1778             while (indx < len) {
  1779                 char ch = params.charAt(indx);
  1780                 if (ch == '[' || ch == 'L') {
  1781                     pb.append("Ljava/lang/Object;");
  1782                     indx = params.indexOf(';', indx) + 1;
  1783                 } else {
  1784                     pb.append(ch);
  1785                     indx++;
  1786                 }
  1787             }
  1788             srp = mangleSig(pb.toString());
  1789         }
  1790         final String rp = mangleSig(params);
  1791         final String mrp = mangleMethodName(rp);
  1792         sb.append(rfqn).append("$").append(rm).
  1793             append('$').append(mrp).append("__Ljava_lang_Object_2");
  1794         if (!isStatic) {
  1795             sb.append('L').append(fqnu).append("_2");
  1796         }
  1797         sb.append(srp);
  1798         return sb.toString();
  1799     }
  1800 
  1801     private static String className(ClassData jc) {
  1802         //return jc.getName().getInternalName().replace('/', '_');
  1803         return mangleClassName(jc.getClassName());
  1804     }
  1805     
  1806     private static String[] findAnnotation(
  1807         byte[] arr, ClassData cd, final String className, 
  1808         final String... attrNames
  1809     ) throws IOException {
  1810         if (arr == null) {
  1811             return null;
  1812         }
  1813         final String[] values = new String[attrNames.length];
  1814         final boolean[] found = { false };
  1815         final String jvmType = "L" + className.replace('.', '/') + ";";
  1816         AnnotationParser ap = new AnnotationParser(false, true) {
  1817             @Override
  1818             protected void visitAttr(String type, String attr, String at, String value) {
  1819                 if (type.equals(jvmType)) {
  1820                     found[0] = true;
  1821                     for (int i = 0; i < attrNames.length; i++) {
  1822                         if (attrNames[i].equals(attr)) {
  1823                             values[i] = value;
  1824                         }
  1825                     }
  1826                 }
  1827             }
  1828             
  1829         };
  1830         ap.parse(arr, cd);
  1831         return found[0] ? values : null;
  1832     }
  1833 
  1834     private CharSequence initField(FieldData v) {
  1835         final String is = v.getInternalSig();
  1836         if (is.length() == 1) {
  1837             switch (is.charAt(0)) {
  1838                 case 'S':
  1839                 case 'J':
  1840                 case 'B':
  1841                 case 'Z':
  1842                 case 'C':
  1843                 case 'I': return " = 0;";
  1844                 case 'F': 
  1845                 case 'D': return " = 0.0;";
  1846                 default:
  1847                     throw new IllegalStateException(is);
  1848             }
  1849         }
  1850         return " = null;";
  1851     }
  1852 
  1853     private void generateAnno(ClassData cd, final Appendable out, byte[] data) throws IOException {
  1854         AnnotationParser ap = new AnnotationParser(true, false) {
  1855             int[] cnt = new int[32];
  1856             int depth;
  1857             
  1858             @Override
  1859             protected void visitAnnotationStart(String attrType, boolean top) throws IOException {
  1860                 final String slashType = attrType.substring(1, attrType.length() - 1);
  1861                 requireReference(slashType);
  1862                 
  1863                 if (cnt[depth]++ > 0) {
  1864                     out.append(",");
  1865                 }
  1866                 if (top) {
  1867                     out.append('"').append(attrType).append("\" : ");
  1868                 }
  1869                 out.append("{\n");
  1870                 cnt[++depth] = 0;
  1871             }
  1872 
  1873             @Override
  1874             protected void visitAnnotationEnd(String type, boolean top) throws IOException {
  1875                 out.append("\n}\n");
  1876                 depth--;
  1877             }
  1878 
  1879             @Override
  1880             protected void visitValueStart(String attrName, char type) throws IOException {
  1881                 if (cnt[depth]++ > 0) {
  1882                     out.append(",\n");
  1883                 }
  1884                 cnt[++depth] = 0;
  1885                 if (attrName != null) {
  1886                     out.append(attrName).append(" : ");
  1887                 }
  1888                 if (type == '[') {
  1889                     out.append("[");
  1890                 }
  1891             }
  1892 
  1893             @Override
  1894             protected void visitValueEnd(String attrName, char type) throws IOException {
  1895                 if (type == '[') {
  1896                     out.append("]");
  1897                 }
  1898                 depth--;
  1899             }
  1900             
  1901             @Override
  1902             protected void visitAttr(String type, String attr, String attrType, String value) 
  1903             throws IOException {
  1904                 if (attr == null && value == null) {
  1905                     return;
  1906                 }
  1907                 out.append(value);
  1908             }
  1909 
  1910             @Override
  1911             protected void visitEnumAttr(String type, String attr, String attrType, String value) 
  1912             throws IOException {
  1913                 final String slashType = attrType.substring(1, attrType.length() - 1);
  1914                 requireReference(slashType);
  1915                 
  1916                 out.append(accessClass(mangleClassName(slashType)))
  1917                    .append("(false).constructor.fld_").append(value);
  1918             }
  1919         };
  1920         ap.parse(data, cd);
  1921     }
  1922 
  1923     private static String outputArg(Appendable out, String[] args, int indx) throws IOException {
  1924         final String name = args[indx];
  1925         if (name == null) {
  1926             return "";
  1927         }
  1928         if (name.contains(",")) {
  1929             throw new IOException("Wrong parameter with ',': " + name);
  1930         }
  1931         out.append(name);
  1932         return ",";
  1933     }
  1934 
  1935     final void emit(
  1936         StackMapper sm, 
  1937         final Appendable out, 
  1938         final String format, final CharSequence... params
  1939     ) throws IOException {
  1940         sm.flush(out);
  1941         emitImpl(out, format, params);
  1942     }
  1943     static void emitImpl(final Appendable out,
  1944                              final String format,
  1945                              final CharSequence... params) throws IOException {
  1946         final int length = format.length();
  1947 
  1948         int processed = 0;
  1949         int paramOffset = format.indexOf('@');
  1950         while ((paramOffset != -1) && (paramOffset < (length - 1))) {
  1951             final char paramChar = format.charAt(paramOffset + 1);
  1952             if ((paramChar >= '1') && (paramChar <= '9')) {
  1953                 final int paramIndex = paramChar - '0' - 1;
  1954 
  1955                 out.append(format, processed, paramOffset);
  1956                 out.append(params[paramIndex]);
  1957 
  1958                 ++paramOffset;
  1959                 processed = paramOffset + 1;
  1960             }
  1961 
  1962             paramOffset = format.indexOf('@', paramOffset + 1);
  1963         }
  1964 
  1965         out.append(format, processed, length);
  1966     }
  1967 
  1968     private void generateCatch(TrapData[] traps, int current, int topMostLabel) throws IOException {
  1969         out.append("} catch (e) {\n");
  1970         int finallyPC = -1;
  1971         for (TrapData e : traps) {
  1972             if (e == null) {
  1973                 break;
  1974             }
  1975             if (e.catch_cpx != 0) { //not finally
  1976                 final String classInternalName = jc.getClassName(e.catch_cpx);
  1977                 addReference(classInternalName);
  1978                 out.append("e = vm.java_lang_Throwable(false).bck2BrwsrCnvrt(e);");
  1979                 out.append("if (e.$instOf_" + classInternalName.replace('/', '_') + ") {");
  1980                 out.append("var stA0 = e;");
  1981                 goTo(out, current, e.handler_pc, topMostLabel);
  1982                 out.append("}\n");
  1983             } else {
  1984                 finallyPC = e.handler_pc;
  1985             }
  1986         }
  1987         if (finallyPC == -1) {
  1988             out.append("throw e;");
  1989         } else {
  1990             out.append("var stA0 = e;");
  1991             goTo(out, current, finallyPC, topMostLabel);
  1992         }
  1993         out.append("\n}");
  1994     }
  1995 
  1996     private static void goTo(Appendable out, int current, int to, int canBack) throws IOException {
  1997         if (to < current) {
  1998             if (canBack < to) {
  1999                 out.append("{ gt = 0; continue X_" + to + "; }");
  2000             } else {
  2001                 out.append("{ gt = " + to + "; continue X_0; }");
  2002             }
  2003         } else {
  2004             out.append("{ gt = " + to + "; break IF; }");
  2005         }
  2006     }
  2007 
  2008     private static void emitIf(
  2009         StackMapper sm, 
  2010         Appendable out, String pattern, 
  2011         CharSequence param, 
  2012         int current, int to, int canBack
  2013     ) throws IOException {
  2014         sm.flush(out);
  2015         emitImpl(out, pattern, param);
  2016         goTo(out, current, to, canBack);
  2017     }
  2018 
  2019     private void generateNewArray(int atype, final StackMapper smapper) throws IOException, IllegalStateException {
  2020         String jvmType;
  2021         switch (atype) {
  2022             case 4: jvmType = "[Z"; break;
  2023             case 5: jvmType = "[C"; break;
  2024             case 6: jvmType = "[F"; break;
  2025             case 7: jvmType = "[D"; break;
  2026             case 8: jvmType = "[B"; break;
  2027             case 9: jvmType = "[S"; break;
  2028             case 10: jvmType = "[I"; break;
  2029             case 11: jvmType = "[J"; break;
  2030             default: throw new IllegalStateException("Array type: " + atype);
  2031         }
  2032         emit(smapper, out, "var @2 = Array.prototype.newArray__Ljava_lang_Object_2ZLjava_lang_String_2I(true, '@3', @1);",
  2033              smapper.popI(), smapper.pushA(), jvmType);
  2034     }
  2035 
  2036     private void generateANewArray(int type, final StackMapper smapper) throws IOException {
  2037         String typeName = jc.getClassName(type);
  2038         if (typeName.startsWith("[")) {
  2039             typeName = "[" + typeName;
  2040         } else {
  2041             typeName = "[L" + typeName + ";";
  2042         }
  2043         emit(smapper, out, "var @2 = Array.prototype.newArray__Ljava_lang_Object_2ZLjava_lang_String_2I(false, '@3', @1);",
  2044              smapper.popI(), smapper.pushA(), typeName);
  2045     }
  2046 
  2047     private int generateMultiANewArray(int type, final byte[] byteCodes, int i, final StackMapper smapper) throws IOException {
  2048         String typeName = jc.getClassName(type);
  2049         int dim = readUByte(byteCodes, ++i);
  2050         StringBuilder dims = new StringBuilder();
  2051         dims.append('[');
  2052         for (int d = 0; d < dim; d++) {
  2053             if (d != 0) {
  2054                 dims.insert(1, ",");
  2055             }
  2056             dims.insert(1, smapper.popI());
  2057         }
  2058         dims.append(']');
  2059         emit(smapper, out, "var @2 = Array.prototype.multiNewArray__Ljava_lang_Object_2Ljava_lang_String_2_3II('@3', @1, 0);",
  2060              dims.toString(), smapper.pushA(), typeName);
  2061         return i;
  2062     }
  2063 
  2064     private int generateTableSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
  2065         int table = i / 4 * 4 + 4;
  2066         int dflt = i + readInt4(byteCodes, table);
  2067         table += 4;
  2068         int low = readInt4(byteCodes, table);
  2069         table += 4;
  2070         int high = readInt4(byteCodes, table);
  2071         table += 4;
  2072         out.append("switch (").append(smapper.popI()).append(") {\n");
  2073         while (low <= high) {
  2074             int offset = i + readInt4(byteCodes, table);
  2075             table += 4;
  2076             out.append("  case " + low).append(":"); goTo(out, i, offset, topMostLabel); out.append('\n');
  2077             low++;
  2078         }
  2079         out.append("  default: ");
  2080         goTo(out, i, dflt, topMostLabel);
  2081         out.append("\n}");
  2082         i = table - 1;
  2083         return i;
  2084     }
  2085 
  2086     private int generateLookupSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
  2087         int table = i / 4 * 4 + 4;
  2088         int dflt = i + readInt4(byteCodes, table);
  2089         table += 4;
  2090         int n = readInt4(byteCodes, table);
  2091         table += 4;
  2092         out.append("switch (").append(smapper.popI()).append(") {\n");
  2093         while (n-- > 0) {
  2094             int cnstnt = readInt4(byteCodes, table);
  2095             table += 4;
  2096             int offset = i + readInt4(byteCodes, table);
  2097             table += 4;
  2098             out.append("  case " + cnstnt).append(": "); goTo(out, i, offset, topMostLabel); out.append('\n');
  2099         }
  2100         out.append("  default: ");
  2101         goTo(out, i, dflt, topMostLabel);
  2102         out.append("\n}");
  2103         i = table - 1;
  2104         return i;
  2105     }
  2106 
  2107     private void generateInstanceOf(int indx, final StackMapper smapper) throws IOException {
  2108         final String type = jc.getClassName(indx);
  2109         if (!type.startsWith("[")) {
  2110             emit(smapper, out, "var @2 = @1 != null && @1.$instOf_@3 ? 1 : 0;",
  2111                  smapper.popA(), smapper.pushI(),
  2112                  type.replace('/', '_'));
  2113         } else {
  2114             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);",
  2115                 smapper.popA(), smapper.pushI(),
  2116                 type
  2117             );
  2118         }
  2119     }
  2120 
  2121     private void generateCheckcast(int indx, final StackMapper smapper) throws IOException {
  2122         final String type = jc.getClassName(indx);
  2123         if (!type.startsWith("[")) {
  2124             emit(smapper, out,
  2125                  "if (@1 !== null && !@1.$instOf_@2) throw vm.java_lang_ClassCastException(true);",
  2126                  smapper.getA(0), type.replace('/', '_'));
  2127         } else {
  2128             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);",
  2129                  smapper.getA(0), type
  2130             );
  2131         }
  2132     }
  2133 
  2134     private void generateByteCodeComment(int prev, int i, final byte[] byteCodes) throws IOException {
  2135         for (int j = prev; j <= i; j++) {
  2136             out.append(" ");
  2137             final int cc = readUByte(byteCodes, j);
  2138             out.append(Integer.toString(cc));
  2139         }
  2140     }
  2141 }