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