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