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