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