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