vm/src/main/java/org/apidesign/vm4brwsr/ByteCodeToJavaScript.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Tue, 16 Oct 2012 12:42:00 +0200
changeset 106 346633cd13d6
parent 104 1376481f15e7
child 115 3d5597011af0
child 285 c8be2d837788
permissions -rw-r--r--
Fixing license in all files
     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_invokeinterface: {
   573                     i = invokeVirtualMethod(byteCodes, i) + 2;
   574                     break;
   575                 }
   576                 case bc_invokevirtual:
   577                     i = invokeVirtualMethod(byteCodes, i);
   578                     break;
   579                 case bc_invokespecial:
   580                     i = invokeStaticMethod(byteCodes, i, false);
   581                     break;
   582                 case bc_invokestatic:
   583                     i = invokeStaticMethod(byteCodes, i, true);
   584                     break;
   585                 case bc_new: {
   586                     int indx = readIntArg(byteCodes, i);
   587                     CPClassInfo ci = jc.getConstantPool().getClass(indx);
   588                     out.append("stack.push(");
   589                     out.append("new ").append(ci.getClassName().getInternalName().replace('/','_'));
   590                     out.append(");");
   591                     addReference(ci.getClassName().getInternalName());
   592                     i += 2;
   593                     break;
   594                 }
   595                 case bc_newarray: {
   596                     int type = byteCodes[i++];
   597                     out.append("stack.push(new Array(stack.pop()));");
   598                     break;
   599                 }
   600                 case bc_anewarray: {
   601                     i += 2; // skip type of array
   602                     out.append("stack.push(new Array(stack.pop()));");
   603                     break;
   604                 }
   605                 case bc_arraylength:
   606                     out.append("stack.push(stack.pop().length);");
   607                     break;
   608                 case bc_iastore:
   609                 case bc_lastore:
   610                 case bc_fastore:
   611                 case bc_dastore:
   612                 case bc_aastore:
   613                 case bc_bastore:
   614                 case bc_castore:
   615                 case bc_sastore: {
   616                     out.append("{ var value = stack.pop(); var indx = stack.pop(); stack.pop()[indx] = value; }");
   617                     break;
   618                 }
   619                 case bc_iaload:
   620                 case bc_laload:
   621                 case bc_faload:
   622                 case bc_daload:
   623                 case bc_aaload:
   624                 case bc_baload:
   625                 case bc_caload:
   626                 case bc_saload: {
   627                     out.append("{ var indx = stack.pop(); stack.push(stack.pop()[indx]); }");
   628                     break;
   629                 }
   630                 case bc_pop2:
   631                     out.append("stack.pop();");
   632                 case bc_pop:
   633                     out.append("stack.pop();");
   634                     break;
   635                 case bc_dup:
   636                     out.append("stack.push(stack[stack.length - 1]);");
   637                     break;
   638                 case bc_bipush:
   639                     out.append("stack.push(" + byteCodes[++i] + ");");
   640                     break;
   641                 case bc_sipush:
   642                     out.append("stack.push(" + readIntArg(byteCodes, i) + ");");
   643                     i += 2;
   644                     break;
   645                 case bc_getfield: {
   646                     int indx = readIntArg(byteCodes, i);
   647                     CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
   648                     out.append("stack.push(stack.pop().").append(fi.getFieldName()).append(");");
   649                     i += 2;
   650                     break;
   651                 }
   652                 case bc_getstatic: {
   653                     int indx = readIntArg(byteCodes, i);
   654                     CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
   655                     final String in = fi.getClassName().getInternalName();
   656                     out.append("stack.push(").append(in.replace('/', '_'));
   657                     out.append('_').append(fi.getFieldName()).append(");");
   658                     i += 2;
   659                     addReference(in);
   660                     break;
   661                 }
   662                 case bc_putstatic: {
   663                     int indx = readIntArg(byteCodes, i);
   664                     CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
   665                     final String in = fi.getClassName().getInternalName();
   666                     out.append(in.replace('/', '_'));
   667                     out.append('_').append(fi.getFieldName()).append(" = stack.pop();");
   668                     i += 2;
   669                     addReference(in);
   670                     break;
   671                 }
   672                 case bc_putfield: {
   673                     int indx = readIntArg(byteCodes, i);
   674                     CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
   675                     out.append("{ var v = stack.pop(); stack.pop().")
   676                        .append(fi.getFieldName()).append(" = v; }");
   677                     i += 2;
   678                     break;
   679                 }
   680                 case bc_checkcast: {
   681                     int indx = readIntArg(byteCodes, i);
   682                     CPClassInfo ci = jc.getConstantPool().getClass(indx);
   683                     final String type = ci.getClassName().getType();
   684                     if (!type.startsWith("[")) {
   685                         // no way to check arrays right now
   686                         out.append("if(stack[stack.length - 1].$instOf_")
   687                            .append(type.replace('/', '_'))
   688                            .append(" != 1) throw {};"); // XXX proper exception
   689                     }
   690                     i += 2;
   691                     break;
   692                 }
   693                 case bc_instanceof: {
   694                     int indx = readIntArg(byteCodes, i);
   695                     CPClassInfo ci = jc.getConstantPool().getClass(indx);
   696                     out.append("stack.push(stack.pop().$instOf_")
   697                        .append(ci.getClassName().getInternalName().replace('/', '_'))
   698                        .append(" ? 1 : 0);");
   699                     i += 2;
   700                     break;
   701                 }
   702                 case bc_athrow: {
   703                     out.append("{ var t = stack.pop(); stack = new Array(1); stack[0] = t; throw t; }");
   704                     break;
   705                 }
   706                 default: {
   707                     out.append("throw 'unknown bytecode " + c + "';");
   708                 }
   709                     
   710             }
   711             out.append(" //");
   712             for (int j = prev; j <= i; j++) {
   713                 out.append(" ");
   714                 final int cc = (byteCodes[j] + 256) % 256;
   715                 out.append(Integer.toString(cc));
   716             }
   717             out.append("\n");
   718         }
   719         out.append("  }\n");
   720     }
   721 
   722     private int generateIf(byte[] byteCodes, int i, final String test) throws IOException {
   723         int indx = i + readIntArg(byteCodes, i);
   724         out.append("if (stack.pop() ").append(test).append(" stack.pop()) { gt = " + indx);
   725         out.append("; continue; }");
   726         return i + 2;
   727     }
   728 
   729     private int readIntArg(byte[] byteCodes, int offsetInstruction) {
   730         final int indxHi = byteCodes[offsetInstruction + 1] << 8;
   731         final int indxLo = byteCodes[offsetInstruction + 2];
   732         return (indxHi & 0xffffff00) | (indxLo & 0xff);
   733     }
   734     
   735     private static int countArgs(String descriptor, boolean[] hasReturnType, StringBuilder sig) {
   736         int cnt = 0;
   737         int i = 0;
   738         Boolean count = null;
   739         boolean array = false;
   740         int firstPos = sig.length();
   741         while (i < descriptor.length()) {
   742             char ch = descriptor.charAt(i++);
   743             switch (ch) {
   744                 case '(':
   745                     count = true;
   746                     continue;
   747                 case ')':
   748                     count = false;
   749                     continue;
   750                 case 'A':
   751                     array = true;
   752                     break;
   753                 case 'B': 
   754                 case 'C': 
   755                 case 'D': 
   756                 case 'F': 
   757                 case 'I': 
   758                 case 'J': 
   759                 case 'S': 
   760                 case 'Z': 
   761                     if (count) {
   762                         cnt++;
   763                         if (array) {
   764                             sig.append('A');
   765                         }
   766                         sig.append(ch);
   767                     } else {
   768                         hasReturnType[0] = true;
   769                         sig.insert(firstPos, ch);
   770                         if (array) {
   771                             sig.insert(firstPos, 'A');
   772                         }
   773                     }
   774                     array = false;
   775                     continue;
   776                 case 'V': 
   777                     assert !count;
   778                     hasReturnType[0] = false;
   779                     sig.insert(firstPos, 'V');
   780                     continue;
   781                 case 'L':
   782                     int next = descriptor.indexOf(';', i);
   783                     if (count) {
   784                         cnt++;
   785                         if (array) {
   786                             sig.append('A');
   787                         }
   788                         sig.append(ch);
   789                         sig.append(descriptor.substring(i, next).replace('/', '_'));
   790                     } else {
   791                         sig.insert(firstPos, descriptor.substring(i, next).replace('/', '_'));
   792                         sig.insert(firstPos, ch);
   793                         if (array) {
   794                             sig.insert(firstPos, 'A');
   795                         }
   796                         hasReturnType[0] = true;
   797                     }
   798                     i = next + 1;
   799                     continue;
   800                 case '[':
   801                     //arrays++;
   802                     continue;
   803                 default:
   804                     break; // invalid character
   805             }
   806         }
   807         return cnt;
   808     }
   809 
   810     private void generateStaticField(Variable v) throws IOException {
   811         out.append("\nvar ")
   812            .append(jc.getName().getInternalName().replace('/', '_'))
   813            .append('_').append(v.getName()).append(" = 0;");
   814     }
   815 
   816     private String findMethodName(Method m) {
   817         StringBuilder name = new StringBuilder();
   818         String descr = m.getDescriptor();
   819         if ("<init>".equals(m.getName())) { // NOI18N
   820             name.append("cons"); // NOI18N
   821         } else if ("<clinit>".equals(m.getName())) { // NOI18N
   822             name.append("class"); // NOI18N
   823         } else {
   824             name.append(m.getName());
   825         } 
   826         
   827         boolean hasReturn[] = { false };
   828         countArgs(findDescriptor(m.getDescriptor()), hasReturn, name);
   829         return name.toString();
   830     }
   831 
   832     private String findMethodName(CPMethodInfo mi, int[] cnt, boolean[] hasReturn) {
   833         StringBuilder name = new StringBuilder();
   834         String descr = mi.getDescriptor();
   835         if ("<init>".equals(mi.getName())) { // NOI18N
   836             name.append("cons"); // NOI18N
   837         } else {
   838             name.append(mi.getName());
   839         }
   840         cnt[0] = countArgs(findDescriptor(mi.getDescriptor()), hasReturn, name);
   841         return name.toString();
   842     }
   843 
   844     private int invokeStaticMethod(byte[] byteCodes, int i, boolean isStatic)
   845     throws IOException {
   846         int methodIndex = readIntArg(byteCodes, i);
   847         CPMethodInfo mi = (CPMethodInfo) jc.getConstantPool().get(methodIndex);
   848         boolean[] hasReturn = { false };
   849         int[] cnt = { 0 };
   850         String mn = findMethodName(mi, cnt, hasReturn);
   851         out.append("{ ");
   852         for (int j = cnt[0] - 1; j >= 0; j--) {
   853             out.append("var v" + j).append(" = stack.pop(); ");
   854         }
   855         
   856         if (hasReturn[0]) {
   857             out.append("stack.push(");
   858         }
   859         final String in = mi.getClassName().getInternalName();
   860         out.append(in.replace('/', '_'));
   861         if (isStatic) {
   862             out.append(".prototype.");
   863         } else {
   864             out.append('_');
   865         }
   866         out.append(mn);
   867         out.append('(');
   868         String sep = "";
   869         if (!isStatic) {
   870             out.append("stack.pop()");
   871             sep = ", ";
   872         }
   873         for (int j = 0; j < cnt[0]; j++) {
   874             out.append(sep);
   875             out.append("v" + j);
   876             sep = ", ";
   877         }
   878         out.append(")");
   879         if (hasReturn[0]) {
   880             out.append(")");
   881         }
   882         out.append("; }");
   883         i += 2;
   884         addReference(in);
   885         return i;
   886     }
   887     private int invokeVirtualMethod(byte[] byteCodes, int i)
   888     throws IOException {
   889         int methodIndex = readIntArg(byteCodes, i);
   890         CPMethodInfo mi = (CPMethodInfo) jc.getConstantPool().get(methodIndex);
   891         boolean[] hasReturn = { false };
   892         int[] cnt = { 0 };
   893         String mn = findMethodName(mi, cnt, hasReturn);
   894         out.append("{ ");
   895         for (int j = cnt[0] - 1; j >= 0; j--) {
   896             out.append("var v" + j).append(" = stack.pop(); ");
   897         }
   898         out.append("var self = stack.pop(); ");
   899         if (hasReturn[0]) {
   900             out.append("stack.push(");
   901         }
   902         out.append("self.");
   903         out.append(mn);
   904         out.append('(');
   905         out.append("self");
   906         for (int j = 0; j < cnt[0]; j++) {
   907             out.append(", ");
   908             out.append("v" + j);
   909         }
   910         out.append(")");
   911         if (hasReturn[0]) {
   912             out.append(")");
   913         }
   914         out.append("; }");
   915         i += 2;
   916         return i;
   917     }
   918     
   919     private void addReference(String cn) throws IOException {
   920         out.append(" /* needs ").append(cn).append(" */");
   921         if (references != null) {
   922             references.add(cn);
   923         }
   924     }
   925 
   926     private void outType(String d, StringBuilder out) {
   927         int arr = 0;
   928         while (d.charAt(0) == '[') {
   929             out.append('A');
   930             d = d.substring(1);
   931         }
   932         if (d.charAt(0) == 'L') {
   933             assert d.charAt(d.length() - 1) == ';';
   934             out.append(d.replace('/', '_').substring(0, d.length() - 1));
   935         } else {
   936             out.append(d);
   937         }
   938     }
   939 
   940     private String encodeConstant(CPEntry entry) {
   941         final String v;
   942         if (entry instanceof CPClassInfo) {
   943             v = "new java_lang_Class";
   944         } else if (entry instanceof CPStringInfo) {
   945             v = "\"" + entry.getValue().toString().replace("\"", "\\\"") + "\"";
   946         } else {
   947             v = entry.getValue().toString();
   948         }
   949         return v;
   950     }
   951 
   952     private String findDescriptor(String d) {
   953         return d.replace('[', 'A');
   954     }
   955 
   956     private boolean javaScriptBody(Method m, boolean isStatic) throws IOException {
   957         final ClassName extraAnn = ClassName.getClassName(JavaScriptBody.class.getName().replace('.', '/'));
   958         Annotation a = m.getAnnotation(extraAnn);
   959         if (a != null) {
   960             final ElementValue annVal = a.getComponent("body").getValue();
   961             String body = ((PrimitiveElementValue) annVal).getValue().getValue().toString();
   962             
   963             final ArrayElementValue arrVal = (ArrayElementValue) a.getComponent("args").getValue();
   964             final int len = arrVal.getValues().length;
   965             String[] names = new String[len];
   966             for (int i = 0; i < len; i++) {
   967                 names[i] = ((PrimitiveElementValue) arrVal.getValues()[i]).getValue().getValue().toString();
   968             }
   969             out.append("\nfunction ").append(
   970                 jc.getName().getInternalName().replace('/', '_')).append('_').append(findMethodName(m));
   971             out.append("(");
   972             String space;
   973             int index;
   974             if (!isStatic) {                
   975                 out.append(names[0]);
   976                 space = ",";
   977                 index = 1;
   978             } else {
   979                 space = "";
   980                 index = 0;
   981             }
   982             List<Parameter> args = m.getParameters();
   983             for (int i = 0; i < args.size(); i++) {
   984                 out.append(space);
   985                 out.append(names[index]);
   986                 final String desc = findDescriptor(args.get(i).getDescriptor());
   987                 index++;
   988                 space = ",";
   989             }
   990             out.append(") {").append("\n");
   991             out.append(body);
   992             out.append("\n}\n");
   993             return true;
   994         }
   995         return false;
   996     }
   997 }