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