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