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