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