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