vm/src/main/java/org/apidesign/vm4brwsr/ByteCodeToJavaScript.java
author Jaroslav Tulach <jtulach@netbeans.org>
Tue, 30 Oct 2012 22:35:32 +0100
changeset 129 15df78d24302
parent 128 8db5cf267d74
child 130 0b7c9b5b8079
permissions -rw-r--r--
Print the information about "needs" only once per each type
     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 java.util.ArrayList;
    23 import java.util.Collection;
    24 import java.util.List;
    25 import org.apidesign.bck2brwsr.core.ExtraJavaScript;
    26 import org.apidesign.bck2brwsr.core.JavaScriptBody;
    27 import org.netbeans.modules.classfile.Annotation;
    28 import org.netbeans.modules.classfile.AnnotationComponent;
    29 import org.netbeans.modules.classfile.ArrayElementValue;
    30 import static org.netbeans.modules.classfile.ByteCodes.*;
    31 import org.netbeans.modules.classfile.CPClassInfo;
    32 import org.netbeans.modules.classfile.CPEntry;
    33 import org.netbeans.modules.classfile.CPFieldInfo;
    34 import org.netbeans.modules.classfile.CPMethodInfo;
    35 import org.netbeans.modules.classfile.CPStringInfo;
    36 import org.netbeans.modules.classfile.ClassFile;
    37 import org.netbeans.modules.classfile.ClassName;
    38 import org.netbeans.modules.classfile.Code;
    39 import org.netbeans.modules.classfile.ElementValue;
    40 import org.netbeans.modules.classfile.Method;
    41 import org.netbeans.modules.classfile.Parameter;
    42 import org.netbeans.modules.classfile.PrimitiveElementValue;
    43 import org.netbeans.modules.classfile.Variable;
    44 
    45 /** Translator of the code inside class files to JavaScript.
    46  *
    47  * @author Jaroslav Tulach <jtulach@netbeans.org>
    48  */
    49 public final class ByteCodeToJavaScript {
    50     private final ClassFile jc;
    51     private final Appendable out;
    52     private final Collection<? super String> references;
    53 
    54     private ByteCodeToJavaScript(
    55         ClassFile jc, Appendable out, Collection<? super String> references
    56     ) {
    57         this.jc = jc;
    58         this.out = out;
    59         this.references = references;
    60     }
    61 
    62     /**
    63      * Converts a given class file to a JavaScript version.
    64      *
    65      * @param classFile input stream with code of the .class file
    66      * @param out a {@link StringBuilder} or similar to generate the output to
    67      * @param references a write only collection where the system adds list of
    68      *   other classes that were referenced and should be loaded in order the
    69      *   generated JavaScript code works properly. The names are in internal 
    70      *   JVM form so String is <code>java/lang/String</code>. Can be <code>null</code>
    71      *   if one is not interested in knowing references
    72      * @param scripts write only collection with names of resources to read
    73      * @return the initialization code for this class, if any. Otherwise <code>null</code>
    74      * 
    75      * @throws IOException if something goes wrong during read or write or translating
    76      */
    77     
    78     public static String compile(
    79         InputStream classFile, Appendable out,
    80         Collection<? super String> references,
    81         Collection<? super String> scripts
    82     ) throws IOException {
    83         ClassFile jc = new ClassFile(classFile, true);
    84         final ClassName extraAnn = ClassName.getClassName(ExtraJavaScript.class.getName().replace('.', '/'));
    85         Annotation a = jc.getAnnotation(extraAnn);
    86         if (a != null) {
    87             final ElementValue annVal = a.getComponent("resource").getValue();
    88             String res = ((PrimitiveElementValue)annVal).getValue().getValue().toString();
    89             scripts.add(res);
    90             final AnnotationComponent process = a.getComponent("processByteCode");
    91             if (process != null && "const=0".equals(process.getValue().toString())) {
    92                 return null;
    93             }
    94         }
    95         
    96         ByteCodeToJavaScript compiler = new ByteCodeToJavaScript(
    97             jc, out, references
    98         );
    99         List<String> toInitilize = new ArrayList<String>();
   100         for (Method m : jc.getMethods()) {
   101             if (m.isStatic()) {
   102                 compiler.generateStaticMethod(m, toInitilize);
   103             } else {
   104                 compiler.generateInstanceMethod(m);
   105             }
   106         }
   107         for (Variable v : jc.getVariables()) {
   108             if (v.isStatic()) {
   109                 compiler.generateStaticField(v);
   110             }
   111         }
   112         
   113         final String className = jc.getName().getInternalName().replace('/', '_');
   114         out.append("\nfunction ").append(className);
   115         out.append("() {");
   116         for (Variable v : jc.getVariables()) {
   117             if (!v.isStatic()) {
   118                 out.append("\n  this." + v.getName() + " = 0;");
   119             }
   120         }
   121         out.append("\n}\n\nfunction ").append(className).append("_proto() {");
   122         out.append("\n  if (").append(className).
   123             append(".prototype.$instOf_").append(className).append(") {");
   124         out.append("\n    return ").append(className).append(".prototype;");
   125         out.append("\n  }");
   126         ClassName sc = jc.getSuperClass();
   127         if (sc != null) {
   128             out.append("\n  ").append(sc.getInternalName().replace('/', '_')).append("_proto();");
   129             out.append("\n  ").append(className)
   130                .append(".prototype = new ").append(sc.getInternalName().replace('/', '_')).append(';');
   131         }
   132         for (Method m : jc.getMethods()) {
   133             if (!m.getName().contains("<init>") && !m.getName().contains("<cinit>")) {
   134                 compiler.generateMethodReference("\n  " + className + ".prototype.", m);
   135             }
   136         }
   137         out.append("\n  " + className + ".prototype.$instOf_").append(className).append(" = true;");
   138         for (ClassName superInterface : jc.getInterfaces()) {
   139             out.append("\n  " + className + ".prototype.$instOf_").append(superInterface.getInternalName().replace('/', '_')).append(" = true;");
   140         }
   141         out.append("\n  return ").append(className).append(".prototype;");
   142         out.append("\n}");
   143         out.append("\n").append(className).append("_proto();");
   144         StringBuilder sb = new StringBuilder();
   145         for (String init : toInitilize) {
   146             sb.append("\n").append(init).append("();");
   147         }
   148         return sb.toString();
   149     }
   150     private void generateStaticMethod(Method m, List<String> toInitilize) throws IOException {
   151         if (javaScriptBody(m, true)) {
   152             return;
   153         }
   154         final String mn = findMethodName(m);
   155         out.append("\nfunction ").append(
   156             jc.getName().getInternalName().replace('/', '_')
   157         ).append('_').append(mn);
   158         if (mn.equals("classV")) {
   159             toInitilize.add(jc.getName().getInternalName().replace('/', '_') + '_' + mn);
   160         }
   161         out.append('(');
   162         String space = "";
   163         List<Parameter> args = m.getParameters();
   164         for (int index = 0, i = 0; i < args.size(); i++) {
   165             out.append(space);
   166             out.append("arg").append(String.valueOf(index));
   167             space = ",";
   168             final String desc = findDescriptor(args.get(i).getDescriptor());
   169             if ("D".equals(desc) || "J".equals(desc)) {
   170                 index += 2;
   171             } else {
   172                 index++;
   173             }
   174         }
   175         out.append(") {").append("\n");
   176         final Code code = m.getCode();
   177         if (code != null) {
   178             int len = code.getMaxLocals();
   179             for (int index = args.size(), i = args.size(); i < len; i++) {
   180                 out.append("  var ");
   181                 out.append("arg").append(String.valueOf(i)).append(";\n");
   182             }
   183             out.append("  var stack = new Array();\n");
   184             produceCode(code.getByteCodes());
   185         } else {
   186             out.append("  /* no code found for ").append(m.getTypeSignature()).append(" */\n");
   187         }
   188         out.append("}");
   189     }
   190     
   191     private void generateMethodReference(String prefix, Method m) throws IOException {
   192         final String name = findMethodName(m);
   193         out.append(prefix).append(name).append(" = ")
   194            .append(jc.getName().getInternalName().replace('/', '_'))
   195            .append('_').append(name).append(";");
   196     }
   197     
   198     private void generateInstanceMethod(Method m) throws IOException {
   199         if (javaScriptBody(m, false)) {
   200             return;
   201         }
   202         out.append("\nfunction ").append(
   203             jc.getName().getInternalName().replace('/', '_')
   204         ).append('_').append(findMethodName(m));
   205         out.append("(arg0");
   206         String space = ",";
   207         List<Parameter> args = m.getParameters();
   208         for (int index = 1, i = 0; i < args.size(); i++) {
   209             out.append(space);
   210             out.append("arg").append(String.valueOf(index));
   211             final String desc = findDescriptor(args.get(i).getDescriptor());
   212             if ("D".equals(desc) || "J".equals(desc)) {
   213                 index += 2;
   214             } else {
   215                 index++;
   216             }
   217         }
   218         out.append(") {").append("\n");
   219         final Code code = m.getCode();
   220         if (code != null) {
   221             int len = code.getMaxLocals();
   222             for (int index = args.size(), i = args.size(); i < len; i++) {
   223                 out.append("  var ");
   224                 out.append("arg").append(String.valueOf(i + 1)).append(";\n");
   225             }
   226             out.append(";\n  var stack = new Array();\n");
   227             produceCode(code.getByteCodes());
   228         } else {
   229             out.append("  /* no code found for ").append(m.getTypeSignature()).append(" */\n");
   230         }
   231         out.append("}");
   232     }
   233 
   234     private void produceCode(byte[] byteCodes) throws IOException {
   235         out.append("\n  var gt = 0;\n  for(;;) switch(gt) {\n");
   236         for (int i = 0; i < byteCodes.length; i++) {
   237             int prev = i;
   238             out.append("    case " + i).append(": ");
   239             final int c = readByte(byteCodes, i);
   240             switch (c) {
   241                 case bc_aload_0:
   242                 case bc_iload_0:
   243                 case bc_lload_0:
   244                 case bc_fload_0:
   245                 case bc_dload_0:
   246                     out.append("stack.push(arg0);");
   247                     break;
   248                 case bc_aload_1:
   249                 case bc_iload_1:
   250                 case bc_lload_1:
   251                 case bc_fload_1:
   252                 case bc_dload_1:
   253                     out.append("stack.push(arg1);");
   254                     break;
   255                 case bc_aload_2:
   256                 case bc_iload_2:
   257                 case bc_lload_2:
   258                 case bc_fload_2:
   259                 case bc_dload_2:
   260                     out.append("stack.push(arg2);");
   261                     break;
   262                 case bc_aload_3:
   263                 case bc_iload_3:
   264                 case bc_lload_3:
   265                 case bc_fload_3:
   266                 case bc_dload_3:
   267                     out.append("stack.push(arg3);");
   268                     break;
   269                 case bc_iload:
   270                 case bc_lload:
   271                 case bc_fload:
   272                 case bc_dload:
   273                 case bc_aload: {
   274                     final int indx = readByte(byteCodes, ++i);
   275                     out.append("stack.push(arg").append(indx + ");");
   276                     break;
   277                 }
   278                 case bc_istore:
   279                 case bc_lstore:
   280                 case bc_fstore:
   281                 case bc_dstore:
   282                 case bc_astore: {
   283                     final int indx = readByte(byteCodes, ++i);
   284                     out.append("arg" + indx).append(" = stack.pop()");
   285                     break;
   286                 }
   287                 case bc_astore_0:
   288                 case bc_istore_0:
   289                 case bc_lstore_0:
   290                 case bc_fstore_0:
   291                 case bc_dstore_0:
   292                     out.append("arg0 = stack.pop();");
   293                     break;
   294                 case bc_astore_1:
   295                 case bc_istore_1:
   296                 case bc_lstore_1:
   297                 case bc_fstore_1:
   298                 case bc_dstore_1:
   299                     out.append("arg1 = stack.pop();");
   300                     break;
   301                 case bc_astore_2:
   302                 case bc_istore_2:
   303                 case bc_lstore_2:
   304                 case bc_fstore_2:
   305                 case bc_dstore_2:
   306                     out.append("arg2 = stack.pop();");
   307                     break;
   308                 case bc_astore_3:
   309                 case bc_istore_3:
   310                 case bc_lstore_3:
   311                 case bc_fstore_3:
   312                 case bc_dstore_3:
   313                     out.append("arg3 = stack.pop();");
   314                     break;
   315                 case bc_iadd:
   316                 case bc_ladd:
   317                 case bc_fadd:
   318                 case bc_dadd:
   319                     out.append("stack.push(stack.pop() + stack.pop());");
   320                     break;
   321                 case bc_isub:
   322                 case bc_lsub:
   323                 case bc_fsub:
   324                 case bc_dsub:
   325                     out.append("{ var tmp = stack.pop(); stack.push(stack.pop() - tmp); }");
   326                     break;
   327                 case bc_imul:
   328                 case bc_lmul:
   329                 case bc_fmul:
   330                 case bc_dmul:
   331                     out.append("stack.push(stack.pop() * stack.pop());");
   332                     break;
   333                 case bc_idiv:
   334                 case bc_ldiv:
   335                     out.append("{ var tmp = stack.pop(); stack.push(Math.floor(stack.pop() / tmp)); }");
   336                     break;
   337                 case bc_fdiv:
   338                 case bc_ddiv:
   339                     out.append("{ var tmp = stack.pop(); stack.push(stack.pop() / tmp); }");
   340                     break;
   341                 case bc_iand:
   342                 case bc_land:
   343                     out.append("stack.push(stack.pop() & stack.pop());");
   344                     break;
   345                 case bc_ior:
   346                 case bc_lor:
   347                     out.append("stack.push(stack.pop() | stack.pop());");
   348                     break;
   349                 case bc_ixor:
   350                 case bc_lxor:
   351                     out.append("stack.push(stack.pop() ^ stack.pop());");
   352                     break;
   353                 case bc_ineg:
   354                 case bc_lneg:
   355                 case bc_fneg:
   356                 case bc_dneg:
   357                     out.append("stack.push(- stack.pop());");
   358                     break;
   359                 case bc_ishl:
   360                 case bc_lshl:
   361                     out.append("{ var v = stack.pop(); stack.push(stack.pop() << v); }");
   362                     break;
   363                 case bc_ishr:
   364                 case bc_lshr:
   365                     out.append("{ var v = stack.pop(); stack.push(stack.pop() >> v); }");
   366                     break;
   367                 case bc_iushr:
   368                 case bc_lushr:
   369                     out.append("{ var v = stack.pop(); stack.push(stack.pop() >>> v); }");
   370                     break;
   371                 case bc_iinc: {
   372                     final int varIndx = readByte(byteCodes, ++i);
   373                     final int incrBy = byteCodes[++i];
   374                     if (incrBy == 1) {
   375                         out.append("arg" + varIndx).append("++;");
   376                     } else {
   377                         out.append("arg" + varIndx).append(" += " + incrBy).append(";");
   378                     }
   379                     break;
   380                 }
   381                 case bc_return:
   382                     out.append("return;");
   383                     break;
   384                 case bc_ireturn:
   385                 case bc_lreturn:
   386                 case bc_freturn:
   387                 case bc_dreturn:
   388                 case bc_areturn:
   389                     out.append("return stack.pop();");
   390                     break;
   391                 case bc_i2l:
   392                 case bc_i2f:
   393                 case bc_i2d:
   394                 case bc_l2i:
   395                     // max int check?
   396                 case bc_l2f:
   397                 case bc_l2d:
   398                 case bc_f2d:
   399                 case bc_d2f:
   400                     out.append("/* number conversion */");
   401                     break;
   402                 case bc_f2i:
   403                 case bc_f2l:
   404                 case bc_d2i:
   405                 case bc_d2l:
   406                     out.append("stack.push(Math.floor(stack.pop()));");
   407                     break;
   408                 case bc_i2b:
   409                 case bc_i2c:
   410                 case bc_i2s:
   411                     out.append("/* number conversion */");
   412                     break;
   413                 case bc_aconst_null:
   414                     out.append("stack.push(null);");
   415                     break;
   416                 case bc_iconst_m1:
   417                     out.append("stack.push(-1);");
   418                     break;
   419                 case bc_iconst_0:
   420                 case bc_dconst_0:
   421                 case bc_lconst_0:
   422                 case bc_fconst_0:
   423                     out.append("stack.push(0);");
   424                     break;
   425                 case bc_iconst_1:
   426                 case bc_lconst_1:
   427                 case bc_fconst_1:
   428                 case bc_dconst_1:
   429                     out.append("stack.push(1);");
   430                     break;
   431                 case bc_iconst_2:
   432                 case bc_fconst_2:
   433                     out.append("stack.push(2);");
   434                     break;
   435                 case bc_iconst_3:
   436                     out.append("stack.push(3);");
   437                     break;
   438                 case bc_iconst_4:
   439                     out.append("stack.push(4);");
   440                     break;
   441                 case bc_iconst_5:
   442                     out.append("stack.push(5);");
   443                     break;
   444                 case bc_ldc: {
   445                     int indx = readByte(byteCodes, ++i);
   446                     CPEntry entry = jc.getConstantPool().get(indx);
   447                     String v = encodeConstant(entry);
   448                     out.append("stack.push(").append(v).append(");");
   449                     break;
   450                 }
   451                 case bc_ldc_w:
   452                 case bc_ldc2_w: {
   453                     int indx = readIntArg(byteCodes, i);
   454                     CPEntry entry = jc.getConstantPool().get(indx);
   455                     i += 2;
   456                     String v = encodeConstant(entry);
   457                     out.append("stack.push(").append(v).append(");");
   458                     break;
   459                 }
   460                 case bc_lcmp:
   461                 case bc_fcmpl:
   462                 case bc_fcmpg:
   463                 case bc_dcmpl:
   464                 case bc_dcmpg: {
   465                     out.append("{ var delta = stack.pop() - stack.pop(); stack.push(delta < 0 ?-1 : (delta == 0 ? 0 : 1)); }");
   466                     break;
   467                 }
   468                 case bc_if_acmpeq:
   469                     i = generateIf(byteCodes, i, "===");
   470                     break;
   471                 case bc_if_acmpne:
   472                     i = generateIf(byteCodes, i, "!=");
   473                     break;
   474                 case bc_if_icmpeq: {
   475                     i = generateIf(byteCodes, i, "==");
   476                     break;
   477                 }
   478                 case bc_ifeq: {
   479                     int indx = i + readIntArg(byteCodes, i);
   480                     out.append("if (stack.pop() == 0) { gt = " + indx);
   481                     out.append("; continue; }");
   482                     i += 2;
   483                     break;
   484                 }
   485                 case bc_ifne: {
   486                     int indx = i + readIntArg(byteCodes, i);
   487                     out.append("if (stack.pop() != 0) { gt = " + indx);
   488                     out.append("; continue; }");
   489                     i += 2;
   490                     break;
   491                 }
   492                 case bc_iflt: {
   493                     int indx = i + readIntArg(byteCodes, i);
   494                     out.append("if (stack.pop() < 0) { gt = " + indx);
   495                     out.append("; continue; }");
   496                     i += 2;
   497                     break;
   498                 }
   499                 case bc_ifle: {
   500                     int indx = i + readIntArg(byteCodes, i);
   501                     out.append("if (stack.pop() <= 0) { gt = " + indx);
   502                     out.append("; continue; }");
   503                     i += 2;
   504                     break;
   505                 }
   506                 case bc_ifgt: {
   507                     int indx = i + readIntArg(byteCodes, i);
   508                     out.append("if (stack.pop() > 0) { gt = " + indx);
   509                     out.append("; continue; }");
   510                     i += 2;
   511                     break;
   512                 }
   513                 case bc_ifge: {
   514                     int indx = i + readIntArg(byteCodes, i);
   515                     out.append("if (stack.pop() >= 0) { gt = " + indx);
   516                     out.append("; continue; }");
   517                     i += 2;
   518                     break;
   519                 }
   520                 case bc_ifnonnull: {
   521                     int indx = i + readIntArg(byteCodes, i);
   522                     out.append("if (stack.pop()) { gt = " + indx);
   523                     out.append("; continue; }");
   524                     i += 2;
   525                     break;
   526                 }
   527                 case bc_ifnull: {
   528                     int indx = i + readIntArg(byteCodes, i);
   529                     out.append("if (!stack.pop()) { gt = " + indx);
   530                     out.append("; continue; }");
   531                     i += 2;
   532                     break;
   533                 }
   534                 case bc_if_icmpne:
   535                     i = generateIf(byteCodes, i, "!=");
   536                     break;
   537                 case bc_if_icmplt:
   538                     i = generateIf(byteCodes, i, ">");
   539                     break;
   540                 case bc_if_icmple:
   541                     i = generateIf(byteCodes, i, ">=");
   542                     break;
   543                 case bc_if_icmpgt:
   544                     i = generateIf(byteCodes, i, "<");
   545                     break;
   546                 case bc_if_icmpge:
   547                     i = generateIf(byteCodes, i, "<=");
   548                     break;
   549                 case bc_goto: {
   550                     int indx = i + readIntArg(byteCodes, i);
   551                     out.append("gt = " + indx).append("; continue;");
   552                     i += 2;
   553                     break;
   554                 }
   555                 case bc_lookupswitch: {
   556                     int table = i / 4 * 4 + 4;
   557                     int dflt = i + readInt4(byteCodes, table);
   558                     table += 4;
   559                     int n = readInt4(byteCodes, table);
   560                     table += 4;
   561                     out.append("switch (stack.pop()) {\n");
   562                     while (n-- > 0) {
   563                         int cnstnt = readInt4(byteCodes, table);
   564                         table += 4;
   565                         int offset = i + readInt4(byteCodes, table);
   566                         table += 4;
   567                         out.append("  case " + cnstnt).append(": gt = " + offset).append("; continue;\n");
   568                     }
   569                     out.append("  default: gt = " + dflt).append("; continue;\n}");
   570                     i = table - 1;
   571                     break;
   572                 }
   573                 case bc_tableswitch: {
   574                     int table = i / 4 * 4 + 4;
   575                     int dflt = i + readInt4(byteCodes, table);
   576                     table += 4;
   577                     int low = readInt4(byteCodes, table);
   578                     table += 4;
   579                     int high = readInt4(byteCodes, table);
   580                     table += 4;
   581                     out.append("switch (stack.pop()) {\n");
   582                     while (low <= high) {
   583                         int offset = i + readInt4(byteCodes, table);
   584                         table += 4;
   585                         out.append("  case " + low).append(": gt = " + offset).append("; continue;\n");
   586                         low++;
   587                     }
   588                     out.append("  default: gt = " + dflt).append("; continue;\n}");
   589                     i = table - 1;
   590                     break;
   591                 }
   592                 case bc_invokeinterface: {
   593                     i = invokeVirtualMethod(byteCodes, i) + 2;
   594                     break;
   595                 }
   596                 case bc_invokevirtual:
   597                     i = invokeVirtualMethod(byteCodes, i);
   598                     break;
   599                 case bc_invokespecial:
   600                     i = invokeStaticMethod(byteCodes, i, false);
   601                     break;
   602                 case bc_invokestatic:
   603                     i = invokeStaticMethod(byteCodes, i, true);
   604                     break;
   605                 case bc_new: {
   606                     int indx = readIntArg(byteCodes, i);
   607                     CPClassInfo ci = jc.getConstantPool().getClass(indx);
   608                     out.append("stack.push(");
   609                     out.append("new ").append(ci.getClassName().getInternalName().replace('/','_'));
   610                     out.append(");");
   611                     addReference(ci.getClassName().getInternalName());
   612                     i += 2;
   613                     break;
   614                 }
   615                 case bc_newarray: {
   616                     int type = byteCodes[i++];
   617                     out.append("stack.push(new Array(stack.pop()));");
   618                     break;
   619                 }
   620                 case bc_anewarray: {
   621                     i += 2; // skip type of array
   622                     out.append("stack.push(new Array(stack.pop()));");
   623                     break;
   624                 }
   625                 case bc_multianewarray: {
   626                     i += 2;
   627                     int dim = readByte(byteCodes, ++i);
   628                     out.append("{ var a0 = new Array(stack.pop());");
   629                     for (int d = 1; d < dim; d++) {
   630                         out.append("\n  var l" + d).append(" = stack.pop();");
   631                         out.append("\n  for (var i" + d).append (" = 0; i" + d).
   632                             append(" < a" + (d - 1)).
   633                             append(".length; i" + d).append("++) {");
   634                         out.append("\n    var a" + d).
   635                             append (" = new Array(l" + d).append(");");
   636                         out.append("\n    a" + (d - 1)).append("[i" + d).append("] = a" + d).
   637                             append(";");
   638                     }
   639                     for (int d = 1; d < dim; d++) {
   640                         out.append("\n  }");
   641                     }
   642                     out.append("\nstack.push(a0); }");
   643                     break;
   644                 }
   645                 case bc_arraylength:
   646                     out.append("stack.push(stack.pop().length);");
   647                     break;
   648                 case bc_iastore:
   649                 case bc_lastore:
   650                 case bc_fastore:
   651                 case bc_dastore:
   652                 case bc_aastore:
   653                 case bc_bastore:
   654                 case bc_castore:
   655                 case bc_sastore: {
   656                     out.append("{ var value = stack.pop(); var indx = stack.pop(); stack.pop()[indx] = value; }");
   657                     break;
   658                 }
   659                 case bc_iaload:
   660                 case bc_laload:
   661                 case bc_faload:
   662                 case bc_daload:
   663                 case bc_aaload:
   664                 case bc_baload:
   665                 case bc_caload:
   666                 case bc_saload: {
   667                     out.append("{ var indx = stack.pop(); stack.push(stack.pop()[indx]); }");
   668                     break;
   669                 }
   670                 case bc_pop2:
   671                     out.append("stack.pop();");
   672                 case bc_pop:
   673                     out.append("stack.pop();");
   674                     break;
   675                 case bc_dup:
   676                     out.append("stack.push(stack[stack.length - 1]);");
   677                     break;
   678                 case bc_bipush:
   679                     out.append("stack.push(" + byteCodes[++i] + ");");
   680                     break;
   681                 case bc_sipush:
   682                     out.append("stack.push(" + readIntArg(byteCodes, i) + ");");
   683                     i += 2;
   684                     break;
   685                 case bc_getfield: {
   686                     int indx = readIntArg(byteCodes, i);
   687                     CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
   688                     out.append("stack.push(stack.pop().").append(fi.getFieldName()).append(");");
   689                     i += 2;
   690                     break;
   691                 }
   692                 case bc_getstatic: {
   693                     int indx = readIntArg(byteCodes, i);
   694                     CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
   695                     final String in = fi.getClassName().getInternalName();
   696                     out.append("stack.push(").append(in.replace('/', '_'));
   697                     out.append('_').append(fi.getFieldName()).append(");");
   698                     i += 2;
   699                     addReference(in);
   700                     break;
   701                 }
   702                 case bc_putstatic: {
   703                     int indx = readIntArg(byteCodes, i);
   704                     CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
   705                     final String in = fi.getClassName().getInternalName();
   706                     out.append(in.replace('/', '_'));
   707                     out.append('_').append(fi.getFieldName()).append(" = stack.pop();");
   708                     i += 2;
   709                     addReference(in);
   710                     break;
   711                 }
   712                 case bc_putfield: {
   713                     int indx = readIntArg(byteCodes, i);
   714                     CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
   715                     out.append("{ var v = stack.pop(); stack.pop().")
   716                        .append(fi.getFieldName()).append(" = v; }");
   717                     i += 2;
   718                     break;
   719                 }
   720                 case bc_checkcast: {
   721                     int indx = readIntArg(byteCodes, i);
   722                     CPClassInfo ci = jc.getConstantPool().getClass(indx);
   723                     final String type = ci.getClassName().getType();
   724                     if (!type.startsWith("[")) {
   725                         // no way to check arrays right now
   726                         out.append("if(stack[stack.length - 1].$instOf_")
   727                            .append(type.replace('/', '_'))
   728                            .append(" != 1) throw {};"); // XXX proper exception
   729                     }
   730                     i += 2;
   731                     break;
   732                 }
   733                 case bc_instanceof: {
   734                     int indx = readIntArg(byteCodes, i);
   735                     CPClassInfo ci = jc.getConstantPool().getClass(indx);
   736                     out.append("stack.push(stack.pop().$instOf_")
   737                        .append(ci.getClassName().getInternalName().replace('/', '_'))
   738                        .append(" ? 1 : 0);");
   739                     i += 2;
   740                     break;
   741                 }
   742                 case bc_athrow: {
   743                     out.append("{ var t = stack.pop(); stack = new Array(1); stack[0] = t; throw t; }");
   744                     break;
   745                 }
   746                 default: {
   747                     out.append("throw 'unknown bytecode " + c + "';");
   748                 }
   749                     
   750             }
   751             out.append(" //");
   752             for (int j = prev; j <= i; j++) {
   753                 out.append(" ");
   754                 final int cc = readByte(byteCodes, j);
   755                 out.append(Integer.toString(cc));
   756             }
   757             out.append("\n");
   758         }
   759         out.append("  }\n");
   760     }
   761 
   762     private int generateIf(byte[] byteCodes, int i, final String test) throws IOException {
   763         int indx = i + readIntArg(byteCodes, i);
   764         out.append("if (stack.pop() ").append(test).append(" stack.pop()) { gt = " + indx);
   765         out.append("; continue; }");
   766         return i + 2;
   767     }
   768 
   769     private int readIntArg(byte[] byteCodes, int offsetInstruction) {
   770         final int indxHi = byteCodes[offsetInstruction + 1] << 8;
   771         final int indxLo = byteCodes[offsetInstruction + 2];
   772         return (indxHi & 0xffffff00) | (indxLo & 0xff);
   773     }
   774     private int readInt4(byte[] byteCodes, int offsetInstruction) {
   775         final int d = byteCodes[offsetInstruction + 0] << 24;
   776         final int c = byteCodes[offsetInstruction + 1] << 16;
   777         final int b = byteCodes[offsetInstruction + 2] << 8;
   778         final int a = byteCodes[offsetInstruction + 3];
   779         return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
   780     }
   781     private int readByte(byte[] byteCodes, int offsetInstruction) {
   782         return (byteCodes[offsetInstruction] + 256) % 256;
   783     }
   784     
   785     private static int countArgs(String descriptor, boolean[] hasReturnType, StringBuilder sig) {
   786         int cnt = 0;
   787         int i = 0;
   788         Boolean count = null;
   789         boolean array = false;
   790         int firstPos = sig.length();
   791         while (i < descriptor.length()) {
   792             char ch = descriptor.charAt(i++);
   793             switch (ch) {
   794                 case '(':
   795                     count = true;
   796                     continue;
   797                 case ')':
   798                     count = false;
   799                     continue;
   800                 case 'A':
   801                     array = true;
   802                     break;
   803                 case 'B': 
   804                 case 'C': 
   805                 case 'D': 
   806                 case 'F': 
   807                 case 'I': 
   808                 case 'J': 
   809                 case 'S': 
   810                 case 'Z': 
   811                     if (count) {
   812                         cnt++;
   813                         if (array) {
   814                             sig.append('A');
   815                         }
   816                         sig.append(ch);
   817                     } else {
   818                         hasReturnType[0] = true;
   819                         sig.insert(firstPos, ch);
   820                         if (array) {
   821                             sig.insert(firstPos, 'A');
   822                         }
   823                     }
   824                     array = false;
   825                     continue;
   826                 case 'V': 
   827                     assert !count;
   828                     hasReturnType[0] = false;
   829                     sig.insert(firstPos, 'V');
   830                     continue;
   831                 case 'L':
   832                     int next = descriptor.indexOf(';', i);
   833                     if (count) {
   834                         cnt++;
   835                         if (array) {
   836                             sig.append('A');
   837                         }
   838                         sig.append(ch);
   839                         sig.append(descriptor.substring(i, next).replace('/', '_'));
   840                     } else {
   841                         sig.insert(firstPos, descriptor.substring(i, next).replace('/', '_'));
   842                         sig.insert(firstPos, ch);
   843                         if (array) {
   844                             sig.insert(firstPos, 'A');
   845                         }
   846                         hasReturnType[0] = true;
   847                     }
   848                     i = next + 1;
   849                     continue;
   850                 case '[':
   851                     //arrays++;
   852                     continue;
   853                 default:
   854                     break; // invalid character
   855             }
   856         }
   857         return cnt;
   858     }
   859 
   860     private void generateStaticField(Variable v) throws IOException {
   861         out.append("\nvar ")
   862            .append(jc.getName().getInternalName().replace('/', '_'))
   863            .append('_').append(v.getName()).append(" = 0;");
   864     }
   865 
   866     private String findMethodName(Method m) {
   867         StringBuilder name = new StringBuilder();
   868         String descr = m.getDescriptor();
   869         if ("<init>".equals(m.getName())) { // NOI18N
   870             name.append("cons"); // NOI18N
   871         } else if ("<clinit>".equals(m.getName())) { // NOI18N
   872             name.append("class"); // NOI18N
   873         } else {
   874             name.append(m.getName());
   875         } 
   876         
   877         boolean hasReturn[] = { false };
   878         countArgs(findDescriptor(m.getDescriptor()), hasReturn, name);
   879         return name.toString();
   880     }
   881 
   882     private String findMethodName(CPMethodInfo mi, int[] cnt, boolean[] hasReturn) {
   883         StringBuilder name = new StringBuilder();
   884         String descr = mi.getDescriptor();
   885         if ("<init>".equals(mi.getName())) { // NOI18N
   886             name.append("cons"); // NOI18N
   887         } else {
   888             name.append(mi.getName());
   889         }
   890         cnt[0] = countArgs(findDescriptor(mi.getDescriptor()), hasReturn, name);
   891         return name.toString();
   892     }
   893 
   894     private int invokeStaticMethod(byte[] byteCodes, int i, boolean isStatic)
   895     throws IOException {
   896         int methodIndex = readIntArg(byteCodes, i);
   897         CPMethodInfo mi = (CPMethodInfo) jc.getConstantPool().get(methodIndex);
   898         boolean[] hasReturn = { false };
   899         int[] cnt = { 0 };
   900         String mn = findMethodName(mi, cnt, hasReturn);
   901         out.append("{ ");
   902         for (int j = cnt[0] - 1; j >= 0; j--) {
   903             out.append("var v" + j).append(" = stack.pop(); ");
   904         }
   905         
   906         if (hasReturn[0]) {
   907             out.append("stack.push(");
   908         }
   909         final String in = mi.getClassName().getInternalName();
   910         out.append(in.replace('/', '_'));
   911         if (isStatic) {
   912             out.append(".prototype.");
   913         } else {
   914             out.append('_');
   915         }
   916         out.append(mn);
   917         out.append('(');
   918         String sep = "";
   919         if (!isStatic) {
   920             out.append("stack.pop()");
   921             sep = ", ";
   922         }
   923         for (int j = 0; j < cnt[0]; j++) {
   924             out.append(sep);
   925             out.append("v" + j);
   926             sep = ", ";
   927         }
   928         out.append(")");
   929         if (hasReturn[0]) {
   930             out.append(")");
   931         }
   932         out.append("; }");
   933         i += 2;
   934         addReference(in);
   935         return i;
   936     }
   937     private int invokeVirtualMethod(byte[] byteCodes, int i)
   938     throws IOException {
   939         int methodIndex = readIntArg(byteCodes, i);
   940         CPMethodInfo mi = (CPMethodInfo) jc.getConstantPool().get(methodIndex);
   941         boolean[] hasReturn = { false };
   942         int[] cnt = { 0 };
   943         String mn = findMethodName(mi, cnt, hasReturn);
   944         out.append("{ ");
   945         for (int j = cnt[0] - 1; j >= 0; j--) {
   946             out.append("var v" + j).append(" = stack.pop(); ");
   947         }
   948         out.append("var self = stack.pop(); ");
   949         if (hasReturn[0]) {
   950             out.append("stack.push(");
   951         }
   952         out.append("self.");
   953         out.append(mn);
   954         out.append('(');
   955         out.append("self");
   956         for (int j = 0; j < cnt[0]; j++) {
   957             out.append(", ");
   958             out.append("v" + j);
   959         }
   960         out.append(")");
   961         if (hasReturn[0]) {
   962             out.append(")");
   963         }
   964         out.append("; }");
   965         i += 2;
   966         return i;
   967     }
   968     
   969     private void addReference(String cn) throws IOException {
   970         if (references != null) {
   971             if (references.add(cn)) {
   972                 out.append(" /* needs ").append(cn).append(" */");
   973             }
   974         }
   975     }
   976 
   977     private void outType(String d, StringBuilder out) {
   978         int arr = 0;
   979         while (d.charAt(0) == '[') {
   980             out.append('A');
   981             d = d.substring(1);
   982         }
   983         if (d.charAt(0) == 'L') {
   984             assert d.charAt(d.length() - 1) == ';';
   985             out.append(d.replace('/', '_').substring(0, d.length() - 1));
   986         } else {
   987             out.append(d);
   988         }
   989     }
   990 
   991     private String encodeConstant(CPEntry entry) {
   992         final String v;
   993         if (entry instanceof CPClassInfo) {
   994             v = "new java_lang_Class";
   995         } else if (entry instanceof CPStringInfo) {
   996             v = "\"" + entry.getValue().toString().replace("\"", "\\\"") + "\"";
   997         } else {
   998             v = entry.getValue().toString();
   999         }
  1000         return v;
  1001     }
  1002 
  1003     private String findDescriptor(String d) {
  1004         return d.replace('[', 'A');
  1005     }
  1006 
  1007     private boolean javaScriptBody(Method m, boolean isStatic) throws IOException {
  1008         final ClassName extraAnn = ClassName.getClassName(JavaScriptBody.class.getName().replace('.', '/'));
  1009         Annotation a = m.getAnnotation(extraAnn);
  1010         if (a != null) {
  1011             final ElementValue annVal = a.getComponent("body").getValue();
  1012             String body = ((PrimitiveElementValue) annVal).getValue().getValue().toString();
  1013             
  1014             final ArrayElementValue arrVal = (ArrayElementValue) a.getComponent("args").getValue();
  1015             final int len = arrVal.getValues().length;
  1016             String[] names = new String[len];
  1017             for (int i = 0; i < len; i++) {
  1018                 names[i] = ((PrimitiveElementValue) arrVal.getValues()[i]).getValue().getValue().toString();
  1019             }
  1020             out.append("\nfunction ").append(
  1021                 jc.getName().getInternalName().replace('/', '_')).append('_').append(findMethodName(m));
  1022             out.append("(");
  1023             String space;
  1024             int index;
  1025             if (!isStatic) {                
  1026                 out.append(names[0]);
  1027                 space = ",";
  1028                 index = 1;
  1029             } else {
  1030                 space = "";
  1031                 index = 0;
  1032             }
  1033             List<Parameter> args = m.getParameters();
  1034             for (int i = 0; i < args.size(); i++) {
  1035                 out.append(space);
  1036                 out.append(names[index]);
  1037                 final String desc = findDescriptor(args.get(i).getDescriptor());
  1038                 index++;
  1039                 space = ",";
  1040             }
  1041             out.append(") {").append("\n");
  1042             out.append(body);
  1043             out.append("\n}\n");
  1044             return true;
  1045         }
  1046         return false;
  1047     }
  1048 }