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