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