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