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