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