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