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