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