vm/src/main/java/org/apidesign/vm4brwsr/ByteCodeToJavaScript.java
author Martin Soch <Martin.Soch@oracle.com>
Fri, 25 Jan 2013 11:00:52 +0100
brancharithmetic
changeset 582 8e546d108658
parent 503 80a388c8c27b
child 593 b42911b78a16
permissions -rw-r--r--
Long arithmetic prototype, Long currently represented by separate JavaScript object with two JS-Numbers.
Just few operation implemented to pass tests. Tests under vmtest directory are still failing.
     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) throws IOException;
    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 = MakeLong(@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 = MakeLong(@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 = MakeLong(@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 = MakeLong(@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 = @1.add64(@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 = @1.div64(@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 = @1.shl64(@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 = new Long(@1, 0);", 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.toInt32();", smapper.popL(), smapper.pushI());
   631                     break;
   632                     // max int check?
   633                 case opc_l2f:
   634                     emit(out, "var @2 = @1.toFP();", smapper.popL(), smapper.pushF());
   635                     break;
   636                 case opc_l2d:
   637                     emit(out, "var @2 = @1.toFP();", 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 = LongFromNumber(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 = LongFromNumber(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 = new Long(0,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 = new Long(1,0);", 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                     if (type == VarType.LONG) {
   729                         final Long lv = new Long(v);
   730                         final int low = (int)(lv.longValue() & 0xFFFFFFFF);
   731                         final int hi = (int)(lv.longValue() >> 32);
   732                         emit(out, "var @1 = new Long(0x@2, 0x@3);", smapper.pushL(), 
   733                                 Integer.toHexString(low), Integer.toHexString(hi));
   734                     } else {
   735                         emit(out, "var @1 = @2;", smapper.pushT(type), v);
   736                     }
   737                     break;
   738                 }
   739                 case opc_lcmp:
   740                     emit(out, "var @3 = @2.compare64(@1);",
   741                          smapper.popL(), smapper.popL(), smapper.pushI());
   742                     break;
   743                 case opc_fcmpl:
   744                 case opc_fcmpg:
   745                     emit(out, "var @3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
   746                          smapper.popF(), smapper.popF(), smapper.pushI());
   747                     break;
   748                 case opc_dcmpl:
   749                 case opc_dcmpg:
   750                     emit(out, "var @3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
   751                          smapper.popD(), smapper.popD(), smapper.pushI());
   752                     break;
   753                 case opc_if_acmpeq:
   754                     i = generateIf(byteCodes, i, smapper.popA(), smapper.popA(),
   755                                    "===");
   756                     break;
   757                 case opc_if_acmpne:
   758                     i = generateIf(byteCodes, i, smapper.popA(), smapper.popA(),
   759                                    "!=");
   760                     break;
   761                 case opc_if_icmpeq:
   762                     i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
   763                                    "==");
   764                     break;
   765                 case opc_ifeq: {
   766                     int indx = i + readIntArg(byteCodes, i);
   767                     emit(out, "if (@1 == 0) { gt = @2; continue; }",
   768                          smapper.popI(), Integer.toString(indx));
   769                     i += 2;
   770                     break;
   771                 }
   772                 case opc_ifne: {
   773                     int indx = i + readIntArg(byteCodes, i);
   774                     emit(out, "if (@1 != 0) { gt = @2; continue; }",
   775                          smapper.popI(), Integer.toString(indx));
   776                     i += 2;
   777                     break;
   778                 }
   779                 case opc_iflt: {
   780                     int indx = i + readIntArg(byteCodes, i);
   781                     emit(out, "if (@1 < 0) { gt = @2; continue; }",
   782                          smapper.popI(), Integer.toString(indx));
   783                     i += 2;
   784                     break;
   785                 }
   786                 case opc_ifle: {
   787                     int indx = i + readIntArg(byteCodes, i);
   788                     emit(out, "if (@1 <= 0) { gt = @2; continue; }",
   789                          smapper.popI(), Integer.toString(indx));
   790                     i += 2;
   791                     break;
   792                 }
   793                 case opc_ifgt: {
   794                     int indx = i + readIntArg(byteCodes, i);
   795                     emit(out, "if (@1 > 0) { gt = @2; continue; }",
   796                          smapper.popI(), Integer.toString(indx));
   797                     i += 2;
   798                     break;
   799                 }
   800                 case opc_ifge: {
   801                     int indx = i + readIntArg(byteCodes, i);
   802                     emit(out, "if (@1 >= 0) { gt = @2; continue; }",
   803                          smapper.popI(), Integer.toString(indx));
   804                     i += 2;
   805                     break;
   806                 }
   807                 case opc_ifnonnull: {
   808                     int indx = i + readIntArg(byteCodes, i);
   809                     emit(out, "if (@1 !== null) { gt = @2; continue; }",
   810                          smapper.popA(), Integer.toString(indx));
   811                     i += 2;
   812                     break;
   813                 }
   814                 case opc_ifnull: {
   815                     int indx = i + readIntArg(byteCodes, i);
   816                     emit(out, "if (@1 === null) { gt = @2; continue; }",
   817                          smapper.popA(), Integer.toString(indx));
   818                     i += 2;
   819                     break;
   820                 }
   821                 case opc_if_icmpne:
   822                     i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
   823                                    "!=");
   824                     break;
   825                 case opc_if_icmplt:
   826                     i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
   827                                    "<");
   828                     break;
   829                 case opc_if_icmple:
   830                     i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
   831                                    "<=");
   832                     break;
   833                 case opc_if_icmpgt:
   834                     i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
   835                                    ">");
   836                     break;
   837                 case opc_if_icmpge:
   838                     i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
   839                                    ">=");
   840                     break;
   841                 case opc_goto: {
   842                     int indx = i + readIntArg(byteCodes, i);
   843                     emit(out, "gt = @1; continue;", Integer.toString(indx));
   844                     i += 2;
   845                     break;
   846                 }
   847                 case opc_lookupswitch: {
   848                     int table = i / 4 * 4 + 4;
   849                     int dflt = i + readInt4(byteCodes, table);
   850                     table += 4;
   851                     int n = readInt4(byteCodes, table);
   852                     table += 4;
   853                     out.append("switch (").append(smapper.popI()).append(") {\n");
   854                     while (n-- > 0) {
   855                         int cnstnt = readInt4(byteCodes, table);
   856                         table += 4;
   857                         int offset = i + readInt4(byteCodes, table);
   858                         table += 4;
   859                         out.append("  case " + cnstnt).append(": gt = " + offset).append("; continue;\n");
   860                     }
   861                     out.append("  default: gt = " + dflt).append("; continue;\n}");
   862                     i = table - 1;
   863                     break;
   864                 }
   865                 case opc_tableswitch: {
   866                     int table = i / 4 * 4 + 4;
   867                     int dflt = i + readInt4(byteCodes, table);
   868                     table += 4;
   869                     int low = readInt4(byteCodes, table);
   870                     table += 4;
   871                     int high = readInt4(byteCodes, table);
   872                     table += 4;
   873                     out.append("switch (").append(smapper.popI()).append(") {\n");
   874                     while (low <= high) {
   875                         int offset = i + readInt4(byteCodes, table);
   876                         table += 4;
   877                         out.append("  case " + low).append(": gt = " + offset).append("; continue;\n");
   878                         low++;
   879                     }
   880                     out.append("  default: gt = " + dflt).append("; continue;\n}");
   881                     i = table - 1;
   882                     break;
   883                 }
   884                 case opc_invokeinterface: {
   885                     i = invokeVirtualMethod(byteCodes, i, smapper) + 2;
   886                     break;
   887                 }
   888                 case opc_invokevirtual:
   889                     i = invokeVirtualMethod(byteCodes, i, smapper);
   890                     break;
   891                 case opc_invokespecial:
   892                     i = invokeStaticMethod(byteCodes, i, smapper, false);
   893                     break;
   894                 case opc_invokestatic:
   895                     i = invokeStaticMethod(byteCodes, i, smapper, true);
   896                     break;
   897                 case opc_new: {
   898                     int indx = readIntArg(byteCodes, i);
   899                     String ci = jc.getClassName(indx);
   900                     emit(out, "var @1 = new @2;",
   901                          smapper.pushA(), accessClass(ci.replace('/', '_')));
   902                     addReference(ci);
   903                     i += 2;
   904                     break;
   905                 }
   906                 case opc_newarray:
   907                     int atype = readByte(byteCodes, ++i);
   908                     String jvmType;
   909                     switch (atype) {
   910                         case 4: jvmType = "[Z"; break;
   911                         case 5: jvmType = "[C"; break;
   912                         case 6: jvmType = "[F"; break;
   913                         case 7: jvmType = "[D"; break;
   914                         case 8: jvmType = "[B"; break;
   915                         case 9: jvmType = "[S"; break;
   916                         case 10: jvmType = "[I"; break;
   917                         case 11: jvmType = "[J"; break;
   918                         default: throw new IllegalStateException("Array type: " + atype);
   919                     }
   920                     emit(out, "var @2 = Array.prototype.newArray__Ljava_lang_Object_2ZLjava_lang_String_2I(true, '@3', @1);",
   921                          smapper.popI(), smapper.pushA(), jvmType);
   922                     break;
   923                 case opc_anewarray: {
   924                     int type = readIntArg(byteCodes, i);
   925                     i += 2;
   926                     String typeName = jc.getClassName(type);
   927                     if (typeName.startsWith("[")) {
   928                         typeName = "[" + typeName;
   929                     } else {
   930                         typeName = "[L" + typeName + ";";
   931                     }
   932                     emit(out, "var @2 = Array.prototype.newArray__Ljava_lang_Object_2ZLjava_lang_String_2I(false, '@3', @1);",
   933                          smapper.popI(), smapper.pushA(), typeName);
   934                     break;
   935                 }
   936                 case opc_multianewarray: {
   937                     int type = readIntArg(byteCodes, i);
   938                     i += 2;
   939                     String typeName = jc.getClassName(type);
   940                     int dim = readByte(byteCodes, ++i);
   941                     StringBuilder dims = new StringBuilder();
   942                     dims.append('[');
   943                     for (int d = 0; d < dim; d++) {
   944                         if (d != 0) {
   945                             dims.append(",");
   946                         }
   947                         dims.append(smapper.popI());
   948                     }
   949                     dims.append(']');
   950                     emit(out, "var @2 = Array.prototype.multiNewArray__Ljava_lang_Object_2Ljava_lang_String_2_3II('@3', @1, 0);",
   951                          dims.toString(), smapper.pushA(), typeName);
   952                     break;
   953                 }
   954                 case opc_arraylength:
   955                     emit(out, "var @2 = @1.length;",
   956                          smapper.popA(), smapper.pushI());
   957                     break;
   958                 case opc_lastore:
   959                     emit(out, "@3.at(@2, @1);",
   960                          smapper.popL(), smapper.popI(), smapper.popA());
   961                     break;
   962                 case opc_fastore:
   963                     emit(out, "@3.at(@2, @1);",
   964                          smapper.popF(), smapper.popI(), smapper.popA());
   965                     break;
   966                 case opc_dastore:
   967                     emit(out, "@3.at(@2, @1);",
   968                          smapper.popD(), smapper.popI(), smapper.popA());
   969                     break;
   970                 case opc_aastore:
   971                     emit(out, "@3.at(@2, @1);",
   972                          smapper.popA(), smapper.popI(), smapper.popA());
   973                     break;
   974                 case opc_iastore:
   975                 case opc_bastore:
   976                 case opc_castore:
   977                 case opc_sastore:
   978                     emit(out, "@3.at(@2, @1);",
   979                          smapper.popI(), smapper.popI(), smapper.popA());
   980                     break;
   981                 case opc_laload:
   982                     emit(out, "var @3 = @2.at(@1);",
   983                          smapper.popI(), smapper.popA(), smapper.pushL());
   984                     break;
   985                 case opc_faload:
   986                     emit(out, "var @3 = @2.at(@1);",
   987                          smapper.popI(), smapper.popA(), smapper.pushF());
   988                     break;
   989                 case opc_daload:
   990                     emit(out, "var @3 = @2.at(@1);",
   991                          smapper.popI(), smapper.popA(), smapper.pushD());
   992                     break;
   993                 case opc_aaload:
   994                     emit(out, "var @3 = @2.at(@1);",
   995                          smapper.popI(), smapper.popA(), smapper.pushA());
   996                     break;
   997                 case opc_iaload:
   998                 case opc_baload:
   999                 case opc_caload:
  1000                 case opc_saload:
  1001                     emit(out, "var @3 = @2.at(@1);",
  1002                          smapper.popI(), smapper.popA(), smapper.pushI());
  1003                     break;
  1004                 case opc_pop:
  1005                 case opc_pop2:
  1006                     smapper.pop(1);
  1007                     debug("/* pop */");
  1008                     break;
  1009                 case opc_dup: {
  1010                     final Variable v = smapper.get(0);
  1011                     emit(out, "var @1 = @2;", smapper.pushT(v.getType()), v);
  1012                     break;
  1013                 }
  1014                 case opc_dup2: {
  1015                     if (smapper.get(0).isCategory2()) {
  1016                         final Variable v = smapper.get(0);
  1017                         emit(out, "var @1 = @2;",
  1018                              smapper.pushT(v.getType()), v);
  1019                     } else {
  1020                         final Variable v1 = smapper.get(0);
  1021                         final Variable v2 = smapper.get(1);
  1022                         emit(out, "var @1 = @2, @3 = @4;",
  1023                              smapper.pushT(v2.getType()), v2,
  1024                              smapper.pushT(v1.getType()), v1);
  1025                     }
  1026                     break;
  1027                 }
  1028                 case opc_dup_x1: {
  1029                     final Variable vi1 = smapper.pop();
  1030                     final Variable vi2 = smapper.pop();
  1031                     final Variable vo3 = smapper.pushT(vi1.getType());
  1032                     final Variable vo2 = smapper.pushT(vi2.getType());
  1033                     final Variable vo1 = smapper.pushT(vi1.getType());
  1034 
  1035                     emit(out, "var @1 = @2, @3 = @4, @5 = @6;",
  1036                          vo1, vi1, vo2, vi2, vo3, vo1);
  1037                     break;
  1038                 }
  1039                 case opc_dup_x2: {
  1040                     if (smapper.get(1).isCategory2()) {
  1041                         final Variable vi1 = smapper.pop();
  1042                         final Variable vi2 = smapper.pop();
  1043                         final Variable vo3 = smapper.pushT(vi1.getType());
  1044                         final Variable vo2 = smapper.pushT(vi2.getType());
  1045                         final Variable vo1 = smapper.pushT(vi1.getType());
  1046 
  1047                         emit(out, "var @1 = @2, @3 = @4, @5 = @6;",
  1048                              vo1, vi1, vo2, vi2, vo3, vo1);
  1049                     } else {
  1050                         final Variable vi1 = smapper.pop();
  1051                         final Variable vi2 = smapper.pop();
  1052                         final Variable vi3 = smapper.pop();
  1053                         final Variable vo4 = smapper.pushT(vi1.getType());
  1054                         final Variable vo3 = smapper.pushT(vi3.getType());
  1055                         final Variable vo2 = smapper.pushT(vi2.getType());
  1056                         final Variable vo1 = smapper.pushT(vi1.getType());
  1057 
  1058                         emit(out, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
  1059                              vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
  1060                     }
  1061                     break;
  1062                 }
  1063                 case opc_bipush:
  1064                     emit(out, "var @1 = @2;",
  1065                          smapper.pushI(), Integer.toString(byteCodes[++i]));
  1066                     break;
  1067                 case opc_sipush:
  1068                     emit(out, "var @1 = @2;",
  1069                          smapper.pushI(),
  1070                          Integer.toString(readIntArg(byteCodes, i)));
  1071                     i += 2;
  1072                     break;
  1073                 case opc_getfield: {
  1074                     int indx = readIntArg(byteCodes, i);
  1075                     String[] fi = jc.getFieldInfoName(indx);
  1076                     final int type = VarType.fromFieldType(fi[2].charAt(0));
  1077                     emit(out, "var @2 = @1.fld_@3;",
  1078                          smapper.popA(), smapper.pushT(type), fi[1]);
  1079                     i += 2;
  1080                     break;
  1081                 }
  1082                 case opc_getstatic: {
  1083                     int indx = readIntArg(byteCodes, i);
  1084                     String[] fi = jc.getFieldInfoName(indx);
  1085                     final int type = VarType.fromFieldType(fi[2].charAt(0));
  1086                     emit(out, "var @1 = @2(false).constructor.@3;",
  1087                          smapper.pushT(type),
  1088                          accessClass(fi[0].replace('/', '_')), fi[1]);
  1089                     i += 2;
  1090                     addReference(fi[0]);
  1091                     break;
  1092                 }
  1093                 case opc_putfield: {
  1094                     int indx = readIntArg(byteCodes, i);
  1095                     String[] fi = jc.getFieldInfoName(indx);
  1096                     final int type = VarType.fromFieldType(fi[2].charAt(0));
  1097                     emit(out, "@2.fld_@3 = @1;",
  1098                          smapper.popT(type), smapper.popA(), fi[1]);
  1099                     i += 2;
  1100                     break;
  1101                 }
  1102                 case opc_putstatic: {
  1103                     int indx = readIntArg(byteCodes, i);
  1104                     String[] fi = jc.getFieldInfoName(indx);
  1105                     final int type = VarType.fromFieldType(fi[2].charAt(0));
  1106                     emit(out, "@1(false).constructor.@2 = @3;",
  1107                          accessClass(fi[0].replace('/', '_')), fi[1],
  1108                          smapper.popT(type));
  1109                     i += 2;
  1110                     addReference(fi[0]);
  1111                     break;
  1112                 }
  1113                 case opc_checkcast: {
  1114                     int indx = readIntArg(byteCodes, i);
  1115                     final String type = jc.getClassName(indx);
  1116                     if (!type.startsWith("[")) {
  1117                         // no way to check arrays right now
  1118                         // XXX proper exception
  1119                         emit(out,
  1120                              "if (@1 !== null && !@1.$instOf_@2) throw {};",
  1121                              smapper.getA(0), type.replace('/', '_'));
  1122                     }
  1123                     i += 2;
  1124                     break;
  1125                 }
  1126                 case opc_instanceof: {
  1127                     int indx = readIntArg(byteCodes, i);
  1128                     final String type = jc.getClassName(indx);
  1129                     emit(out, "var @2 = @1.$instOf_@3 ? 1 : 0;",
  1130                          smapper.popA(), smapper.pushI(),
  1131                          type.replace('/', '_'));
  1132                     i += 2;
  1133                     break;
  1134                 }
  1135                 case opc_athrow: {
  1136                     final Variable v = smapper.popA();
  1137                     smapper.clear();
  1138 
  1139                     emit(out, "{ var @1 = @2; throw @2; }",
  1140                          smapper.pushA(), v);
  1141                     break;
  1142                 }
  1143 
  1144                 case opc_monitorenter: {
  1145                     out.append("/* monitor enter */");
  1146                     smapper.popA();
  1147                     break;
  1148                 }
  1149 
  1150                 case opc_monitorexit: {
  1151                     out.append("/* monitor exit */");
  1152                     smapper.popA();
  1153                     break;
  1154                 }
  1155 
  1156                 default: {
  1157                     emit(out, "throw 'unknown bytecode @1';",
  1158                          Integer.toString(c));
  1159                 }
  1160             }
  1161             if (debug(" //")) {
  1162                 for (int j = prev; j <= i; j++) {
  1163                     out.append(" ");
  1164                     final int cc = readByte(byteCodes, j);
  1165                     out.append(Integer.toString(cc));
  1166                 }
  1167             }
  1168             out.append("\n");            
  1169         }
  1170         if (previousTrap != null) {
  1171             generateCatch(previousTrap);
  1172         }
  1173         out.append("  }\n");
  1174         out.append("};");
  1175     }
  1176 
  1177     private int generateIf(byte[] byteCodes, int i,
  1178                            final Variable v2, final Variable v1,
  1179                            final String test) throws IOException {
  1180         int indx = i + readIntArg(byteCodes, i);
  1181         out.append("if (").append(v1)
  1182            .append(' ').append(test).append(' ')
  1183            .append(v2).append(") { gt = " + indx)
  1184            .append("; continue; }");
  1185         return i + 2;
  1186     }
  1187 
  1188     private int readIntArg(byte[] byteCodes, int offsetInstruction) {
  1189         final int indxHi = byteCodes[offsetInstruction + 1] << 8;
  1190         final int indxLo = byteCodes[offsetInstruction + 2];
  1191         return (indxHi & 0xffffff00) | (indxLo & 0xff);
  1192     }
  1193     private int readInt4(byte[] byteCodes, int offsetInstruction) {
  1194         final int d = byteCodes[offsetInstruction + 0] << 24;
  1195         final int c = byteCodes[offsetInstruction + 1] << 16;
  1196         final int b = byteCodes[offsetInstruction + 2] << 8;
  1197         final int a = byteCodes[offsetInstruction + 3];
  1198         return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
  1199     }
  1200     private int readByte(byte[] byteCodes, int offsetInstruction) {
  1201         return byteCodes[offsetInstruction] & 0xff;
  1202     }
  1203     
  1204     private static void countArgs(String descriptor, char[] returnType, StringBuilder sig, StringBuilder cnt) {
  1205         int i = 0;
  1206         Boolean count = null;
  1207         boolean array = false;
  1208         sig.append("__");
  1209         int firstPos = sig.length();
  1210         while (i < descriptor.length()) {
  1211             char ch = descriptor.charAt(i++);
  1212             switch (ch) {
  1213                 case '(':
  1214                     count = true;
  1215                     continue;
  1216                 case ')':
  1217                     count = false;
  1218                     continue;
  1219                 case 'B': 
  1220                 case 'C': 
  1221                 case 'D': 
  1222                 case 'F': 
  1223                 case 'I': 
  1224                 case 'J': 
  1225                 case 'S': 
  1226                 case 'Z': 
  1227                     if (count) {
  1228                         if (array) {
  1229                             sig.append("_3");
  1230                         }
  1231                         sig.append(ch);
  1232                         if (ch == 'J' || ch == 'D') {
  1233                             cnt.append('1');
  1234                         } else {
  1235                             cnt.append('0');
  1236                         }
  1237                     } else {
  1238                         sig.insert(firstPos, ch);
  1239                         if (array) {
  1240                             returnType[0] = '[';
  1241                             sig.insert(firstPos, "_3");
  1242                         } else {
  1243                             returnType[0] = ch;
  1244                         }
  1245                     }
  1246                     array = false;
  1247                     continue;
  1248                 case 'V': 
  1249                     assert !count;
  1250                     returnType[0] = 'V';
  1251                     sig.insert(firstPos, 'V');
  1252                     continue;
  1253                 case 'L':
  1254                     int next = descriptor.indexOf(';', i);
  1255                     String realSig = mangleSig(descriptor, i - 1, next + 1);
  1256                     if (count) {
  1257                         if (array) {
  1258                             sig.append("_3");
  1259                         }
  1260                         sig.append(realSig);
  1261                         cnt.append('0');
  1262                     } else {
  1263                         sig.insert(firstPos, realSig);
  1264                         if (array) {
  1265                             sig.insert(firstPos, "_3");
  1266                         }
  1267                         returnType[0] = 'L';
  1268                     }
  1269                     i = next + 1;
  1270                     array = false;
  1271                     continue;
  1272                 case '[':
  1273                     array = true;
  1274                     continue;
  1275                 default:
  1276                     throw new IllegalStateException("Invalid char: " + ch);
  1277             }
  1278         }
  1279     }
  1280     
  1281     private static String mangleSig(String txt, int first, int last) {
  1282         StringBuilder sb = new StringBuilder();
  1283         for (int i = first; i < last; i++) {
  1284             final char ch = txt.charAt(i);
  1285             switch (ch) {
  1286                 case '/': sb.append('_'); break;
  1287                 case '_': sb.append("_1"); break;
  1288                 case ';': sb.append("_2"); break;
  1289                 case '[': sb.append("_3"); break;
  1290                 default: sb.append(ch); break;
  1291             }
  1292         }
  1293         return sb.toString();
  1294     }
  1295 
  1296     private static String findMethodName(MethodData m, StringBuilder cnt) {
  1297         StringBuilder name = new StringBuilder();
  1298         if ("<init>".equals(m.getName())) { // NOI18N
  1299             name.append("cons"); // NOI18N
  1300         } else if ("<clinit>".equals(m.getName())) { // NOI18N
  1301             name.append("class"); // NOI18N
  1302         } else {
  1303             name.append(m.getName());
  1304         } 
  1305         
  1306         countArgs(m.getInternalSig(), new char[1], name, cnt);
  1307         return name.toString();
  1308     }
  1309 
  1310     static String findMethodName(String[] mi, StringBuilder cnt, char[] returnType) {
  1311         StringBuilder name = new StringBuilder();
  1312         String descr = mi[2];//mi.getDescriptor();
  1313         String nm= mi[1];
  1314         if ("<init>".equals(nm)) { // NOI18N
  1315             name.append("cons"); // NOI18N
  1316         } else {
  1317             name.append(nm);
  1318         }
  1319         countArgs(descr, returnType, name, cnt);
  1320         return name.toString();
  1321     }
  1322 
  1323     private int invokeStaticMethod(byte[] byteCodes, int i, final StackMapper mapper, boolean isStatic)
  1324     throws IOException {
  1325         int methodIndex = readIntArg(byteCodes, i);
  1326         String[] mi = jc.getFieldInfoName(methodIndex);
  1327         char[] returnType = { 'V' };
  1328         StringBuilder cnt = new StringBuilder();
  1329         String mn = findMethodName(mi, cnt, returnType);
  1330 
  1331         final int numArguments = isStatic ? cnt.length() : cnt.length() + 1;
  1332         final Variable[] vars = new Variable[numArguments];
  1333 
  1334         for (int j = numArguments - 1; j >= 0; --j) {
  1335             vars[j] = mapper.pop();
  1336         }
  1337 
  1338         if (returnType[0] != 'V') {
  1339             out.append("var ")
  1340                .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
  1341                .append(" = ");
  1342         }
  1343 
  1344         final String in = mi[0];
  1345         out.append(accessClass(in.replace('/', '_')));
  1346         out.append("(false).");
  1347         if (mn.startsWith("cons_")) {
  1348             out.append("constructor.");
  1349         }
  1350         out.append(mn);
  1351         if (isStatic) {
  1352             out.append('(');
  1353         } else {
  1354             out.append(".call(");
  1355         }
  1356         if (numArguments > 0) {
  1357             out.append(vars[0]);
  1358             for (int j = 1; j < numArguments; ++j) {
  1359                 out.append(", ");
  1360                 out.append(vars[j]);
  1361             }
  1362         }
  1363         out.append(");");
  1364         i += 2;
  1365         addReference(in);
  1366         return i;
  1367     }
  1368     private int invokeVirtualMethod(byte[] byteCodes, int i, final StackMapper mapper)
  1369     throws IOException {
  1370         int methodIndex = readIntArg(byteCodes, i);
  1371         String[] mi = jc.getFieldInfoName(methodIndex);
  1372         char[] returnType = { 'V' };
  1373         StringBuilder cnt = new StringBuilder();
  1374         String mn = findMethodName(mi, cnt, returnType);
  1375 
  1376         final int numArguments = cnt.length() + 1;
  1377         final Variable[] vars = new Variable[numArguments];
  1378 
  1379         for (int j = numArguments - 1; j >= 0; --j) {
  1380             vars[j] = mapper.pop();
  1381         }
  1382 
  1383         if (returnType[0] != 'V') {
  1384             out.append("var ")
  1385                .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
  1386                .append(" = ");
  1387         }
  1388 
  1389         out.append(vars[0]).append('.');
  1390         out.append(mn);
  1391         out.append('(');
  1392         String sep = "";
  1393         for (int j = 1; j < numArguments; ++j) {
  1394             out.append(sep);
  1395             out.append(vars[j]);
  1396             sep = ", ";
  1397         }
  1398         out.append(");");
  1399         i += 2;
  1400         return i;
  1401     }
  1402 
  1403     private void addReference(String cn) throws IOException {
  1404         if (requireReference(cn)) {
  1405             debug(" /* needs " + cn + " */");
  1406         }
  1407     }
  1408 
  1409     private void outType(String d, StringBuilder out) {
  1410         int arr = 0;
  1411         while (d.charAt(0) == '[') {
  1412             out.append('A');
  1413             d = d.substring(1);
  1414         }
  1415         if (d.charAt(0) == 'L') {
  1416             assert d.charAt(d.length() - 1) == ';';
  1417             out.append(d.replace('/', '_').substring(0, d.length() - 1));
  1418         } else {
  1419             out.append(d);
  1420         }
  1421     }
  1422 
  1423     private String encodeConstant(int entryIndex) throws IOException {
  1424         String[] classRef = { null };
  1425         String s = jc.stringValue(entryIndex, classRef);
  1426         if (classRef[0] != null) {
  1427             addReference(classRef[0]);
  1428             s = accessClass(s.replace('/', '_')) + "(false).constructor.$class";
  1429         }
  1430         return s;
  1431     }
  1432 
  1433     private String javaScriptBody(String prefix, MethodData m, boolean isStatic) throws IOException {
  1434         byte[] arr = m.findAnnotationData(true);
  1435         if (arr == null) {
  1436             return null;
  1437         }
  1438         final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
  1439         class P extends AnnotationParser {
  1440             public P() {
  1441                 super(false);
  1442             }
  1443             
  1444             int cnt;
  1445             String[] args = new String[30];
  1446             String body;
  1447             
  1448             @Override
  1449             protected void visitAttr(String type, String attr, String at, String value) {
  1450                 if (type.equals(jvmType)) {
  1451                     if ("body".equals(attr)) {
  1452                         body = value;
  1453                     } else if ("args".equals(attr)) {
  1454                         args[cnt++] = value;
  1455                     } else {
  1456                         throw new IllegalArgumentException(attr);
  1457                     }
  1458                 }
  1459             }
  1460         }
  1461         P p = new P();
  1462         p.parse(arr, jc);
  1463         if (p.body == null) {
  1464             return null;
  1465         }
  1466         StringBuilder cnt = new StringBuilder();
  1467         final String mn = findMethodName(m, cnt);
  1468         out.append(prefix).append(mn);
  1469         out.append(" = function(");
  1470         String space = "";
  1471         int index = 0;
  1472         for (int i = 0; i < cnt.length(); i++) {
  1473             out.append(space);
  1474             space = outputArg(out, p.args, index);
  1475             index++;
  1476         }
  1477         out.append(") {").append("\n");
  1478         out.append(p.body);
  1479         out.append("\n}\n");
  1480         return mn;
  1481     }
  1482     private static String className(ClassData jc) {
  1483         //return jc.getName().getInternalName().replace('/', '_');
  1484         return jc.getClassName().replace('/', '_');
  1485     }
  1486     
  1487     private static String[] findAnnotation(
  1488         byte[] arr, ClassData cd, final String className, 
  1489         final String... attrNames
  1490     ) throws IOException {
  1491         if (arr == null) {
  1492             return null;
  1493         }
  1494         final String[] values = new String[attrNames.length];
  1495         final boolean[] found = { false };
  1496         final String jvmType = "L" + className.replace('.', '/') + ";";
  1497         AnnotationParser ap = new AnnotationParser(false) {
  1498             @Override
  1499             protected void visitAttr(String type, String attr, String at, String value) {
  1500                 if (type.equals(jvmType)) {
  1501                     found[0] = true;
  1502                     for (int i = 0; i < attrNames.length; i++) {
  1503                         if (attrNames[i].equals(attr)) {
  1504                             values[i] = value;
  1505                         }
  1506                     }
  1507                 }
  1508             }
  1509             
  1510         };
  1511         ap.parse(arr, cd);
  1512         return found[0] ? values : null;
  1513     }
  1514 
  1515     private CharSequence initField(FieldData v) {
  1516         final String is = v.getInternalSig();
  1517         if (is.length() == 1) {
  1518             switch (is.charAt(0)) {
  1519                 case 'S':
  1520                 case 'J':
  1521                 case 'B':
  1522                 case 'Z':
  1523                 case 'C':
  1524                 case 'I': return " = 0;";
  1525                 case 'F': 
  1526                 case 'D': return " = 0.0;";
  1527                 default:
  1528                     throw new IllegalStateException(is);
  1529             }
  1530         }
  1531         return " = null;";
  1532     }
  1533 
  1534     private static void generateAnno(ClassData cd, final Appendable out, byte[] data) throws IOException {
  1535         AnnotationParser ap = new AnnotationParser(true) {
  1536             int anno;
  1537             int cnt;
  1538             
  1539             @Override
  1540             protected void visitAnnotationStart(String type) throws IOException {
  1541                 if (anno++ > 0) {
  1542                     out.append(",");
  1543                 }
  1544                 out.append('"').append(type).append("\" : {\n");
  1545                 cnt = 0;
  1546             }
  1547 
  1548             @Override
  1549             protected void visitAnnotationEnd(String type) throws IOException {
  1550                 out.append("\n}\n");
  1551             }
  1552             
  1553             @Override
  1554             protected void visitAttr(String type, String attr, String attrType, String value) 
  1555             throws IOException {
  1556                 if (attr == null) {
  1557                     return;
  1558                 }
  1559                 if (cnt++ > 0) {
  1560                     out.append(",\n");
  1561                 }
  1562                 out.append(attr).append("__").append(attrType).append(" : ").append(value);
  1563             }
  1564         };
  1565         ap.parse(data, cd);
  1566     }
  1567 
  1568     private static String outputArg(Appendable out, String[] args, int indx) throws IOException {
  1569         final String name = args[indx];
  1570         if (name == null) {
  1571             return "";
  1572         }
  1573         if (name.contains(",")) {
  1574             throw new IOException("Wrong parameter with ',': " + name);
  1575         }
  1576         out.append(name);
  1577         return ",";
  1578     }
  1579 
  1580     private static void emit(final Appendable out,
  1581                              final String format,
  1582                              final CharSequence... params) throws IOException {
  1583         final int length = format.length();
  1584 
  1585         int processed = 0;
  1586         int paramOffset = format.indexOf('@');
  1587         while ((paramOffset != -1) && (paramOffset < (length - 1))) {
  1588             final char paramChar = format.charAt(paramOffset + 1);
  1589             if ((paramChar >= '1') && (paramChar <= '9')) {
  1590                 final int paramIndex = paramChar - '0' - 1;
  1591 
  1592                 out.append(format, processed, paramOffset);
  1593                 out.append(params[paramIndex]);
  1594 
  1595                 ++paramOffset;
  1596                 processed = paramOffset + 1;
  1597             }
  1598 
  1599             paramOffset = format.indexOf('@', paramOffset + 1);
  1600         }
  1601 
  1602         out.append(format, processed, length);
  1603     }
  1604 
  1605     private void generateCatch(TrapData[] traps) throws IOException {
  1606         out.append("} catch (e) {\n");
  1607         int finallyPC = -1;
  1608         for (TrapData e : traps) {
  1609             if (e == null) {
  1610                 break;
  1611             }
  1612             if (e.catch_cpx != 0) { //not finally
  1613                 final String classInternalName = jc.getClassName(e.catch_cpx);
  1614                 addReference(classInternalName);
  1615                 if ("java/lang/Throwable".equals(classInternalName)) {
  1616                     out.append("if (e.$instOf_java_lang_Throwable) {");
  1617                     out.append("  var stA0 = e;");
  1618                     out.append("} else {");
  1619                     out.append("  var stA0 = vm.java_lang_Throwable(true);");
  1620                     out.append("  vm.java_lang_Throwable.cons__VLjava_lang_String_2.call(stA0, e.toString());");
  1621                     out.append("}");
  1622                     out.append("gt=" + e.handler_pc + "; continue;");
  1623                 } else {
  1624                     out.append("if (e.$instOf_" + classInternalName.replace('/', '_') + ") {");
  1625                     out.append("gt=" + e.handler_pc + "; var stA0 = e; continue;");
  1626                     out.append("}\n");
  1627                 }
  1628             } else {
  1629                 finallyPC = e.handler_pc;
  1630             }
  1631         }
  1632         if (finallyPC == -1) {
  1633             out.append("throw e;");
  1634         } else {
  1635             out.append("gt=" + finallyPC + "; var stA0 = e; continue;");
  1636         }
  1637         out.append("\n}");
  1638     }
  1639 }