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