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