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