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