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