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