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