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