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