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