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