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