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