vm/src/main/java/org/apidesign/vm4brwsr/ByteCodeToJavaScript.java
author Lubomir Nerad <lubomir.nerad@oracle.com>
Fri, 18 Jan 2013 15:33:03 +0100
branchregisters
changeset 474 859cc3a0b8f0
parent 459 a2871a3fd4c5
child 488 9288ecf9657c
child 585 fe1a07c17681
permissions -rw-r--r--
Var is the Answer
     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 org.apidesign.javap.AnnotationParser;
    24 import org.apidesign.javap.ClassData;
    25 import org.apidesign.javap.FieldData;
    26 import org.apidesign.javap.MethodData;
    27 import org.apidesign.javap.StackMapIterator;
    28 import static org.apidesign.javap.RuntimeConstants.*;
    29 import org.apidesign.javap.TrapData;
    30 import org.apidesign.javap.TrapDataIterator;
    31 
    32 /** Translator of the code inside class files to JavaScript.
    33  *
    34  * @author Jaroslav Tulach <jtulach@netbeans.org>
    35  */
    36 abstract class ByteCodeToJavaScript {
    37     private ClassData jc;
    38     final Appendable out;
    39 
    40     protected ByteCodeToJavaScript(Appendable out) {
    41         this.out = out;
    42     }
    43     
    44     /* Collects additional required resources.
    45      * 
    46      * @param internalClassName classes that were referenced and should be loaded in order the
    47      *   generated JavaScript code works properly. The names are in internal 
    48      *   JVM form so String is <code>java/lang/String</code>. 
    49      */
    50     protected abstract boolean requireReference(String internalClassName);
    51     
    52     /*
    53      * @param resourcePath name of resources to read
    54      */
    55     protected abstract void requireScript(String resourcePath);
    56     
    57     /** Allows subclasses to redefine what field a function representing a
    58      * class gets assigned. By default it returns the suggested name followed
    59      * by <code>" = "</code>;
    60      * 
    61      * @param className suggested name of the class
    62      */
    63     /* protected */ String assignClass(String className) {
    64         return className + " = ";
    65     }
    66     /* protected */ String accessClass(String classOperation) {
    67         return classOperation;
    68     }
    69     
    70     /** Prints out a debug message. 
    71      * 
    72      * @param msg the message
    73      * @return true if the message has been printed
    74      * @throws IOException 
    75      */
    76     boolean debug(String msg) throws IOException {
    77         out.append(msg);
    78         return true;
    79     }
    80 
    81     /**
    82      * Converts a given class file to a JavaScript version.
    83      *
    84      * @param classFile input stream with code of the .class file
    85      * @return the initialization code for this class, if any. Otherwise <code>null</code>
    86      * 
    87      * @throws IOException if something goes wrong during read or write or translating
    88      */
    89     
    90     public String compile(InputStream classFile) throws IOException {
    91         this.jc = new ClassData(classFile);
    92         if (jc.getMajor_version() < 50) {
    93             throw new IOException("Can't compile " + jc.getClassName() + ". Class file version " + jc.getMajor_version() + "."
    94                 + jc.getMinor_version() + " - recompile with -target 1.6 (at least)."
    95             );
    96         }
    97         byte[] arrData = jc.findAnnotationData(true);
    98         String[] arr = findAnnotation(arrData, jc, 
    99             "org.apidesign.bck2brwsr.core.ExtraJavaScript", 
   100             "resource", "processByteCode"
   101         );
   102         if (arr != null) {
   103             requireScript(arr[0]);
   104             if ("0".equals(arr[1])) {
   105                 return null;
   106             }
   107         }
   108         String[] proto = findAnnotation(arrData, jc, 
   109             "org.apidesign.bck2brwsr.core.JavaScriptPrototype", 
   110             "container", "prototype"
   111         );
   112         StringArray toInitilize = new StringArray();
   113         final String className = className(jc);
   114         out.append("\n\n").append(assignClass(className));
   115         out.append("function CLS() {");
   116         out.append("\n  if (!CLS.prototype.$instOf_").append(className).append(") {");
   117         for (FieldData v : jc.getFields()) {
   118             if (v.isStatic()) {
   119                 out.append("\n  CLS.").append(v.getName()).append(initField(v));
   120             }
   121         }
   122         if (proto == null) {
   123             String sc = jc.getSuperClassName(); // with _
   124             out.append("\n    var pp = ").
   125                 append(accessClass(sc.replace('/', '_'))).append("(true);");
   126             out.append("\n    var p = CLS.prototype = pp;");
   127             out.append("\n    var c = p;");
   128             out.append("\n    var sprcls = pp.constructor.$class;");
   129         } else {
   130             out.append("\n    var p = CLS.prototype = ").append(proto[1]).append(";");
   131             if (proto[0] == null) {
   132                 proto[0] = "p";
   133             }
   134             out.append("\n    var c = ").append(proto[0]).append(";");
   135             out.append("\n    var sprcls = null;");
   136         }
   137         for (MethodData m : jc.getMethods()) {
   138             byte[] onlyArr = m.findAnnotationData(true);
   139             String[] only = findAnnotation(onlyArr, jc, 
   140                 "org.apidesign.bck2brwsr.core.JavaScriptOnly", 
   141                 "name", "value"
   142             );
   143             if (only != null) {
   144                 if (only[0] != null && only[1] != null) {
   145                     out.append("\n    p.").append(only[0]).append(" = ")
   146                         .append(only[1]).append(";");
   147                 }
   148                 continue;
   149             }
   150             String prefix;
   151             String mn;
   152             if (m.isStatic()) {
   153                 prefix = "\n    c.";
   154                 mn = generateStaticMethod(prefix, m, toInitilize);
   155             } else {
   156                 if (m.isConstructor()) {
   157                     prefix = "\n    CLS.";
   158                     mn = generateInstanceMethod(prefix, m);
   159                 } else {
   160                     prefix = "\n    c.";
   161                     mn = generateInstanceMethod(prefix, m);
   162                 }
   163             }
   164             byte[] runAnno = m.findAnnotationData(false);
   165             if (runAnno != null) {
   166                 out.append(prefix).append(mn).append(".anno = {");
   167                 generateAnno(jc, out, runAnno);
   168                 out.append("\n    };");
   169             }
   170             out.append(prefix).append(mn).append(".access = " + m.getAccess()).append(";");
   171         }
   172         out.append("\n    c.constructor = CLS;");
   173         out.append("\n    c.$instOf_").append(className).append(" = true;");
   174         for (String superInterface : jc.getSuperInterfaces()) {
   175             out.append("\n    c.$instOf_").append(superInterface.replace('/', '_')).append(" = true;");
   176         }
   177         out.append("\n    CLS.$class = ");
   178         out.append(accessClass("java_lang_Class(true);"));
   179         out.append("\n    CLS.$class.jvmName = '").append(jc.getClassName()).append("';");
   180         out.append("\n    CLS.$class.superclass = sprcls;");
   181         out.append("\n    CLS.$class.access = ").append(jc.getAccessFlags()+";");
   182         out.append("\n    CLS.$class.cnstr = CLS;");
   183         byte[] classAnno = jc.findAnnotationData(false);
   184         if (classAnno != null) {
   185             out.append("\n    CLS.$class.anno = {");
   186             generateAnno(jc, out, classAnno);
   187             out.append("\n    };");
   188         }
   189         out.append("\n  }");
   190         out.append("\n  if (arguments.length === 0) {");
   191         out.append("\n    if (!(this instanceof CLS)) {");
   192         out.append("\n      return new CLS();");
   193         out.append("\n    }");
   194         for (FieldData v : jc.getFields()) {
   195             byte[] onlyArr = v.findAnnotationData(true);
   196             String[] only = findAnnotation(onlyArr, jc, 
   197                 "org.apidesign.bck2brwsr.core.JavaScriptOnly", 
   198                 "name", "value"
   199             );
   200             if (only != null) {
   201                 if (only[0] != null && only[1] != null) {
   202                     out.append("\n    p.").append(only[0]).append(" = ")
   203                         .append(only[1]).append(";");
   204                 }
   205                 continue;
   206             }
   207             if (!v.isStatic()) {
   208                 out.append("\n    this.fld_").
   209                     append(v.getName()).append(initField(v));
   210             }
   211         }
   212         out.append("\n    return this;");
   213         out.append("\n  }");
   214         out.append("\n  return arguments[0] ? new CLS() : CLS.prototype;");
   215         out.append("\n}");
   216         StringBuilder sb = new StringBuilder();
   217         for (String init : toInitilize.toArray()) {
   218             sb.append("\n").append(init).append("();");
   219         }
   220         return sb.toString();
   221     }
   222     private String generateStaticMethod(String prefix, MethodData m, StringArray toInitilize) throws IOException {
   223         String jsb = javaScriptBody(prefix, m, true);
   224         if (jsb != null) {
   225             return jsb;
   226         }
   227         final String mn = findMethodName(m, new StringBuilder());
   228         if (mn.equals("class__V")) {
   229             toInitilize.add(accessClass(className(jc)) + "(false)." + mn);
   230         }
   231         generateMethod(prefix, mn, m);
   232         return mn;
   233     }
   234 
   235     private String generateInstanceMethod(String prefix, MethodData m) throws IOException {
   236         String jsb = javaScriptBody(prefix, m, false);
   237         if (jsb != null) {
   238             return jsb;
   239         }
   240         final String mn = findMethodName(m, new StringBuilder());
   241         generateMethod(prefix, mn, m);
   242         return mn;
   243     }
   244 
   245     private void generateMethod(String prefix, String name, MethodData m)
   246             throws IOException {
   247         final StackMapIterator stackMapIterator = m.createStackMapIterator();
   248         TrapDataIterator trap = m.getTrapDataIterator();
   249         final LocalsMapper lmapper =
   250                 new LocalsMapper(stackMapIterator.getArguments());
   251 
   252         out.append(prefix).append(name).append(" = function(");
   253         lmapper.outputArguments(out, m.isStatic());
   254         out.append(") {").append("\n");
   255 
   256         final byte[] byteCodes = m.getCode();
   257         if (byteCodes == null) {
   258             out.append("  throw 'no code found for ")
   259                .append(jc.getClassName()).append('.')
   260                .append(m.getName()).append("';\n");
   261             out.append("};");
   262             return;
   263         }
   264 
   265         final StackMapper smapper = new StackMapper();
   266 
   267         if (!m.isStatic()) {
   268             out.append("  var ").append(" lcA0 = this;\n");
   269         }
   270 
   271         int lastStackFrame = -1;
   272         TrapData[] previousTrap = null;
   273         
   274         out.append("\n  var gt = 0;\n  for(;;) switch(gt) {\n");
   275         for (int i = 0; i < byteCodes.length; i++) {
   276             int prev = i;
   277             stackMapIterator.advanceTo(i);
   278             boolean changeInCatch = trap.advanceTo(i);
   279             if (changeInCatch || lastStackFrame != stackMapIterator.getFrameIndex()) {
   280                 if (previousTrap != null) {
   281                     generateCatch(previousTrap);
   282                     previousTrap = null;
   283                 }
   284             }
   285             if (lastStackFrame != stackMapIterator.getFrameIndex()) {
   286                 lastStackFrame = stackMapIterator.getFrameIndex();
   287                 lmapper.syncWithFrameLocals(stackMapIterator.getFrameLocals());
   288                 smapper.syncWithFrameStack(stackMapIterator.getFrameStack());
   289                 out.append("    case " + i).append(": ");            
   290                 changeInCatch = true;
   291             } else {
   292                 debug("    /* " + i + " */ ");
   293             }
   294             if (changeInCatch && trap.useTry()) {
   295                 out.append("try {");
   296                 previousTrap = trap.current();
   297             }
   298             final int c = readByte(byteCodes, i);
   299             switch (c) {
   300                 case opc_aload_0:
   301                     emit(out, "var @1 = @2;", smapper.pushA(), lmapper.getA(0));
   302                     break;
   303                 case opc_iload_0:
   304                     emit(out, "var @1 = @2;", smapper.pushI(), lmapper.getI(0));
   305                     break;
   306                 case opc_lload_0:
   307                     emit(out, "var @1 = @2;", smapper.pushL(), lmapper.getL(0));
   308                     break;
   309                 case opc_fload_0:
   310                     emit(out, "var @1 = @2;", smapper.pushF(), lmapper.getF(0));
   311                     break;
   312                 case opc_dload_0:
   313                     emit(out, "var @1 = @2;", smapper.pushD(), lmapper.getD(0));
   314                     break;
   315                 case opc_aload_1:
   316                     emit(out, "var @1 = @2;", smapper.pushA(), lmapper.getA(1));
   317                     break;
   318                 case opc_iload_1:
   319                     emit(out, "var @1 = @2;", smapper.pushI(), lmapper.getI(1));
   320                     break;
   321                 case opc_lload_1:
   322                     emit(out, "var @1 = @2;", smapper.pushL(), lmapper.getL(1));
   323                     break;
   324                 case opc_fload_1:
   325                     emit(out, "var @1 = @2;", smapper.pushF(), lmapper.getF(1));
   326                     break;
   327                 case opc_dload_1:
   328                     emit(out, "var @1 = @2;", smapper.pushD(), lmapper.getD(1));
   329                     break;
   330                 case opc_aload_2:
   331                     emit(out, "var @1 = @2;", smapper.pushA(), lmapper.getA(2));
   332                     break;
   333                 case opc_iload_2:
   334                     emit(out, "var @1 = @2;", smapper.pushI(), lmapper.getI(2));
   335                     break;
   336                 case opc_lload_2:
   337                     emit(out, "var @1 = @2;", smapper.pushL(), lmapper.getL(2));
   338                     break;
   339                 case opc_fload_2:
   340                     emit(out, "var @1 = @2;", smapper.pushF(), lmapper.getF(2));
   341                     break;
   342                 case opc_dload_2:
   343                     emit(out, "var @1 = @2;", smapper.pushD(), lmapper.getD(2));
   344                     break;
   345                 case opc_aload_3:
   346                     emit(out, "var @1 = @2;", smapper.pushA(), lmapper.getA(3));
   347                     break;
   348                 case opc_iload_3:
   349                     emit(out, "var @1 = @2;", smapper.pushI(), lmapper.getI(3));
   350                     break;
   351                 case opc_lload_3:
   352                     emit(out, "var @1 = @2;", smapper.pushL(), lmapper.getL(3));
   353                     break;
   354                 case opc_fload_3:
   355                     emit(out, "var @1 = @2;", smapper.pushF(), lmapper.getF(3));
   356                     break;
   357                 case opc_dload_3:
   358                     emit(out, "var @1 = @2;", smapper.pushD(), lmapper.getD(3));
   359                     break;
   360                 case opc_iload: {
   361                     final int indx = readByte(byteCodes, ++i);
   362                     emit(out, "var @1 = @2;",
   363                          smapper.pushI(), lmapper.getI(indx));
   364                     break;
   365                 }
   366                 case opc_lload: {
   367                     final int indx = readByte(byteCodes, ++i);
   368                     emit(out, "var @1 = @2;",
   369                          smapper.pushL(), lmapper.getL(indx));
   370                     break;
   371                 }
   372                 case opc_fload: {
   373                     final int indx = readByte(byteCodes, ++i);
   374                     emit(out, "var @1 = @2;",
   375                          smapper.pushF(), lmapper.getF(indx));
   376                     break;
   377                 }
   378                 case opc_dload: {
   379                     final int indx = readByte(byteCodes, ++i);
   380                     emit(out, "var @1 = @2;",
   381                          smapper.pushD(), lmapper.getD(indx));
   382                     break;
   383                 }
   384                 case opc_aload: {
   385                     final int indx = readByte(byteCodes, ++i);
   386                     emit(out, "var @1 = @2;",
   387                          smapper.pushA(), lmapper.getA(indx));
   388                     break;
   389                 }
   390                 case opc_istore: {
   391                     final int indx = readByte(byteCodes, ++i);
   392                     emit(out, "var @1 = @2;",
   393                          lmapper.setI(indx), smapper.popI());
   394                     break;
   395                 }
   396                 case opc_lstore: {
   397                     final int indx = readByte(byteCodes, ++i);
   398                     emit(out, "var @1 = @2;",
   399                          lmapper.setL(indx), smapper.popL());
   400                     break;
   401                 }
   402                 case opc_fstore: {
   403                     final int indx = readByte(byteCodes, ++i);
   404                     emit(out, "var @1 = @2;",
   405                          lmapper.setF(indx), smapper.popF());
   406                     break;
   407                 }
   408                 case opc_dstore: {
   409                     final int indx = readByte(byteCodes, ++i);
   410                     emit(out, "var @1 = @2;",
   411                          lmapper.setD(indx), smapper.popD());
   412                     break;
   413                 }
   414                 case opc_astore: {
   415                     final int indx = readByte(byteCodes, ++i);
   416                     emit(out, "var @1 = @2;",
   417                          lmapper.setA(indx), smapper.popA());
   418                     break;
   419                 }
   420                 case opc_astore_0:
   421                     emit(out, "var @1 = @2;", lmapper.setA(0), smapper.popA());
   422                     break;
   423                 case opc_istore_0:
   424                     emit(out, "var @1 = @2;", lmapper.setI(0), smapper.popI());
   425                     break;
   426                 case opc_lstore_0:
   427                     emit(out, "var @1 = @2;", lmapper.setL(0), smapper.popL());
   428                     break;
   429                 case opc_fstore_0:
   430                     emit(out, "var @1 = @2;", lmapper.setF(0), smapper.popF());
   431                     break;
   432                 case opc_dstore_0:
   433                     emit(out, "var @1 = @2;", lmapper.setD(0), smapper.popD());
   434                     break;
   435                 case opc_astore_1:
   436                     emit(out, "var @1 = @2;", lmapper.setA(1), smapper.popA());
   437                     break;
   438                 case opc_istore_1:
   439                     emit(out, "var @1 = @2;", lmapper.setI(1), smapper.popI());
   440                     break;
   441                 case opc_lstore_1:
   442                     emit(out, "var @1 = @2;", lmapper.setL(1), smapper.popL());
   443                     break;
   444                 case opc_fstore_1:
   445                     emit(out, "var @1 = @2;", lmapper.setF(1), smapper.popF());
   446                     break;
   447                 case opc_dstore_1:
   448                     emit(out, "var @1 = @2;", lmapper.setD(1), smapper.popD());
   449                     break;
   450                 case opc_astore_2:
   451                     emit(out, "var @1 = @2;", lmapper.setA(2), smapper.popA());
   452                     break;
   453                 case opc_istore_2:
   454                     emit(out, "var @1 = @2;", lmapper.setI(2), smapper.popI());
   455                     break;
   456                 case opc_lstore_2:
   457                     emit(out, "var @1 = @2;", lmapper.setL(2), smapper.popL());
   458                     break;
   459                 case opc_fstore_2:
   460                     emit(out, "var @1 = @2;", lmapper.setF(2), smapper.popF());
   461                     break;
   462                 case opc_dstore_2:
   463                     emit(out, "var @1 = @2;", lmapper.setD(2), smapper.popD());
   464                     break;
   465                 case opc_astore_3:
   466                     emit(out, "var @1 = @2;", lmapper.setA(3), smapper.popA());
   467                     break;
   468                 case opc_istore_3:
   469                     emit(out, "var @1 = @2;", lmapper.setI(3), smapper.popI());
   470                     break;
   471                 case opc_lstore_3:
   472                     emit(out, "var @1 = @2;", lmapper.setL(3), smapper.popL());
   473                     break;
   474                 case opc_fstore_3:
   475                     emit(out, "var @1 = @2;", lmapper.setF(3), smapper.popF());
   476                     break;
   477                 case opc_dstore_3:
   478                     emit(out, "var @1 = @2;", lmapper.setD(3), smapper.popD());
   479                     break;
   480                 case opc_iadd:
   481                     emit(out, "@1 = @1.add32(@2);", smapper.getI(1), smapper.popI());
   482                     break;
   483                 case opc_ladd:
   484                     emit(out, "@1 += @2;", smapper.getL(1), smapper.popL());
   485                     break;
   486                 case opc_fadd:
   487                     emit(out, "@1 += @2;", smapper.getF(1), smapper.popF());
   488                     break;
   489                 case opc_dadd:
   490                     emit(out, "@1 += @2;", smapper.getD(1), smapper.popD());
   491                     break;
   492                 case opc_isub:
   493                     emit(out, "@1 = @1.sub32(@2);", smapper.getI(1), smapper.popI());
   494                     break;
   495                 case opc_lsub:
   496                     emit(out, "@1 -= @2;", smapper.getL(1), smapper.popL());
   497                     break;
   498                 case opc_fsub:
   499                     emit(out, "@1 -= @2;", smapper.getF(1), smapper.popF());
   500                     break;
   501                 case opc_dsub:
   502                     emit(out, "@1 -= @2;", smapper.getD(1), smapper.popD());
   503                     break;
   504                 case opc_imul:
   505                     emit(out, "@1 = @1.mul32(@2);", smapper.getI(1), smapper.popI());
   506                     break;
   507                 case opc_lmul:
   508                     emit(out, "@1 *= @2;", smapper.getL(1), smapper.popL());
   509                     break;
   510                 case opc_fmul:
   511                     emit(out, "@1 *= @2;", smapper.getF(1), smapper.popF());
   512                     break;
   513                 case opc_dmul:
   514                     emit(out, "@1 *= @2;", smapper.getD(1), smapper.popD());
   515                     break;
   516                 case opc_idiv:
   517                     emit(out, "@1 = Math.floor(@1 / @2);",
   518                          smapper.getI(1), smapper.popI());
   519                     break;
   520                 case opc_ldiv:
   521                     emit(out, "@1 = Math.floor(@1 / @2);",
   522                          smapper.getL(1), smapper.popL());
   523                     break;
   524                 case opc_fdiv:
   525                     emit(out, "@1 /= @2;", smapper.getF(1), smapper.popF());
   526                     break;
   527                 case opc_ddiv:
   528                     emit(out, "@1 /= @2;", smapper.getD(1), smapper.popD());
   529                     break;
   530                 case opc_irem:
   531                     emit(out, "@1 %= @2;", smapper.getI(1), smapper.popI());
   532                     break;
   533                 case opc_lrem:
   534                     emit(out, "@1 %= @2;", smapper.getL(1), smapper.popL());
   535                     break;
   536                 case opc_frem:
   537                     emit(out, "@1 %= @2;", smapper.getF(1), smapper.popF());
   538                     break;
   539                 case opc_drem:
   540                     emit(out, "@1 %= @2;", smapper.getD(1), smapper.popD());
   541                     break;
   542                 case opc_iand:
   543                     emit(out, "@1 &= @2;", smapper.getI(1), smapper.popI());
   544                     break;
   545                 case opc_land:
   546                     emit(out, "@1 &= @2;", smapper.getL(1), smapper.popL());
   547                     break;
   548                 case opc_ior:
   549                     emit(out, "@1 |= @2;", smapper.getI(1), smapper.popI());
   550                     break;
   551                 case opc_lor:
   552                     emit(out, "@1 |= @2;", smapper.getL(1), smapper.popL());
   553                     break;
   554                 case opc_ixor:
   555                     emit(out, "@1 ^= @2;", smapper.getI(1), smapper.popI());
   556                     break;
   557                 case opc_lxor:
   558                     emit(out, "@1 ^= @2;", smapper.getL(1), smapper.popL());
   559                     break;
   560                 case opc_ineg:
   561                     emit(out, "@1 = -@1;", smapper.getI(0));
   562                     break;
   563                 case opc_lneg:
   564                     emit(out, "@1 = -@1;", smapper.getL(0));
   565                     break;
   566                 case opc_fneg:
   567                     emit(out, "@1 = -@1;", smapper.getF(0));
   568                     break;
   569                 case opc_dneg:
   570                     emit(out, "@1 = -@1;", smapper.getD(0));
   571                     break;
   572                 case opc_ishl:
   573                     emit(out, "@1 <<= @2;", smapper.getI(1), smapper.popI());
   574                     break;
   575                 case opc_lshl:
   576                     emit(out, "@1 <<= @2;", smapper.getL(1), smapper.popI());
   577                     break;
   578                 case opc_ishr:
   579                     emit(out, "@1 >>= @2;", smapper.getI(1), smapper.popI());
   580                     break;
   581                 case opc_lshr:
   582                     emit(out, "@1 >>= @2;", smapper.getL(1), smapper.popI());
   583                     break;
   584                 case opc_iushr:
   585                     emit(out, "@1 >>>= @2;", smapper.getI(1), smapper.popI());
   586                     break;
   587                 case opc_lushr:
   588                     emit(out, "@1 >>>= @2;", smapper.getL(1), smapper.popI());
   589                     break;
   590                 case opc_iinc: {
   591                     final int varIndx = readByte(byteCodes, ++i);
   592                     final int incrBy = byteCodes[++i];
   593                     if (incrBy == 1) {
   594                         emit(out, "@1++;", lmapper.getI(varIndx));
   595                     } else {
   596                         emit(out, "@1 += @2;",
   597                              lmapper.getI(varIndx),
   598                              Integer.toString(incrBy));
   599                     }
   600                     break;
   601                 }
   602                 case opc_return:
   603                     emit(out, "return;");
   604                     break;
   605                 case opc_ireturn:
   606                     emit(out, "return @1;", smapper.popI());
   607                     break;
   608                 case opc_lreturn:
   609                     emit(out, "return @1;", smapper.popL());
   610                     break;
   611                 case opc_freturn:
   612                     emit(out, "return @1;", smapper.popF());
   613                     break;
   614                 case opc_dreturn:
   615                     emit(out, "return @1;", smapper.popD());
   616                     break;
   617                 case opc_areturn:
   618                     emit(out, "return @1;", smapper.popA());
   619                     break;
   620                 case opc_i2l:
   621                     emit(out, "var @2 = @1;", smapper.popI(), smapper.pushL());
   622                     break;
   623                 case opc_i2f:
   624                     emit(out, "var @2 = @1;", smapper.popI(), smapper.pushF());
   625                     break;
   626                 case opc_i2d:
   627                     emit(out, "var @2 = @1;", smapper.popI(), smapper.pushD());
   628                     break;
   629                 case opc_l2i:
   630                     emit(out, "var @2 = @1;", smapper.popL(), smapper.pushI());
   631                     break;
   632                     // max int check?
   633                 case opc_l2f:
   634                     emit(out, "var @2 = @1;", smapper.popL(), smapper.pushF());
   635                     break;
   636                 case opc_l2d:
   637                     emit(out, "var @2 = @1;", smapper.popL(), smapper.pushD());
   638                     break;
   639                 case opc_f2d:
   640                     emit(out, "var @2 = @1;", smapper.popF(), smapper.pushD());
   641                     break;
   642                 case opc_d2f:
   643                     emit(out, "var @2 = @1;", smapper.popD(), smapper.pushF());
   644                     break;
   645                 case opc_f2i:
   646                     emit(out, "var @2 = Math.floor(@1);",
   647                          smapper.popF(), smapper.pushI());
   648                     break;
   649                 case opc_f2l:
   650                     emit(out, "var @2 = Math.floor(@1);",
   651                          smapper.popF(), smapper.pushL());
   652                     break;
   653                 case opc_d2i:
   654                     emit(out, "var @2 = Math.floor(@1);",
   655                          smapper.popD(), smapper.pushI());
   656                     break;
   657                 case opc_d2l:
   658                     emit(out, "var @2 = Math.floor(@1);",
   659                          smapper.popD(), smapper.pushL());
   660                     break;
   661                 case opc_i2b:
   662                     emit(out, "var @1 = @1.toInt8();", smapper.getI(0));
   663                     break;
   664                 case opc_i2c:
   665                     out.append("{ /* number conversion */ }");
   666                     break;
   667                 case opc_i2s:
   668                     emit(out, "var @1 = @1.toInt16();", smapper.getI(0));
   669                     break;
   670                 case opc_aconst_null:
   671                     emit(out, "var @1 = null;", smapper.pushA());
   672                     break;
   673                 case opc_iconst_m1:
   674                     emit(out, "var @1 = -1;", smapper.pushI());
   675                     break;
   676                 case opc_iconst_0:
   677                     emit(out, "var @1 = 0;", smapper.pushI());
   678                     break;
   679                 case opc_dconst_0:
   680                     emit(out, "var @1 = 0;", smapper.pushD());
   681                     break;
   682                 case opc_lconst_0:
   683                     emit(out, "var @1 = 0;", smapper.pushL());
   684                     break;
   685                 case opc_fconst_0:
   686                     emit(out, "var @1 = 0;", smapper.pushF());
   687                     break;
   688                 case opc_iconst_1:
   689                     emit(out, "var @1 = 1;", smapper.pushI());
   690                     break;
   691                 case opc_lconst_1:
   692                     emit(out, "var @1 = 1;", smapper.pushL());
   693                     break;
   694                 case opc_fconst_1:
   695                     emit(out, "var @1 = 1;", smapper.pushF());
   696                     break;
   697                 case opc_dconst_1:
   698                     emit(out, "var @1 = 1;", smapper.pushD());
   699                     break;
   700                 case opc_iconst_2:
   701                     emit(out, "var @1 = 2;", smapper.pushI());
   702                     break;
   703                 case opc_fconst_2:
   704                     emit(out, "var @1 = 2;", smapper.pushF());
   705                     break;
   706                 case opc_iconst_3:
   707                     emit(out, "var @1 = 3;", smapper.pushI());
   708                     break;
   709                 case opc_iconst_4:
   710                     emit(out, "var @1 = 4;", smapper.pushI());
   711                     break;
   712                 case opc_iconst_5:
   713                     emit(out, "var @1 = 5;", smapper.pushI());
   714                     break;
   715                 case opc_ldc: {
   716                     int indx = readByte(byteCodes, ++i);
   717                     String v = encodeConstant(indx);
   718                     int type = VarType.fromConstantType(jc.getTag(indx));
   719                     emit(out, "var @1 = @2;", smapper.pushT(type), v);
   720                     break;
   721                 }
   722                 case opc_ldc_w:
   723                 case opc_ldc2_w: {
   724                     int indx = readIntArg(byteCodes, i);
   725                     i += 2;
   726                     String v = encodeConstant(indx);
   727                     int type = VarType.fromConstantType(jc.getTag(indx));
   728                     emit(out, "var @1 = @2;", smapper.pushT(type), v);
   729                     break;
   730                 }
   731                 case opc_lcmp:
   732                     emit(out, "var @3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
   733                          smapper.popL(), smapper.popL(), smapper.pushI());
   734                     break;
   735                 case opc_fcmpl:
   736                 case opc_fcmpg:
   737                     emit(out, "var @3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
   738                          smapper.popF(), smapper.popF(), smapper.pushI());
   739                     break;
   740                 case opc_dcmpl:
   741                 case opc_dcmpg:
   742                     emit(out, "var @3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
   743                          smapper.popD(), smapper.popD(), smapper.pushI());
   744                     break;
   745                 case opc_if_acmpeq:
   746                     i = generateIf(byteCodes, i, smapper.popA(), smapper.popA(),
   747                                    "===");
   748                     break;
   749                 case opc_if_acmpne:
   750                     i = generateIf(byteCodes, i, smapper.popA(), smapper.popA(),
   751                                    "!=");
   752                     break;
   753                 case opc_if_icmpeq:
   754                     i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
   755                                    "==");
   756                     break;
   757                 case opc_ifeq: {
   758                     int indx = i + readIntArg(byteCodes, i);
   759                     emit(out, "if (@1 == 0) { gt = @2; continue; }",
   760                          smapper.popI(), Integer.toString(indx));
   761                     i += 2;
   762                     break;
   763                 }
   764                 case opc_ifne: {
   765                     int indx = i + readIntArg(byteCodes, i);
   766                     emit(out, "if (@1 != 0) { gt = @2; continue; }",
   767                          smapper.popI(), Integer.toString(indx));
   768                     i += 2;
   769                     break;
   770                 }
   771                 case opc_iflt: {
   772                     int indx = i + readIntArg(byteCodes, i);
   773                     emit(out, "if (@1 < 0) { gt = @2; continue; }",
   774                          smapper.popI(), Integer.toString(indx));
   775                     i += 2;
   776                     break;
   777                 }
   778                 case opc_ifle: {
   779                     int indx = i + readIntArg(byteCodes, i);
   780                     emit(out, "if (@1 <= 0) { gt = @2; continue; }",
   781                          smapper.popI(), Integer.toString(indx));
   782                     i += 2;
   783                     break;
   784                 }
   785                 case opc_ifgt: {
   786                     int indx = i + readIntArg(byteCodes, i);
   787                     emit(out, "if (@1 > 0) { gt = @2; continue; }",
   788                          smapper.popI(), Integer.toString(indx));
   789                     i += 2;
   790                     break;
   791                 }
   792                 case opc_ifge: {
   793                     int indx = i + readIntArg(byteCodes, i);
   794                     emit(out, "if (@1 >= 0) { gt = @2; continue; }",
   795                          smapper.popI(), Integer.toString(indx));
   796                     i += 2;
   797                     break;
   798                 }
   799                 case opc_ifnonnull: {
   800                     int indx = i + readIntArg(byteCodes, i);
   801                     emit(out, "if (@1 !== null) { gt = @2; continue; }",
   802                          smapper.popA(), Integer.toString(indx));
   803                     i += 2;
   804                     break;
   805                 }
   806                 case opc_ifnull: {
   807                     int indx = i + readIntArg(byteCodes, i);
   808                     emit(out, "if (@1 === null) { gt = @2; continue; }",
   809                          smapper.popA(), Integer.toString(indx));
   810                     i += 2;
   811                     break;
   812                 }
   813                 case opc_if_icmpne:
   814                     i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
   815                                    "!=");
   816                     break;
   817                 case opc_if_icmplt:
   818                     i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
   819                                    "<");
   820                     break;
   821                 case opc_if_icmple:
   822                     i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
   823                                    "<=");
   824                     break;
   825                 case opc_if_icmpgt:
   826                     i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
   827                                    ">");
   828                     break;
   829                 case opc_if_icmpge:
   830                     i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
   831                                    ">=");
   832                     break;
   833                 case opc_goto: {
   834                     int indx = i + readIntArg(byteCodes, i);
   835                     emit(out, "gt = @1; continue;", Integer.toString(indx));
   836                     i += 2;
   837                     break;
   838                 }
   839                 case opc_lookupswitch: {
   840                     int table = i / 4 * 4 + 4;
   841                     int dflt = i + readInt4(byteCodes, table);
   842                     table += 4;
   843                     int n = readInt4(byteCodes, table);
   844                     table += 4;
   845                     out.append("switch (").append(smapper.popI()).append(") {\n");
   846                     while (n-- > 0) {
   847                         int cnstnt = readInt4(byteCodes, table);
   848                         table += 4;
   849                         int offset = i + readInt4(byteCodes, table);
   850                         table += 4;
   851                         out.append("  case " + cnstnt).append(": gt = " + offset).append("; continue;\n");
   852                     }
   853                     out.append("  default: gt = " + dflt).append("; continue;\n}");
   854                     i = table - 1;
   855                     break;
   856                 }
   857                 case opc_tableswitch: {
   858                     int table = i / 4 * 4 + 4;
   859                     int dflt = i + readInt4(byteCodes, table);
   860                     table += 4;
   861                     int low = readInt4(byteCodes, table);
   862                     table += 4;
   863                     int high = readInt4(byteCodes, table);
   864                     table += 4;
   865                     out.append("switch (").append(smapper.popI()).append(") {\n");
   866                     while (low <= high) {
   867                         int offset = i + readInt4(byteCodes, table);
   868                         table += 4;
   869                         out.append("  case " + low).append(": gt = " + offset).append("; continue;\n");
   870                         low++;
   871                     }
   872                     out.append("  default: gt = " + dflt).append("; continue;\n}");
   873                     i = table - 1;
   874                     break;
   875                 }
   876                 case opc_invokeinterface: {
   877                     i = invokeVirtualMethod(byteCodes, i, smapper) + 2;
   878                     break;
   879                 }
   880                 case opc_invokevirtual:
   881                     i = invokeVirtualMethod(byteCodes, i, smapper);
   882                     break;
   883                 case opc_invokespecial:
   884                     i = invokeStaticMethod(byteCodes, i, smapper, false);
   885                     break;
   886                 case opc_invokestatic:
   887                     i = invokeStaticMethod(byteCodes, i, smapper, true);
   888                     break;
   889                 case opc_new: {
   890                     int indx = readIntArg(byteCodes, i);
   891                     String ci = jc.getClassName(indx);
   892                     emit(out, "var @1 = new @2;",
   893                          smapper.pushA(), accessClass(ci.replace('/', '_')));
   894                     addReference(ci);
   895                     i += 2;
   896                     break;
   897                 }
   898                 case opc_newarray:
   899                     int atype = readByte(byteCodes, ++i);
   900                     String jvmType;
   901                     switch (atype) {
   902                         case 4: jvmType = "[Z"; break;
   903                         case 5: jvmType = "[C"; break;
   904                         case 6: jvmType = "[F"; break;
   905                         case 7: jvmType = "[D"; break;
   906                         case 8: jvmType = "[B"; break;
   907                         case 9: jvmType = "[S"; break;
   908                         case 10: jvmType = "[I"; break;
   909                         case 11: jvmType = "[J"; break;
   910                         default: throw new IllegalStateException("Array type: " + atype);
   911                     }
   912                     emit(out, "var @2 = new Array(@1).initWith('@3', 0);",
   913                          smapper.popI(), smapper.pushA(), jvmType);
   914                     break;
   915                 case opc_anewarray: {
   916                     int type = readIntArg(byteCodes, i);
   917                     i += 2;
   918                     String typeName = jc.getClassName(type);
   919                     if (typeName.startsWith("[")) {
   920                         typeName = "[" + typeName;
   921                     } else {
   922                         typeName = "[L" + typeName + ";";
   923                     }
   924                     emit(out, "var @2 = new Array(@1).initWith('@3', null);",
   925                          smapper.popI(), smapper.pushA(), typeName);
   926                     break;
   927                 }
   928                 case opc_multianewarray: {
   929                     int type = readIntArg(byteCodes, i);
   930                     i += 2;
   931                     String typeName = jc.getClassName(type);
   932                     int dim = readByte(byteCodes, ++i);
   933                     out.append("{ var a0 = new Array(").append(smapper.popI())
   934                        .append(").initWith('").append(typeName).append("', null);");
   935                     for (int d = 1; d < dim; d++) {
   936                         typeName = typeName.substring(1);
   937                         out.append("\n  var l" + d).append(" = ")
   938                            .append(smapper.popI()).append(';');
   939                         out.append("\n  for (var i" + d).append (" = 0; i" + d).
   940                             append(" < a" + (d - 1)).
   941                             append(".length; i" + d).append("++) {");
   942                         out.append("\n    var a" + d).
   943                             append (" = new Array(l" + d).append(").initWith('")
   944                             .append(typeName).append("', ")
   945                             .append(typeName.length() == 2 ? "0" : "null").append(");");
   946                         out.append("\n    a" + (d - 1)).append("[i" + d).append("] = a" + d).
   947                             append(";");
   948                     }
   949                     for (int d = 1; d < dim; d++) {
   950                         out.append("\n  }");
   951                     }
   952                     out.append("\nvar ").append(smapper.pushA())
   953                                         .append(" = a0; }");
   954                     break;
   955                 }
   956                 case opc_arraylength:
   957                     emit(out, "var @2 = @1.length;",
   958                          smapper.popA(), smapper.pushI());
   959                     break;
   960                 case opc_lastore:
   961                     emit(out, "@3.at(@2, @1);",
   962                          smapper.popL(), smapper.popI(), smapper.popA());
   963                     break;
   964                 case opc_fastore:
   965                     emit(out, "@3.at(@2, @1);",
   966                          smapper.popF(), smapper.popI(), smapper.popA());
   967                     break;
   968                 case opc_dastore:
   969                     emit(out, "@3.at(@2, @1);",
   970                          smapper.popD(), smapper.popI(), smapper.popA());
   971                     break;
   972                 case opc_aastore:
   973                     emit(out, "@3.at(@2, @1);",
   974                          smapper.popA(), smapper.popI(), smapper.popA());
   975                     break;
   976                 case opc_iastore:
   977                 case opc_bastore:
   978                 case opc_castore:
   979                 case opc_sastore:
   980                     emit(out, "@3.at(@2, @1);",
   981                          smapper.popI(), smapper.popI(), smapper.popA());
   982                     break;
   983                 case opc_laload:
   984                     emit(out, "var @3 = @2.at(@1);",
   985                          smapper.popI(), smapper.popA(), smapper.pushL());
   986                     break;
   987                 case opc_faload:
   988                     emit(out, "var @3 = @2.at(@1);",
   989                          smapper.popI(), smapper.popA(), smapper.pushF());
   990                     break;
   991                 case opc_daload:
   992                     emit(out, "var @3 = @2.at(@1);",
   993                          smapper.popI(), smapper.popA(), smapper.pushD());
   994                     break;
   995                 case opc_aaload:
   996                     emit(out, "var @3 = @2.at(@1);",
   997                          smapper.popI(), smapper.popA(), smapper.pushA());
   998                     break;
   999                 case opc_iaload:
  1000                 case opc_baload:
  1001                 case opc_caload:
  1002                 case opc_saload:
  1003                     emit(out, "var @3 = @2.at(@1);",
  1004                          smapper.popI(), smapper.popA(), smapper.pushI());
  1005                     break;
  1006                 case opc_pop:
  1007                 case opc_pop2:
  1008                     smapper.pop(1);
  1009                     debug("/* pop */");
  1010                     break;
  1011                 case opc_dup: {
  1012                     final Variable v = smapper.get(0);
  1013                     emit(out, "var @1 = @2;", smapper.pushT(v.getType()), v);
  1014                     break;
  1015                 }
  1016                 case opc_dup2: {
  1017                     if (smapper.get(0).isCategory2()) {
  1018                         final Variable v = smapper.get(0);
  1019                         emit(out, "var @1 = @2;",
  1020                              smapper.pushT(v.getType()), v);
  1021                     } else {
  1022                         final Variable v1 = smapper.get(0);
  1023                         final Variable v2 = smapper.get(1);
  1024                         emit(out, "var @1 = @2, @3 = @4;",
  1025                              smapper.pushT(v2.getType()), v2,
  1026                              smapper.pushT(v1.getType()), v1);
  1027                     }
  1028                     break;
  1029                 }
  1030                 case opc_dup_x1: {
  1031                     final Variable vi1 = smapper.pop();
  1032                     final Variable vi2 = smapper.pop();
  1033                     final Variable vo3 = smapper.pushT(vi1.getType());
  1034                     final Variable vo2 = smapper.pushT(vi2.getType());
  1035                     final Variable vo1 = smapper.pushT(vi1.getType());
  1036 
  1037                     emit(out, "var @1 = @2, @3 = @4, @5 = @6;",
  1038                          vo1, vi1, vo2, vi2, vo3, vo1);
  1039                     break;
  1040                 }
  1041                 case opc_dup_x2: {
  1042                     if (smapper.get(1).isCategory2()) {
  1043                         final Variable vi1 = smapper.pop();
  1044                         final Variable vi2 = smapper.pop();
  1045                         final Variable vo3 = smapper.pushT(vi1.getType());
  1046                         final Variable vo2 = smapper.pushT(vi2.getType());
  1047                         final Variable vo1 = smapper.pushT(vi1.getType());
  1048 
  1049                         emit(out, "var @1 = @2, @3 = @4, @5 = @6;",
  1050                              vo1, vi1, vo2, vi2, vo3, vo1);
  1051                     } else {
  1052                         final Variable vi1 = smapper.pop();
  1053                         final Variable vi2 = smapper.pop();
  1054                         final Variable vi3 = smapper.pop();
  1055                         final Variable vo4 = smapper.pushT(vi1.getType());
  1056                         final Variable vo3 = smapper.pushT(vi3.getType());
  1057                         final Variable vo2 = smapper.pushT(vi2.getType());
  1058                         final Variable vo1 = smapper.pushT(vi1.getType());
  1059 
  1060                         emit(out, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
  1061                              vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
  1062                     }
  1063                     break;
  1064                 }
  1065                 case opc_bipush:
  1066                     emit(out, "var @1 = @2;",
  1067                          smapper.pushI(), Integer.toString(byteCodes[++i]));
  1068                     break;
  1069                 case opc_sipush:
  1070                     emit(out, "var @1 = @2;",
  1071                          smapper.pushI(),
  1072                          Integer.toString(readIntArg(byteCodes, i)));
  1073                     i += 2;
  1074                     break;
  1075                 case opc_getfield: {
  1076                     int indx = readIntArg(byteCodes, i);
  1077                     String[] fi = jc.getFieldInfoName(indx);
  1078                     final int type = VarType.fromFieldType(fi[2].charAt(0));
  1079                     emit(out, "var @2 = @1.fld_@3;",
  1080                          smapper.popA(), smapper.pushT(type), fi[1]);
  1081                     i += 2;
  1082                     break;
  1083                 }
  1084                 case opc_getstatic: {
  1085                     int indx = readIntArg(byteCodes, i);
  1086                     String[] fi = jc.getFieldInfoName(indx);
  1087                     final int type = VarType.fromFieldType(fi[2].charAt(0));
  1088                     emit(out, "var @1 = @2(false).constructor.@3;",
  1089                          smapper.pushT(type),
  1090                          accessClass(fi[0].replace('/', '_')), fi[1]);
  1091                     i += 2;
  1092                     addReference(fi[0]);
  1093                     break;
  1094                 }
  1095                 case opc_putfield: {
  1096                     int indx = readIntArg(byteCodes, i);
  1097                     String[] fi = jc.getFieldInfoName(indx);
  1098                     final int type = VarType.fromFieldType(fi[2].charAt(0));
  1099                     emit(out, "@2.fld_@3 = @1;",
  1100                          smapper.popT(type), smapper.popA(), fi[1]);
  1101                     i += 2;
  1102                     break;
  1103                 }
  1104                 case opc_putstatic: {
  1105                     int indx = readIntArg(byteCodes, i);
  1106                     String[] fi = jc.getFieldInfoName(indx);
  1107                     final int type = VarType.fromFieldType(fi[2].charAt(0));
  1108                     emit(out, "@1(false).constructor.@2 = @3;",
  1109                          accessClass(fi[0].replace('/', '_')), fi[1],
  1110                          smapper.popT(type));
  1111                     i += 2;
  1112                     addReference(fi[0]);
  1113                     break;
  1114                 }
  1115                 case opc_checkcast: {
  1116                     int indx = readIntArg(byteCodes, i);
  1117                     final String type = jc.getClassName(indx);
  1118                     if (!type.startsWith("[")) {
  1119                         // no way to check arrays right now
  1120                         // XXX proper exception
  1121                         emit(out,
  1122                              "if (@1 !== null && !@1.$instOf_@2) throw {};",
  1123                              smapper.getA(0), type.replace('/', '_'));
  1124                     }
  1125                     i += 2;
  1126                     break;
  1127                 }
  1128                 case opc_instanceof: {
  1129                     int indx = readIntArg(byteCodes, i);
  1130                     final String type = jc.getClassName(indx);
  1131                     emit(out, "var @2 = @1.$instOf_@3 ? 1 : 0;",
  1132                          smapper.popA(), smapper.pushI(),
  1133                          type.replace('/', '_'));
  1134                     i += 2;
  1135                     break;
  1136                 }
  1137                 case opc_athrow: {
  1138                     final Variable v = smapper.popA();
  1139                     smapper.clear();
  1140 
  1141                     emit(out, "{ var @1 = @2; throw @2; }",
  1142                          smapper.pushA(), v);
  1143                     break;
  1144                 }
  1145 
  1146                 case opc_monitorenter: {
  1147                     out.append("/* monitor enter */");
  1148                     smapper.popA();
  1149                     break;
  1150                 }
  1151 
  1152                 case opc_monitorexit: {
  1153                     out.append("/* monitor exit */");
  1154                     smapper.popA();
  1155                     break;
  1156                 }
  1157 
  1158                 default: {
  1159                     emit(out, "throw 'unknown bytecode @1';",
  1160                          Integer.toString(c));
  1161                 }
  1162             }
  1163             if (debug(" //")) {
  1164                 for (int j = prev; j <= i; j++) {
  1165                     out.append(" ");
  1166                     final int cc = readByte(byteCodes, j);
  1167                     out.append(Integer.toString(cc));
  1168                 }
  1169             }
  1170             out.append("\n");            
  1171         }
  1172         if (previousTrap != null) {
  1173             generateCatch(previousTrap);
  1174         }
  1175         out.append("  }\n");
  1176         out.append("};");
  1177     }
  1178 
  1179     private int generateIf(byte[] byteCodes, int i,
  1180                            final Variable v2, final Variable v1,
  1181                            final String test) throws IOException {
  1182         int indx = i + readIntArg(byteCodes, i);
  1183         out.append("if (").append(v1)
  1184            .append(' ').append(test).append(' ')
  1185            .append(v2).append(") { gt = " + indx)
  1186            .append("; continue; }");
  1187         return i + 2;
  1188     }
  1189 
  1190     private int readIntArg(byte[] byteCodes, int offsetInstruction) {
  1191         final int indxHi = byteCodes[offsetInstruction + 1] << 8;
  1192         final int indxLo = byteCodes[offsetInstruction + 2];
  1193         return (indxHi & 0xffffff00) | (indxLo & 0xff);
  1194     }
  1195     private int readInt4(byte[] byteCodes, int offsetInstruction) {
  1196         final int d = byteCodes[offsetInstruction + 0] << 24;
  1197         final int c = byteCodes[offsetInstruction + 1] << 16;
  1198         final int b = byteCodes[offsetInstruction + 2] << 8;
  1199         final int a = byteCodes[offsetInstruction + 3];
  1200         return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
  1201     }
  1202     private int readByte(byte[] byteCodes, int offsetInstruction) {
  1203         return byteCodes[offsetInstruction] & 0xff;
  1204     }
  1205     
  1206     private static void countArgs(String descriptor, char[] returnType, StringBuilder sig, StringBuilder cnt) {
  1207         int i = 0;
  1208         Boolean count = null;
  1209         boolean array = false;
  1210         sig.append("__");
  1211         int firstPos = sig.length();
  1212         while (i < descriptor.length()) {
  1213             char ch = descriptor.charAt(i++);
  1214             switch (ch) {
  1215                 case '(':
  1216                     count = true;
  1217                     continue;
  1218                 case ')':
  1219                     count = false;
  1220                     continue;
  1221                 case 'B': 
  1222                 case 'C': 
  1223                 case 'D': 
  1224                 case 'F': 
  1225                 case 'I': 
  1226                 case 'J': 
  1227                 case 'S': 
  1228                 case 'Z': 
  1229                     if (count) {
  1230                         if (array) {
  1231                             sig.append("_3");
  1232                         }
  1233                         sig.append(ch);
  1234                         if (ch == 'J' || ch == 'D') {
  1235                             cnt.append('1');
  1236                         } else {
  1237                             cnt.append('0');
  1238                         }
  1239                     } else {
  1240                         sig.insert(firstPos, ch);
  1241                         if (array) {
  1242                             returnType[0] = '[';
  1243                             sig.insert(firstPos, "_3");
  1244                         } else {
  1245                             returnType[0] = ch;
  1246                         }
  1247                     }
  1248                     array = false;
  1249                     continue;
  1250                 case 'V': 
  1251                     assert !count;
  1252                     returnType[0] = 'V';
  1253                     sig.insert(firstPos, 'V');
  1254                     continue;
  1255                 case 'L':
  1256                     int next = descriptor.indexOf(';', i);
  1257                     String realSig = mangleSig(descriptor, i - 1, next + 1);
  1258                     if (count) {
  1259                         if (array) {
  1260                             sig.append("_3");
  1261                         }
  1262                         sig.append(realSig);
  1263                         cnt.append('0');
  1264                     } else {
  1265                         sig.insert(firstPos, realSig);
  1266                         if (array) {
  1267                             sig.insert(firstPos, "_3");
  1268                         }
  1269                         returnType[0] = 'L';
  1270                     }
  1271                     i = next + 1;
  1272                     array = false;
  1273                     continue;
  1274                 case '[':
  1275                     array = true;
  1276                     continue;
  1277                 default:
  1278                     throw new IllegalStateException("Invalid char: " + ch);
  1279             }
  1280         }
  1281     }
  1282     
  1283     private static String mangleSig(String txt, int first, int last) {
  1284         StringBuilder sb = new StringBuilder();
  1285         for (int i = first; i < last; i++) {
  1286             final char ch = txt.charAt(i);
  1287             switch (ch) {
  1288                 case '/': sb.append('_'); break;
  1289                 case '_': sb.append("_1"); break;
  1290                 case ';': sb.append("_2"); break;
  1291                 case '[': sb.append("_3"); break;
  1292                 default: sb.append(ch); break;
  1293             }
  1294         }
  1295         return sb.toString();
  1296     }
  1297 
  1298     private static String findMethodName(MethodData m, StringBuilder cnt) {
  1299         StringBuilder name = new StringBuilder();
  1300         if ("<init>".equals(m.getName())) { // NOI18N
  1301             name.append("cons"); // NOI18N
  1302         } else if ("<clinit>".equals(m.getName())) { // NOI18N
  1303             name.append("class"); // NOI18N
  1304         } else {
  1305             name.append(m.getName());
  1306         } 
  1307         
  1308         countArgs(m.getInternalSig(), new char[1], name, cnt);
  1309         return name.toString();
  1310     }
  1311 
  1312     static String findMethodName(String[] mi, StringBuilder cnt, char[] returnType) {
  1313         StringBuilder name = new StringBuilder();
  1314         String descr = mi[2];//mi.getDescriptor();
  1315         String nm= mi[1];
  1316         if ("<init>".equals(nm)) { // NOI18N
  1317             name.append("cons"); // NOI18N
  1318         } else {
  1319             name.append(nm);
  1320         }
  1321         countArgs(descr, returnType, name, cnt);
  1322         return name.toString();
  1323     }
  1324 
  1325     private int invokeStaticMethod(byte[] byteCodes, int i, final StackMapper mapper, boolean isStatic)
  1326     throws IOException {
  1327         int methodIndex = readIntArg(byteCodes, i);
  1328         String[] mi = jc.getFieldInfoName(methodIndex);
  1329         char[] returnType = { 'V' };
  1330         StringBuilder cnt = new StringBuilder();
  1331         String mn = findMethodName(mi, cnt, returnType);
  1332 
  1333         final int numArguments = isStatic ? cnt.length() : cnt.length() + 1;
  1334         final Variable[] vars = new Variable[numArguments];
  1335 
  1336         for (int j = numArguments - 1; j >= 0; --j) {
  1337             vars[j] = mapper.pop();
  1338         }
  1339 
  1340         if (returnType[0] != 'V') {
  1341             out.append("var ")
  1342                .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
  1343                .append(" = ");
  1344         }
  1345 
  1346         final String in = mi[0];
  1347         out.append(accessClass(in.replace('/', '_')));
  1348         out.append("(false).");
  1349         if (mn.startsWith("cons_")) {
  1350             out.append("constructor.");
  1351         }
  1352         out.append(mn);
  1353         if (isStatic) {
  1354             out.append('(');
  1355         } else {
  1356             out.append(".call(");
  1357         }
  1358         if (numArguments > 0) {
  1359             out.append(vars[0]);
  1360             for (int j = 1; j < numArguments; ++j) {
  1361                 out.append(", ");
  1362                 out.append(vars[j]);
  1363             }
  1364         }
  1365         out.append(");");
  1366         i += 2;
  1367         addReference(in);
  1368         return i;
  1369     }
  1370     private int invokeVirtualMethod(byte[] byteCodes, int i, final StackMapper mapper)
  1371     throws IOException {
  1372         int methodIndex = readIntArg(byteCodes, i);
  1373         String[] mi = jc.getFieldInfoName(methodIndex);
  1374         char[] returnType = { 'V' };
  1375         StringBuilder cnt = new StringBuilder();
  1376         String mn = findMethodName(mi, cnt, returnType);
  1377 
  1378         final int numArguments = cnt.length() + 1;
  1379         final Variable[] vars = new Variable[numArguments];
  1380 
  1381         for (int j = numArguments - 1; j >= 0; --j) {
  1382             vars[j] = mapper.pop();
  1383         }
  1384 
  1385         if (returnType[0] != 'V') {
  1386             out.append("var ")
  1387                .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
  1388                .append(" = ");
  1389         }
  1390 
  1391         out.append(vars[0]).append('.');
  1392         out.append(mn);
  1393         out.append('(');
  1394         String sep = "";
  1395         for (int j = 1; j < numArguments; ++j) {
  1396             out.append(sep);
  1397             out.append(vars[j]);
  1398             sep = ", ";
  1399         }
  1400         out.append(");");
  1401         i += 2;
  1402         return i;
  1403     }
  1404 
  1405     private void addReference(String cn) throws IOException {
  1406         if (requireReference(cn)) {
  1407             debug(" /* needs " + cn + " */");
  1408         }
  1409     }
  1410 
  1411     private void outType(String d, StringBuilder out) {
  1412         int arr = 0;
  1413         while (d.charAt(0) == '[') {
  1414             out.append('A');
  1415             d = d.substring(1);
  1416         }
  1417         if (d.charAt(0) == 'L') {
  1418             assert d.charAt(d.length() - 1) == ';';
  1419             out.append(d.replace('/', '_').substring(0, d.length() - 1));
  1420         } else {
  1421             out.append(d);
  1422         }
  1423     }
  1424 
  1425     private String encodeConstant(int entryIndex) throws IOException {
  1426         String[] classRef = { null };
  1427         String s = jc.stringValue(entryIndex, classRef);
  1428         if (classRef[0] != null) {
  1429             addReference(classRef[0]);
  1430             s = accessClass(s.replace('/', '_')) + "(false).constructor.$class";
  1431         }
  1432         return s;
  1433     }
  1434 
  1435     private String javaScriptBody(String prefix, MethodData m, boolean isStatic) throws IOException {
  1436         byte[] arr = m.findAnnotationData(true);
  1437         if (arr == null) {
  1438             return null;
  1439         }
  1440         final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
  1441         class P extends AnnotationParser {
  1442             public P() {
  1443                 super(false);
  1444             }
  1445             
  1446             int cnt;
  1447             String[] args = new String[30];
  1448             String body;
  1449             
  1450             @Override
  1451             protected void visitAttr(String type, String attr, String at, String value) {
  1452                 if (type.equals(jvmType)) {
  1453                     if ("body".equals(attr)) {
  1454                         body = value;
  1455                     } else if ("args".equals(attr)) {
  1456                         args[cnt++] = value;
  1457                     } else {
  1458                         throw new IllegalArgumentException(attr);
  1459                     }
  1460                 }
  1461             }
  1462         }
  1463         P p = new P();
  1464         p.parse(arr, jc);
  1465         if (p.body == null) {
  1466             return null;
  1467         }
  1468         StringBuilder cnt = new StringBuilder();
  1469         final String mn = findMethodName(m, cnt);
  1470         out.append(prefix).append(mn);
  1471         out.append(" = function(");
  1472         String space = "";
  1473         int index = 0;
  1474         for (int i = 0; i < cnt.length(); i++) {
  1475             out.append(space);
  1476             space = outputArg(out, p.args, index);
  1477             index++;
  1478         }
  1479         out.append(") {").append("\n");
  1480         out.append(p.body);
  1481         out.append("\n}\n");
  1482         return mn;
  1483     }
  1484     private static String className(ClassData jc) {
  1485         //return jc.getName().getInternalName().replace('/', '_');
  1486         return jc.getClassName().replace('/', '_');
  1487     }
  1488     
  1489     private static String[] findAnnotation(
  1490         byte[] arr, ClassData cd, final String className, 
  1491         final String... attrNames
  1492     ) throws IOException {
  1493         if (arr == null) {
  1494             return null;
  1495         }
  1496         final String[] values = new String[attrNames.length];
  1497         final boolean[] found = { false };
  1498         final String jvmType = "L" + className.replace('.', '/') + ";";
  1499         AnnotationParser ap = new AnnotationParser(false) {
  1500             @Override
  1501             protected void visitAttr(String type, String attr, String at, String value) {
  1502                 if (type.equals(jvmType)) {
  1503                     found[0] = true;
  1504                     for (int i = 0; i < attrNames.length; i++) {
  1505                         if (attrNames[i].equals(attr)) {
  1506                             values[i] = value;
  1507                         }
  1508                     }
  1509                 }
  1510             }
  1511             
  1512         };
  1513         ap.parse(arr, cd);
  1514         return found[0] ? values : null;
  1515     }
  1516 
  1517     private CharSequence initField(FieldData v) {
  1518         final String is = v.getInternalSig();
  1519         if (is.length() == 1) {
  1520             switch (is.charAt(0)) {
  1521                 case 'S':
  1522                 case 'J':
  1523                 case 'B':
  1524                 case 'Z':
  1525                 case 'C':
  1526                 case 'I': return " = 0;";
  1527                 case 'F': 
  1528                 case 'D': return " = 0.0;";
  1529                 default:
  1530                     throw new IllegalStateException(is);
  1531             }
  1532         }
  1533         return " = null;";
  1534     }
  1535 
  1536     private static void generateAnno(ClassData cd, final Appendable out, byte[] data) throws IOException {
  1537         AnnotationParser ap = new AnnotationParser(true) {
  1538             int anno;
  1539             int cnt;
  1540             
  1541             @Override
  1542             protected void visitAnnotationStart(String type) throws IOException {
  1543                 if (anno++ > 0) {
  1544                     out.append(",");
  1545                 }
  1546                 out.append('"').append(type).append("\" : {\n");
  1547                 cnt = 0;
  1548             }
  1549 
  1550             @Override
  1551             protected void visitAnnotationEnd(String type) throws IOException {
  1552                 out.append("\n}\n");
  1553             }
  1554             
  1555             @Override
  1556             protected void visitAttr(String type, String attr, String attrType, String value) 
  1557             throws IOException {
  1558                 if (attr == null) {
  1559                     return;
  1560                 }
  1561                 if (cnt++ > 0) {
  1562                     out.append(",\n");
  1563                 }
  1564                 out.append(attr).append("__").append(attrType).append(" : ").append(value);
  1565             }
  1566         };
  1567         ap.parse(data, cd);
  1568     }
  1569 
  1570     private static String outputArg(Appendable out, String[] args, int indx) throws IOException {
  1571         final String name = args[indx];
  1572         if (name == null) {
  1573             return "";
  1574         }
  1575         if (name.contains(",")) {
  1576             throw new IOException("Wrong parameter with ',': " + name);
  1577         }
  1578         out.append(name);
  1579         return ",";
  1580     }
  1581 
  1582     private static void emit(final Appendable out,
  1583                              final String format,
  1584                              final CharSequence... params) throws IOException {
  1585         final int length = format.length();
  1586 
  1587         int processed = 0;
  1588         int paramOffset = format.indexOf('@');
  1589         while ((paramOffset != -1) && (paramOffset < (length - 1))) {
  1590             final char paramChar = format.charAt(paramOffset + 1);
  1591             if ((paramChar >= '1') && (paramChar <= '9')) {
  1592                 final int paramIndex = paramChar - '0' - 1;
  1593 
  1594                 out.append(format, processed, paramOffset);
  1595                 out.append(params[paramIndex]);
  1596 
  1597                 ++paramOffset;
  1598                 processed = paramOffset + 1;
  1599             }
  1600 
  1601             paramOffset = format.indexOf('@', paramOffset + 1);
  1602         }
  1603 
  1604         out.append(format, processed, length);
  1605     }
  1606 
  1607     private void generateCatch(TrapData[] traps) throws IOException {
  1608         out.append("} catch (e) {\n");
  1609         int finallyPC = -1;
  1610         for (TrapData e : traps) {
  1611             if (e == null) {
  1612                 break;
  1613             }
  1614             if (e.catch_cpx != 0) { //not finally
  1615                 final String classInternalName = jc.getClassName(e.catch_cpx);
  1616                 addReference(classInternalName);
  1617                 if ("java/lang/Throwable".equals(classInternalName)) {
  1618                     out.append("if (e.$instOf_java_lang_Throwable) {");
  1619                     out.append("  var stA0 = e;");
  1620                     out.append("} else {");
  1621                     out.append("  var stA0 = vm.java_lang_Throwable(true);");
  1622                     out.append("  vm.java_lang_Throwable.cons__VLjava_lang_String_2.call(stA0, e.toString());");
  1623                     out.append("}");
  1624                     out.append("gt=" + e.handler_pc + "; continue;");
  1625                 } else {
  1626                     out.append("if (e.$instOf_" + classInternalName.replace('/', '_') + ") {");
  1627                     out.append("gt=" + e.handler_pc + "; var stA0 = e; continue;");
  1628                     out.append("}\n");
  1629                 }
  1630             } else {
  1631                 finallyPC = e.handler_pc;
  1632             }
  1633         }
  1634         if (finallyPC == -1) {
  1635             out.append("throw e;");
  1636         } else {
  1637             out.append("gt=" + finallyPC + "; var stA0 = e; continue;");
  1638         }
  1639         out.append("\n}");
  1640     }
  1641 }