src/main/java/org/apidesign/java4browser/ByteCodeToJavaScript.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Mon, 24 Sep 2012 09:35:00 +0200
changeset 21 d8807b6a636a
parent 20 0e7dd9e2e31e
permissions -rw-r--r--
Basic support for manipulating array
     1 /*
     2 Java 4 Browser Bytecode Translator
     3 Copyright (C) 2012-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.java4browser;
    19 
    20 import java.io.IOException;
    21 import java.io.InputStream;
    22 import java.util.ArrayList;
    23 import java.util.Collection;
    24 import java.util.List;
    25 import static org.netbeans.modules.classfile.ByteCodes.*;
    26 import org.netbeans.modules.classfile.CPClassInfo;
    27 import org.netbeans.modules.classfile.CPEntry;
    28 import org.netbeans.modules.classfile.CPFieldInfo;
    29 import org.netbeans.modules.classfile.CPMethodInfo;
    30 import org.netbeans.modules.classfile.CPStringInfo;
    31 import org.netbeans.modules.classfile.ClassFile;
    32 import org.netbeans.modules.classfile.ClassName;
    33 import org.netbeans.modules.classfile.Code;
    34 import org.netbeans.modules.classfile.Method;
    35 import org.netbeans.modules.classfile.Parameter;
    36 import org.netbeans.modules.classfile.Variable;
    37 
    38 /** Translator of the code inside class files to JavaScript.
    39  *
    40  * @author Jaroslav Tulach <jtulach@netbeans.org>
    41  */
    42 public final class ByteCodeToJavaScript {
    43     private final ClassFile jc;
    44     private final Appendable out;
    45     private final Collection<? super String> references;
    46 
    47     private ByteCodeToJavaScript(
    48         ClassFile jc, Appendable out, Collection<? super String> references
    49     ) {
    50         this.jc = jc;
    51         this.out = out;
    52         this.references = references;
    53     }
    54 
    55     /**
    56      * Converts a given class file to a JavaScript version.
    57      *
    58      * @param classFile input stream with code of the .class file
    59      * @param out a {@link StringBuilder} or similar to generate the output to
    60      * @param references a write only collection where the system adds list of
    61      *   other classes that were referenced and should be loaded in order the
    62      *   generated JavaScript code works properly. The names are in internal 
    63      *   JVM form so String is <code>java/lang/String</code>. Can be <code>null</code>
    64      *   if one is not interested in knowing references
    65      * @throws IOException if something goes wrong during read or write or translating
    66      */
    67     
    68     public static void compile(
    69         InputStream classFile, Appendable out,
    70         Collection<? super String> references
    71     ) throws IOException {
    72         ClassFile jc = new ClassFile(classFile, true);
    73         ByteCodeToJavaScript compiler = new ByteCodeToJavaScript(
    74             jc, out, references
    75         );
    76         List<String> toInitilize = new ArrayList<String>();
    77         for (Method m : jc.getMethods()) {
    78             if (m.isStatic()) {
    79                 compiler.generateStaticMethod(m, toInitilize);
    80             } else {
    81                 compiler.generateInstanceMethod(m);
    82             }
    83         }
    84         for (Variable v : jc.getVariables()) {
    85             if (v.isStatic()) {
    86                 compiler.generateStaticField(v);
    87             }
    88         }
    89         
    90         final String className = jc.getName().getInternalName().replace('/', '_');
    91         out.append("\nfunction ").append(className);
    92         out.append("() {");
    93         for (Method m : jc.getMethods()) {
    94             if (!m.isStatic()) {
    95                 compiler.generateMethodReference(m);
    96             }
    97         }
    98         for (Variable v : jc.getVariables()) {
    99             if (!v.isStatic()) {
   100                 out.append("\n  this." + v.getName() + " = 0;");
   101             }
   102         }
   103         out.append("\n  this.$instOf_").append(className).append(" = true;");
   104         out.append("\n}");
   105         ClassName sc = jc.getSuperClass();
   106         if (sc != null) {
   107             out.append("\n").append(className)
   108                .append(".prototype = new ").append(sc.getInternalName().replace('/', '_'));
   109         }
   110         for (String init : toInitilize) {
   111             out.append("\n").append(init).append("();");
   112         }
   113     }
   114     private void generateStaticMethod(Method m, List<String> toInitilize) throws IOException {
   115         final String mn = findMethodName(m);
   116         out.append("\nfunction ").append(
   117             jc.getName().getInternalName().replace('/', '_')
   118         ).append('_').append(mn);
   119         if (mn.equals("classV")) {
   120             toInitilize.add(jc.getName().getInternalName().replace('/', '_') + '_' + mn);
   121         }
   122         out.append('(');
   123         String space = "";
   124         List<Parameter> args = m.getParameters();
   125         for (int index = 0, i = 0; i < args.size(); i++) {
   126             out.append(space);
   127             out.append("arg").append(String.valueOf(index));
   128             space = ",";
   129             final String desc = args.get(i).getDescriptor();
   130             if ("D".equals(desc) || "J".equals(desc)) {
   131                 index += 2;
   132             } else {
   133                 index++;
   134             }
   135         }
   136         out.append(") {").append("\n");
   137         final Code code = m.getCode();
   138         if (code != null) {
   139             int len = code.getMaxLocals();
   140             for (int index = args.size(), i = args.size(); i < len; i++) {
   141                 out.append("  var ");
   142                 out.append("arg").append(String.valueOf(i)).append(";\n");
   143             }
   144             out.append("  var stack = new Array();\n");
   145             produceCode(code.getByteCodes());
   146         } else {
   147             out.append("  /* no code found for ").append(m.getTypeSignature()).append(" */\n");
   148         }
   149         out.append("}");
   150     }
   151     
   152     private void generateMethodReference(Method m) throws IOException {
   153         final String name = findMethodName(m);
   154         out.append("\n  this.").append(name).append(" = ")
   155            .append(jc.getName().getInternalName().replace('/', '_'))
   156            .append('_').append(name).append(";");
   157     }
   158     
   159     private void generateInstanceMethod(Method m) throws IOException {
   160         out.append("\nfunction ").append(
   161             jc.getName().getInternalName().replace('/', '_')
   162         ).append('_').append(findMethodName(m));
   163         out.append("(arg0");
   164         String space = ",";
   165         List<Parameter> args = m.getParameters();
   166         for (int index = 1, i = 0; i < args.size(); i++) {
   167             out.append(space);
   168             out.append("arg").append(String.valueOf(index));
   169             final String desc = args.get(i).getDescriptor();
   170             if ("D".equals(desc) || "J".equals(desc)) {
   171                 index += 2;
   172             } else {
   173                 index++;
   174             }
   175         }
   176         out.append(") {").append("\n");
   177         final Code code = m.getCode();
   178         if (code != null) {
   179             int len = code.getMaxLocals();
   180             for (int index = args.size(), i = args.size(); i < len; i++) {
   181                 out.append("  var ");
   182                 out.append("arg").append(String.valueOf(i + 1)).append(";\n");
   183             }
   184             out.append(";\n  var stack = new Array(");
   185             out.append(Integer.toString(code.getMaxStack()));
   186             out.append(");\n");
   187             produceCode(code.getByteCodes());
   188         } else {
   189             out.append("  /* no code found for ").append(m.getTypeSignature()).append(" */\n");
   190         }
   191         out.append("}");
   192     }
   193 
   194     private void produceCode(byte[] byteCodes) throws IOException {
   195         out.append("\n  var gt = 0;\n  for(;;) switch(gt) {\n");
   196         for (int i = 0; i < byteCodes.length; i++) {
   197             int prev = i;
   198             out.append("    case " + i).append(": ");
   199             final int c = (byteCodes[i] + 256) % 256;
   200             switch (c) {
   201                 case bc_aload_0:
   202                 case bc_iload_0:
   203                 case bc_lload_0:
   204                 case bc_fload_0:
   205                 case bc_dload_0:
   206                     out.append("stack.push(arg0);");
   207                     break;
   208                 case bc_aload_1:
   209                 case bc_iload_1:
   210                 case bc_lload_1:
   211                 case bc_fload_1:
   212                 case bc_dload_1:
   213                     out.append("stack.push(arg1);");
   214                     break;
   215                 case bc_aload_2:
   216                 case bc_iload_2:
   217                 case bc_lload_2:
   218                 case bc_fload_2:
   219                 case bc_dload_2:
   220                     out.append("stack.push(arg2);");
   221                     break;
   222                 case bc_aload_3:
   223                 case bc_iload_3:
   224                 case bc_lload_3:
   225                 case bc_fload_3:
   226                 case bc_dload_3:
   227                     out.append("stack.push(arg3);");
   228                     break;
   229                 case bc_iload:
   230                 case bc_lload:
   231                 case bc_fload:
   232                 case bc_dload:
   233                 case bc_aload: {
   234                     final int indx = (byteCodes[++i] + 256) % 256;
   235                     out.append("stack.push(arg").append(indx + ");");
   236                     break;
   237                 }
   238                 case bc_astore_0:
   239                 case bc_istore_0:
   240                 case bc_lstore_0:
   241                 case bc_fstore_0:
   242                 case bc_dstore_0:
   243                     out.append("arg0 = stack.pop();");
   244                     break;
   245                 case bc_astore_1:
   246                 case bc_istore_1:
   247                 case bc_lstore_1:
   248                 case bc_fstore_1:
   249                 case bc_dstore_1:
   250                     out.append("arg1 = stack.pop();");
   251                     break;
   252                 case bc_astore_2:
   253                 case bc_istore_2:
   254                 case bc_lstore_2:
   255                 case bc_fstore_2:
   256                 case bc_dstore_2:
   257                     out.append("arg2 = stack.pop();");
   258                     break;
   259                 case bc_astore_3:
   260                 case bc_istore_3:
   261                 case bc_lstore_3:
   262                 case bc_fstore_3:
   263                 case bc_dstore_3:
   264                     out.append("arg3 = stack.pop();");
   265                     break;
   266                 case bc_iadd:
   267                 case bc_ladd:
   268                 case bc_fadd:
   269                 case bc_dadd:
   270                     out.append("stack.push(stack.pop() + stack.pop());");
   271                     break;
   272                 case bc_isub:
   273                 case bc_lsub:
   274                 case bc_fsub:
   275                 case bc_dsub:
   276                     out.append("{ var tmp = stack.pop(); stack.push(stack.pop() - tmp); }");
   277                     break;
   278                 case bc_imul:
   279                 case bc_lmul:
   280                 case bc_fmul:
   281                 case bc_dmul:
   282                     out.append("stack.push(stack.pop() * stack.pop());");
   283                     break;
   284                 case bc_idiv:
   285                 case bc_ldiv:
   286                     out.append("{ var tmp = stack.pop(); stack.push(Math.floor(stack.pop() / tmp)); }");
   287                     break;
   288                 case bc_fdiv:
   289                 case bc_ddiv:
   290                     out.append("{ var tmp = stack.pop(); stack.push(stack.pop() / tmp); }");
   291                     break;
   292                 case bc_iand:
   293                 case bc_land:
   294                     out.append("stack.push(stack.pop() & stack.pop());");
   295                     break;
   296                 case bc_ior:
   297                 case bc_lor:
   298                     out.append("stack.push(stack.pop() | stack.pop());");
   299                     break;
   300                 case bc_ixor:
   301                 case bc_lxor:
   302                     out.append("stack.push(stack.pop() ^ stack.pop());");
   303                     break;
   304                 case bc_iinc: {
   305                     final int varIndx = (byteCodes[++i] + 256) % 256;
   306                     final int incrBy = (byteCodes[++i] + 256) % 256;
   307                     if (incrBy == 1) {
   308                         out.append("arg" + varIndx).append("++;");
   309                     } else {
   310                         out.append("arg" + varIndx).append(" += " + incrBy).append(";");
   311                     }
   312                     break;
   313                 }
   314                 case bc_return:
   315                     out.append("return;");
   316                     break;
   317                 case bc_ireturn:
   318                 case bc_lreturn:
   319                 case bc_freturn:
   320                 case bc_dreturn:
   321                 case bc_areturn:
   322                     out.append("return stack.pop();");
   323                     break;
   324                 case bc_i2l:
   325                 case bc_i2f:
   326                 case bc_i2d:
   327                 case bc_l2i:
   328                     // max int check?
   329                 case bc_l2f:
   330                 case bc_l2d:
   331                 case bc_f2d:
   332                 case bc_d2f:
   333                     out.append("/* number conversion */");
   334                     break;
   335                 case bc_f2i:
   336                 case bc_f2l:
   337                 case bc_d2i:
   338                 case bc_d2l:
   339                     out.append("stack.push(Math.floor(stack.pop()));");
   340                     break;
   341                 case bc_i2b:
   342                 case bc_i2c:
   343                 case bc_i2s:
   344                     out.append("/* number conversion */");
   345                     break;
   346                 case bc_iconst_0:
   347                 case bc_dconst_0:
   348                 case bc_lconst_0:
   349                 case bc_fconst_0:
   350                     out.append("stack.push(0);");
   351                     break;
   352                 case bc_iconst_1:
   353                 case bc_lconst_1:
   354                 case bc_fconst_1:
   355                 case bc_dconst_1:
   356                     out.append("stack.push(1);");
   357                     break;
   358                 case bc_iconst_2:
   359                 case bc_fconst_2:
   360                     out.append("stack.push(2);");
   361                     break;
   362                 case bc_iconst_3:
   363                     out.append("stack.push(3);");
   364                     break;
   365                 case bc_iconst_4:
   366                     out.append("stack.push(4);");
   367                     break;
   368                 case bc_iconst_5:
   369                     out.append("stack.push(5);");
   370                     break;
   371                 case bc_ldc: {
   372                     int indx = byteCodes[++i];
   373                     CPEntry entry = jc.getConstantPool().get(indx);
   374                     String v = encodeConstant(entry);
   375                     out.append("stack.push(").append(v).append(");");
   376                     break;
   377                 }
   378                 case bc_ldc_w:
   379                 case bc_ldc2_w: {
   380                     int indx = readIntArg(byteCodes, i);
   381                     CPEntry entry = jc.getConstantPool().get(indx);
   382                     i += 2;
   383                     String v = encodeConstant(entry);
   384                     out.append("stack.push(").append(v).append(");");
   385                     break;
   386                 }
   387                 case bc_lcmp:
   388                 case bc_fcmpl:
   389                 case bc_fcmpg:
   390                 case bc_dcmpl:
   391                 case bc_dcmpg: {
   392                     out.append("{ var delta = stack.pop() - stack.pop(); stack.push(delta < 0 ?-1 : (delta == 0 ? 0 : 1)); }");
   393                     break;
   394                 }
   395                 case bc_if_icmpeq: {
   396                     i = generateIf(byteCodes, i, "==");
   397                     break;
   398                 }
   399                 case bc_ifeq: {
   400                     int indx = i + readIntArg(byteCodes, i);
   401                     out.append("if (stack.pop() == 0) { gt = " + indx);
   402                     out.append("; continue; }");
   403                     i += 2;
   404                     break;
   405                 }
   406                 case bc_ifne: {
   407                     int indx = i + readIntArg(byteCodes, i);
   408                     out.append("if (stack.pop() != 0) { gt = " + indx);
   409                     out.append("; continue; }");
   410                     i += 2;
   411                     break;
   412                 }
   413                 case bc_iflt: {
   414                     int indx = i + readIntArg(byteCodes, i);
   415                     out.append("if (stack.pop() < 0) { gt = " + indx);
   416                     out.append("; continue; }");
   417                     i += 2;
   418                     break;
   419                 }
   420                 case bc_ifle: {
   421                     int indx = i + readIntArg(byteCodes, i);
   422                     out.append("if (stack.pop() <= 0) { gt = " + indx);
   423                     out.append("; continue; }");
   424                     i += 2;
   425                     break;
   426                 }
   427                 case bc_ifgt: {
   428                     int indx = i + readIntArg(byteCodes, i);
   429                     out.append("if (stack.pop() > 0) { gt = " + indx);
   430                     out.append("; continue; }");
   431                     i += 2;
   432                     break;
   433                 }
   434                 case bc_ifge: {
   435                     int indx = i + readIntArg(byteCodes, i);
   436                     out.append("if (stack.pop() >= 0) { gt = " + indx);
   437                     out.append("; continue; }");
   438                     i += 2;
   439                     break;
   440                 }
   441                 case bc_ifnonnull: {
   442                     int indx = i + readIntArg(byteCodes, i);
   443                     out.append("if (stack.pop()) { gt = " + indx);
   444                     out.append("; continue; }");
   445                     i += 2;
   446                     break;
   447                 }
   448                 case bc_ifnull: {
   449                     int indx = i + readIntArg(byteCodes, i);
   450                     out.append("if (!stack.pop()) { gt = " + indx);
   451                     out.append("; continue; }");
   452                     i += 2;
   453                     break;
   454                 }
   455                 case bc_if_icmpne:
   456                     i = generateIf(byteCodes, i, "!=");
   457                     break;
   458                 case bc_if_icmplt:
   459                     i = generateIf(byteCodes, i, ">");
   460                     break;
   461                 case bc_if_icmple:
   462                     i = generateIf(byteCodes, i, ">=");
   463                     break;
   464                 case bc_if_icmpgt:
   465                     i = generateIf(byteCodes, i, "<");
   466                     break;
   467                 case bc_if_icmpge:
   468                     i = generateIf(byteCodes, i, "<=");
   469                     break;
   470                 case bc_goto: {
   471                     int indx = i + readIntArg(byteCodes, i);
   472                     out.append("gt = " + indx).append("; continue;");
   473                     i += 2;
   474                     break;
   475                 }
   476                 case bc_invokeinterface:
   477                 case bc_invokevirtual:
   478                     i = invokeVirtualMethod(byteCodes, i);
   479                     break;
   480                 case bc_invokespecial:
   481                     i = invokeStaticMethod(byteCodes, i, false);
   482                     break;
   483                 case bc_invokestatic:
   484                     i = invokeStaticMethod(byteCodes, i, true);
   485                     break;
   486                 case bc_new: {
   487                     int indx = readIntArg(byteCodes, i);
   488                     CPClassInfo ci = jc.getConstantPool().getClass(indx);
   489                     out.append("stack.push(");
   490                     out.append("new ").append(ci.getClassName().getInternalName().replace('/','_'));
   491                     out.append(");");
   492                     addReference(ci.getClassName().getInternalName());
   493                     i += 2;
   494                     break;
   495                 }
   496                 case bc_newarray: {
   497                     int type = byteCodes[i++];
   498                     out.append("stack.push(new Array(stack.pop()));");
   499                     break;
   500                 }
   501                 case bc_anewarray: {
   502                     i += 2; // skip type of array
   503                     out.append("stack.push(new Array(stack.pop()));");
   504                     break;
   505                 }
   506                 case bc_arraylength:
   507                     out.append("stack.push(stack.pop().length);");
   508                     break;
   509                 case bc_iastore:
   510                 case bc_lastore:
   511                 case bc_fastore:
   512                 case bc_dastore:
   513                 case bc_aastore:
   514                 case bc_bastore:
   515                 case bc_castore:
   516                 case bc_sastore: {
   517                     out.append("{ var value = stack.pop(); var indx = stack.pop(); stack.pop()[indx] = value; }");
   518                     break;
   519                 }
   520                 case bc_iaload:
   521                 case bc_laload:
   522                 case bc_faload:
   523                 case bc_daload:
   524                 case bc_aaload:
   525                 case bc_baload:
   526                 case bc_caload:
   527                 case bc_saload: {
   528                     out.append("{ var indx = stack.pop(); stack.push(stack.pop()[indx]); }");
   529                     break;
   530                 }
   531                 case bc_dup:
   532                     out.append("stack.push(stack[stack.length - 1]);");
   533                     break;
   534                 case bc_bipush:
   535                     out.append("stack.push(" + byteCodes[++i] + ");");
   536                     break;
   537                 case bc_getfield: {
   538                     int indx = readIntArg(byteCodes, i);
   539                     CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
   540                     out.append("stack.push(stack.pop().").append(fi.getFieldName()).append(");");
   541                     i += 2;
   542                     break;
   543                 }
   544                 case bc_getstatic: {
   545                     int indx = readIntArg(byteCodes, i);
   546                     CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
   547                     final String in = fi.getClassName().getInternalName();
   548                     out.append("stack.push(").append(in.replace('/', '_'));
   549                     out.append('_').append(fi.getFieldName()).append(");");
   550                     i += 2;
   551                     addReference(in);
   552                     break;
   553                 }
   554                 case bc_putstatic: {
   555                     int indx = readIntArg(byteCodes, i);
   556                     CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
   557                     final String in = fi.getClassName().getInternalName();
   558                     out.append(in.replace('/', '_'));
   559                     out.append('_').append(fi.getFieldName()).append(" = stack.pop();");
   560                     i += 2;
   561                     addReference(in);
   562                     break;
   563                 }
   564                 case bc_putfield: {
   565                     int indx = readIntArg(byteCodes, i);
   566                     CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
   567                     out.append("{ var v = stack.pop(); stack.pop().")
   568                        .append(fi.getFieldName()).append(" = v; }");
   569                     i += 2;
   570                     break;
   571                 }
   572                 case bc_instanceof: {
   573                     int indx = readIntArg(byteCodes, i);
   574                     CPClassInfo ci = jc.getConstantPool().getClass(indx);
   575                     out.append("stack.push(stack.pop().$instOf_")
   576                        .append(ci.getClassName().getInternalName().replace('/', '_'))
   577                        .append(" ? 1 : 0);");
   578                     i += 2;
   579                 }
   580                     
   581             }
   582             out.append(" /*");
   583             for (int j = prev; j <= i; j++) {
   584                 out.append(" ");
   585                 final int cc = (byteCodes[j] + 256) % 256;
   586                 out.append(Integer.toString(cc));
   587             }
   588             out.append("*/\n");
   589         }
   590         out.append("  }\n");
   591     }
   592 
   593     private int generateIf(byte[] byteCodes, int i, final String test) throws IOException {
   594         int indx = i + readIntArg(byteCodes, i);
   595         out.append("if (stack.pop() ").append(test).append(" stack.pop()) { gt = " + indx);
   596         out.append("; continue; }");
   597         return i + 2;
   598     }
   599 
   600     private int readIntArg(byte[] byteCodes, int offsetInstruction) {
   601         final int indxHi = byteCodes[offsetInstruction + 1] << 8;
   602         final int indxLo = byteCodes[offsetInstruction + 2];
   603         return (indxHi & 0xffffff00) | (indxLo & 0xff);
   604     }
   605     
   606     private static int countArgs(String descriptor, boolean[] hasReturnType, StringBuilder sig) {
   607         int cnt = 0;
   608         int i = 0;
   609         Boolean count = null;
   610         int firstPos = sig.length();
   611         while (i < descriptor.length()) {
   612             char ch = descriptor.charAt(i++);
   613             switch (ch) {
   614                 case '(':
   615                     count = true;
   616                     continue;
   617                 case ')':
   618                     count = false;
   619                     continue;
   620                 case 'B': 
   621                 case 'C': 
   622                 case 'D': 
   623                 case 'F': 
   624                 case 'I': 
   625                 case 'J': 
   626                 case 'S': 
   627                 case 'Z': 
   628                     if (count) {
   629                         cnt++;
   630                         sig.append(ch);
   631                     } else {
   632                         hasReturnType[0] = true;
   633                         sig.insert(firstPos, ch);
   634                     }
   635                     continue;
   636                 case 'V': 
   637                     assert !count;
   638                     hasReturnType[0] = false;
   639                     sig.insert(firstPos, 'V');
   640                     continue;
   641                 case 'L':
   642                     int next = descriptor.indexOf(';', i);
   643                     if (count) {
   644                         cnt++;
   645                         sig.append(ch);
   646                         sig.append(descriptor.substring(i, next).replace('/', '_'));
   647                     } else {
   648                         sig.insert(firstPos, descriptor.substring(i, next).replace('/', '_'));
   649                         sig.insert(firstPos, ch);
   650                         hasReturnType[0] = true;
   651                     }
   652                     i = next + 1;
   653                     continue;
   654                 case '[':
   655                     //arrays++;
   656                     continue;
   657                 default:
   658                     break; // invalid character
   659             }
   660         }
   661         return cnt;
   662     }
   663 
   664     private void generateStaticField(Variable v) throws IOException {
   665         out.append("\nvar ")
   666            .append(jc.getName().getInternalName().replace('/', '_'))
   667            .append('_').append(v.getName()).append(" = 0;");
   668     }
   669 
   670     private String findMethodName(Method m) {
   671         StringBuilder tmp = new StringBuilder();
   672         if ("<init>".equals(m.getName())) { // NOI18N
   673             tmp.append("consV"); // NOI18N
   674         } else if ("<clinit>".equals(m.getName())) { // NOI18N
   675             tmp.append("classV"); // NOI18N
   676         } else {
   677             tmp.append(m.getName());
   678             outType(m.getReturnType(), tmp);
   679         } 
   680         List<Parameter> args = m.getParameters();
   681         for (Parameter t : args) {
   682             outType(t.getDescriptor(), tmp);
   683         }
   684         return tmp.toString();
   685     }
   686 
   687     private String findMethodName(CPMethodInfo mi, int[] cnt, boolean[] hasReturn) {
   688         StringBuilder name = new StringBuilder();
   689         if ("<init>".equals(mi.getName())) { // NOI18N
   690             name.append("cons"); // NOI18N
   691         } else {
   692             name.append(mi.getName());
   693         }
   694         cnt[0] = countArgs(mi.getDescriptor(), hasReturn, name);
   695         return name.toString();
   696     }
   697 
   698     private int invokeStaticMethod(byte[] byteCodes, int i, boolean isStatic)
   699     throws IOException {
   700         int methodIndex = readIntArg(byteCodes, i);
   701         CPMethodInfo mi = (CPMethodInfo) jc.getConstantPool().get(methodIndex);
   702         boolean[] hasReturn = { false };
   703         int[] cnt = { 0 };
   704         String mn = findMethodName(mi, cnt, hasReturn);
   705         out.append("{ ");
   706         for (int j = cnt[0] - 1; j >= 0; j--) {
   707             out.append("var v" + j).append(" = stack.pop(); ");
   708         }
   709         
   710         if (hasReturn[0]) {
   711             out.append("stack.push(");
   712         }
   713         final String in = mi.getClassName().getInternalName();
   714         out.append(in.replace('/', '_'));
   715         out.append('_');
   716         out.append(mn);
   717         out.append('(');
   718         String sep = "";
   719         if (!isStatic) {
   720             out.append("stack.pop()");
   721             sep = ", ";
   722         }
   723         for (int j = 0; j < cnt[0]; j++) {
   724             out.append(sep);
   725             out.append("v" + j);
   726             sep = ", ";
   727         }
   728         out.append(")");
   729         if (hasReturn[0]) {
   730             out.append(")");
   731         }
   732         out.append("; }");
   733         i += 2;
   734         addReference(in);
   735         return i;
   736     }
   737     private int invokeVirtualMethod(byte[] byteCodes, int i)
   738     throws IOException {
   739         int methodIndex = readIntArg(byteCodes, i);
   740         CPMethodInfo mi = (CPMethodInfo) jc.getConstantPool().get(methodIndex);
   741         boolean[] hasReturn = { false };
   742         int[] cnt = { 0 };
   743         String mn = findMethodName(mi, cnt, hasReturn);
   744         out.append("{ ");
   745         for (int j = cnt[0] - 1; j >= 0; j--) {
   746             out.append("var v" + j).append(" = stack.pop(); ");
   747         }
   748         out.append("var self = stack.pop(); ");
   749         if (hasReturn[0]) {
   750             out.append("stack.push(");
   751         }
   752         out.append("self.");
   753         out.append(mn);
   754         out.append('(');
   755         out.append("self");
   756         for (int j = 0; j < cnt[0]; j++) {
   757             out.append(", ");
   758             out.append("v" + j);
   759         }
   760         out.append(")");
   761         if (hasReturn[0]) {
   762             out.append(")");
   763         }
   764         out.append("; }");
   765         i += 2;
   766         return i;
   767     }
   768     
   769     private void addReference(String cn) {
   770         if (references != null) {
   771             references.add(cn);
   772         }
   773     }
   774 
   775     private void outType(final String d, StringBuilder out) {
   776         if (d.charAt(0) == 'L') {
   777             assert d.charAt(d.length() - 1) == ';';
   778             out.append(d.replace('/', '_').substring(0, d.length() - 1));
   779         } else {
   780             out.append(d);
   781         }
   782     }
   783 
   784     private String encodeConstant(CPEntry entry) {
   785         final String v;
   786         if (entry instanceof CPStringInfo) {
   787             v = "\"" + entry.getValue().toString().replace("\"", "\\\"") + "\"";
   788         } else {
   789             v = entry.getValue().toString();
   790         }
   791         return v;
   792     }
   793 }