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