vm/src/main/java/org/apidesign/vm4brwsr/ByteCodeToJavaScript.java
author Jaroslav Tulach <jtulach@netbeans.org>
Fri, 16 Nov 2012 07:36:32 +0100
branchjavap
changeset 162 70e7710a65dc
parent 156 3bb1a148a795
child 167 77f7135b6eb1
permissions -rw-r--r--
Eliminating references to java.util classes that have too huge transitive closure.
     1 /**
     2  * Back 2 Browser Bytecode Translator
     3  * Copyright (C) 2012 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
     4  *
     5  * This program is free software: you can redistribute it and/or modify
     6  * it under the terms of the GNU General Public License as published by
     7  * the Free Software Foundation, version 2 of the License.
     8  *
     9  * This program is distributed in the hope that it will be useful,
    10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    12  * GNU General Public License for more details.
    13  *
    14  * You should have received a copy of the GNU General Public License
    15  * along with this program. Look for COPYING file in the top folder.
    16  * If not, see http://opensource.org/licenses/GPL-2.0.
    17  */
    18 package org.apidesign.vm4brwsr;
    19 
    20 import java.io.IOException;
    21 import java.io.InputStream;
    22 import org.apidesign.bck2brwsr.core.ExtraJavaScript;
    23 import org.apidesign.bck2brwsr.core.JavaScriptBody;
    24 import sun.tools.javap.AnnotationParser;
    25 import sun.tools.javap.ClassData;
    26 import sun.tools.javap.FieldData;
    27 import sun.tools.javap.MethodData;
    28 import static sun.tools.javap.RuntimeConstants.*;
    29 
    30 /** Translator of the code inside class files to JavaScript.
    31  *
    32  * @author Jaroslav Tulach <jtulach@netbeans.org>
    33  */
    34 public abstract class ByteCodeToJavaScript {
    35     private ClassData jc;
    36     private final Appendable out;
    37 
    38     protected ByteCodeToJavaScript(Appendable out) {
    39         this.out = out;
    40     }
    41     
    42     /* Collects additional required resources.
    43      * 
    44      * @param internalClassName classes that were referenced and should be loaded in order the
    45      *   generated JavaScript code works properly. The names are in internal 
    46      *   JVM form so String is <code>java/lang/String</code>. 
    47      */
    48     protected abstract boolean requireReference(String internalClassName);
    49     
    50     /*
    51      * @param resourcePath name of resources to read
    52      */
    53     protected abstract void requireScript(String resourcePath);
    54 
    55     /**
    56      * Converts a given class file to a JavaScript version.
    57      *
    58      * @param classFile input stream with code of the .class file
    59      * @return the initialization code for this class, if any. Otherwise <code>null</code>
    60      * 
    61      * @throws IOException if something goes wrong during read or write or translating
    62      */
    63     
    64     public String compile(InputStream classFile) throws IOException {
    65         this.jc = new ClassData(classFile);
    66         byte[] arrData = jc.findAnnotationData(true);
    67         String[] arr = findAnnotation(arrData, jc, ExtraJavaScript.class.getName(), "resource", "processByteCode");
    68         if (arr != null) {
    69             requireScript(arr[0]);
    70             if ("0".equals(arr[1])) {
    71                 return null;
    72             }
    73         }
    74         StringArray toInitilize = new StringArray();
    75         for (MethodData m : jc.getMethods()) {
    76             if (m.isStatic()) {
    77                 generateStaticMethod(m, toInitilize);
    78             } else {
    79                 generateInstanceMethod(m);
    80             }
    81         }
    82         for (FieldData v : jc.getFields()) {
    83             if (v.isStatic()) {
    84                 generateStaticField(v);
    85             }
    86         }
    87         
    88         final String className = className(jc);
    89         out.append("\nfunction ").append(className);
    90         out.append("() {");
    91         for (FieldData v : jc.getFields()) {
    92             if (!v.isStatic()) {
    93                 out.append("\n  this.fld_").
    94                     append(v.getName()).append(" = 0;");
    95             }
    96         }
    97         out.append("\n}\n\nfunction ").append(className).append("_proto() {");
    98         out.append("\n  if (").append(className).
    99             append(".prototype.$instOf_").append(className).append(") {");
   100         out.append("\n    return new ").append(className).append(";");
   101         out.append("\n  }");
   102         // ClassName sc = jc.getSuperClass();
   103         String sc = jc.getSuperClassName(); // with _
   104         if (sc != null) {
   105             out.append("\n  var p = ").append(className)
   106                .append(".prototype = ").
   107                 append(sc.replace('/', '_')).append("_proto();");
   108         } else {
   109             out.append("\n  var p = ").append(className).append(".prototype;");
   110         }
   111         for (MethodData m : jc.getMethods()) {
   112             if (!m.getName().contains("<init>") && !m.getName().contains("<cinit>")) {
   113                 generateMethodReference("\n  p.", m);
   114             }
   115         }
   116         out.append("\n  p.$instOf_").append(className).append(" = true;");
   117         for (String superInterface : jc.getSuperInterfaces()) {
   118             out.append("\n  p.$instOf_").append(superInterface.replace('/', '_')).append(" = true;");
   119         }
   120         out.append("\n  return new ").append(className).append(";");
   121         out.append("\n}");
   122         out.append("\n").append(className).append("_proto();");
   123         StringBuilder sb = new StringBuilder();
   124         for (String init : toInitilize.toArray()) {
   125             sb.append("\n").append(init).append("();");
   126         }
   127         return sb.toString();
   128     }
   129     private void generateStaticMethod(MethodData m, StringArray toInitilize) throws IOException {
   130         if (javaScriptBody(m, true)) {
   131             return;
   132         }
   133         StringBuilder argsCnt = new StringBuilder();
   134         final String mn = findMethodName(m, argsCnt);
   135         out.append("\nfunction ").append(
   136             className(jc)
   137         ).append('_').append(mn);
   138         if (mn.equals("classV")) {
   139             toInitilize.add(className(jc) + '_' + mn);
   140         }
   141         out.append('(');
   142         String space = "";
   143         for (int index = 0, i = 0; i < argsCnt.length(); i++) {
   144             out.append(space);
   145             out.append("arg").append(String.valueOf(index));
   146             space = ",";
   147             final String desc = null;// XXX findDescriptor(args.get(i).getDescriptor());
   148             if (argsCnt.charAt(i) == '1') {
   149                 index += 2;
   150             } else {
   151                 index++;
   152             }
   153         }
   154         out.append(") {").append("\n");
   155         final byte[] code = m.getCode();
   156         if (code != null) {
   157             int len = m.getMaxLocals();
   158             for (int index = argsCnt.length(), i = argsCnt.length(); i < len; i++) {
   159                 out.append("  var ");
   160                 out.append("arg").append(String.valueOf(i)).append(";\n");
   161             }
   162             out.append("  var stack = new Array();\n");
   163             produceCode(code);
   164         } else {
   165             out.append("  /* no code found for ").append(m.getInternalSig()).append(" */\n");
   166         }
   167         out.append("}");
   168     }
   169     
   170     private void generateMethodReference(String prefix, MethodData m) throws IOException {
   171         final String name = findMethodName(m, new StringBuilder());
   172         out.append(prefix).append(name).append(" = ")
   173            .append(className(jc))
   174            .append('_').append(name).append(";");
   175     }
   176     
   177     private void generateInstanceMethod(MethodData m) throws IOException {
   178         if (javaScriptBody(m, false)) {
   179             return;
   180         }
   181         StringBuilder argsCnt = new StringBuilder();
   182         out.append("\nfunction ").append(
   183             className(jc)
   184         ).append('_').append(findMethodName(m, argsCnt));
   185         out.append("(arg0");
   186         String space = ",";
   187         for (int index = 1, i = 0; i < argsCnt.length(); i++) {
   188             out.append(space);
   189             out.append("arg").append(String.valueOf(index));
   190             if (argsCnt.charAt(i) == '1') {
   191                 index += 2;
   192             } else {
   193                 index++;
   194             }
   195         }
   196         out.append(") {").append("\n");
   197         final byte[] code = m.getCode();
   198         if (code != null) {
   199             int len = m.getMaxLocals();
   200             for (int index = argsCnt.length(), i = argsCnt.length(); i < len; i++) {
   201                 out.append("  var ");
   202                 out.append("arg").append(String.valueOf(i + 1)).append(";\n");
   203             }
   204             out.append(";\n  var stack = new Array();\n");
   205             produceCode(code);
   206         } else {
   207             out.append("  /* no code found for ").append(m.getInternalSig()).append(" */\n");
   208         }
   209         out.append("}");
   210     }
   211 
   212     private void produceCode(byte[] byteCodes) throws IOException {
   213         out.append("\n  var gt = 0;\n  for(;;) switch(gt) {\n");
   214         for (int i = 0; i < byteCodes.length; i++) {
   215             int prev = i;
   216             out.append("    case " + i).append(": ");
   217             final int c = readByte(byteCodes, i);
   218             switch (c) {
   219                 case opc_aload_0:
   220                 case opc_iload_0:
   221                 case opc_lload_0:
   222                 case opc_fload_0:
   223                 case opc_dload_0:
   224                     out.append("stack.push(arg0);");
   225                     break;
   226                 case opc_aload_1:
   227                 case opc_iload_1:
   228                 case opc_lload_1:
   229                 case opc_fload_1:
   230                 case opc_dload_1:
   231                     out.append("stack.push(arg1);");
   232                     break;
   233                 case opc_aload_2:
   234                 case opc_iload_2:
   235                 case opc_lload_2:
   236                 case opc_fload_2:
   237                 case opc_dload_2:
   238                     out.append("stack.push(arg2);");
   239                     break;
   240                 case opc_aload_3:
   241                 case opc_iload_3:
   242                 case opc_lload_3:
   243                 case opc_fload_3:
   244                 case opc_dload_3:
   245                     out.append("stack.push(arg3);");
   246                     break;
   247                 case opc_iload:
   248                 case opc_lload:
   249                 case opc_fload:
   250                 case opc_dload:
   251                 case opc_aload: {
   252                     final int indx = readByte(byteCodes, ++i);
   253                     out.append("stack.push(arg").append(indx + ");");
   254                     break;
   255                 }
   256                 case opc_istore:
   257                 case opc_lstore:
   258                 case opc_fstore:
   259                 case opc_dstore:
   260                 case opc_astore: {
   261                     final int indx = readByte(byteCodes, ++i);
   262                     out.append("arg" + indx).append(" = stack.pop();");
   263                     break;
   264                 }
   265                 case opc_astore_0:
   266                 case opc_istore_0:
   267                 case opc_lstore_0:
   268                 case opc_fstore_0:
   269                 case opc_dstore_0:
   270                     out.append("arg0 = stack.pop();");
   271                     break;
   272                 case opc_astore_1:
   273                 case opc_istore_1:
   274                 case opc_lstore_1:
   275                 case opc_fstore_1:
   276                 case opc_dstore_1:
   277                     out.append("arg1 = stack.pop();");
   278                     break;
   279                 case opc_astore_2:
   280                 case opc_istore_2:
   281                 case opc_lstore_2:
   282                 case opc_fstore_2:
   283                 case opc_dstore_2:
   284                     out.append("arg2 = stack.pop();");
   285                     break;
   286                 case opc_astore_3:
   287                 case opc_istore_3:
   288                 case opc_lstore_3:
   289                 case opc_fstore_3:
   290                 case opc_dstore_3:
   291                     out.append("arg3 = stack.pop();");
   292                     break;
   293                 case opc_iadd:
   294                 case opc_ladd:
   295                 case opc_fadd:
   296                 case opc_dadd:
   297                     out.append("stack.push(stack.pop() + stack.pop());");
   298                     break;
   299                 case opc_isub:
   300                 case opc_lsub:
   301                 case opc_fsub:
   302                 case opc_dsub:
   303                     out.append("{ var tmp = stack.pop(); stack.push(stack.pop() - tmp); }");
   304                     break;
   305                 case opc_imul:
   306                 case opc_lmul:
   307                 case opc_fmul:
   308                 case opc_dmul:
   309                     out.append("stack.push(stack.pop() * stack.pop());");
   310                     break;
   311                 case opc_idiv:
   312                 case opc_ldiv:
   313                     out.append("{ var tmp = stack.pop(); stack.push(Math.floor(stack.pop() / tmp)); }");
   314                     break;
   315                 case opc_fdiv:
   316                 case opc_ddiv:
   317                     out.append("{ var tmp = stack.pop(); stack.push(stack.pop() / tmp); }");
   318                     break;
   319                 case opc_iand:
   320                 case opc_land:
   321                     out.append("stack.push(stack.pop() & stack.pop());");
   322                     break;
   323                 case opc_ior:
   324                 case opc_lor:
   325                     out.append("stack.push(stack.pop() | stack.pop());");
   326                     break;
   327                 case opc_ixor:
   328                 case opc_lxor:
   329                     out.append("stack.push(stack.pop() ^ stack.pop());");
   330                     break;
   331                 case opc_ineg:
   332                 case opc_lneg:
   333                 case opc_fneg:
   334                 case opc_dneg:
   335                     out.append("stack.push(- stack.pop());");
   336                     break;
   337                 case opc_ishl:
   338                 case opc_lshl:
   339                     out.append("{ var v = stack.pop(); stack.push(stack.pop() << v); }");
   340                     break;
   341                 case opc_ishr:
   342                 case opc_lshr:
   343                     out.append("{ var v = stack.pop(); stack.push(stack.pop() >> v); }");
   344                     break;
   345                 case opc_iushr:
   346                 case opc_lushr:
   347                     out.append("{ var v = stack.pop(); stack.push(stack.pop() >>> v); }");
   348                     break;
   349                 case opc_iinc: {
   350                     final int varIndx = readByte(byteCodes, ++i);
   351                     final int incrBy = byteCodes[++i];
   352                     if (incrBy == 1) {
   353                         out.append("arg" + varIndx).append("++;");
   354                     } else {
   355                         out.append("arg" + varIndx).append(" += " + incrBy).append(";");
   356                     }
   357                     break;
   358                 }
   359                 case opc_return:
   360                     out.append("return;");
   361                     break;
   362                 case opc_ireturn:
   363                 case opc_lreturn:
   364                 case opc_freturn:
   365                 case opc_dreturn:
   366                 case opc_areturn:
   367                     out.append("return stack.pop();");
   368                     break;
   369                 case opc_i2l:
   370                 case opc_i2f:
   371                 case opc_i2d:
   372                 case opc_l2i:
   373                     // max int check?
   374                 case opc_l2f:
   375                 case opc_l2d:
   376                 case opc_f2d:
   377                 case opc_d2f:
   378                     out.append("/* number conversion */");
   379                     break;
   380                 case opc_f2i:
   381                 case opc_f2l:
   382                 case opc_d2i:
   383                 case opc_d2l:
   384                     out.append("stack.push(Math.floor(stack.pop()));");
   385                     break;
   386                 case opc_i2b:
   387                 case opc_i2c:
   388                 case opc_i2s:
   389                     out.append("/* number conversion */");
   390                     break;
   391                 case opc_aconst_null:
   392                     out.append("stack.push(null);");
   393                     break;
   394                 case opc_iconst_m1:
   395                     out.append("stack.push(-1);");
   396                     break;
   397                 case opc_iconst_0:
   398                 case opc_dconst_0:
   399                 case opc_lconst_0:
   400                 case opc_fconst_0:
   401                     out.append("stack.push(0);");
   402                     break;
   403                 case opc_iconst_1:
   404                 case opc_lconst_1:
   405                 case opc_fconst_1:
   406                 case opc_dconst_1:
   407                     out.append("stack.push(1);");
   408                     break;
   409                 case opc_iconst_2:
   410                 case opc_fconst_2:
   411                     out.append("stack.push(2);");
   412                     break;
   413                 case opc_iconst_3:
   414                     out.append("stack.push(3);");
   415                     break;
   416                 case opc_iconst_4:
   417                     out.append("stack.push(4);");
   418                     break;
   419                 case opc_iconst_5:
   420                     out.append("stack.push(5);");
   421                     break;
   422                 case opc_ldc: {
   423                     int indx = readByte(byteCodes, ++i);
   424                     String v = encodeConstant(indx);
   425                     out.append("stack.push(").append(v).append(");");
   426                     break;
   427                 }
   428                 case opc_ldc_w:
   429                 case opc_ldc2_w: {
   430                     int indx = readIntArg(byteCodes, i);
   431                     i += 2;
   432                     String v = encodeConstant(indx);
   433                     out.append("stack.push(").append(v).append(");");
   434                     break;
   435                 }
   436                 case opc_lcmp:
   437                 case opc_fcmpl:
   438                 case opc_fcmpg:
   439                 case opc_dcmpl:
   440                 case opc_dcmpg: {
   441                     out.append("{ var delta = stack.pop() - stack.pop(); stack.push(delta < 0 ?-1 : (delta == 0 ? 0 : 1)); }");
   442                     break;
   443                 }
   444                 case opc_if_acmpeq:
   445                     i = generateIf(byteCodes, i, "===");
   446                     break;
   447                 case opc_if_acmpne:
   448                     i = generateIf(byteCodes, i, "!=");
   449                     break;
   450                 case opc_if_icmpeq: {
   451                     i = generateIf(byteCodes, i, "==");
   452                     break;
   453                 }
   454                 case opc_ifeq: {
   455                     int indx = i + readIntArg(byteCodes, i);
   456                     out.append("if (stack.pop() == 0) { gt = " + indx);
   457                     out.append("; continue; }");
   458                     i += 2;
   459                     break;
   460                 }
   461                 case opc_ifne: {
   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 opc_iflt: {
   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 opc_ifle: {
   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 opc_ifgt: {
   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 opc_ifge: {
   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 opc_ifnonnull: {
   497                     int indx = i + readIntArg(byteCodes, i);
   498                     out.append("if (stack.pop()) { gt = " + indx);
   499                     out.append("; continue; }");
   500                     i += 2;
   501                     break;
   502                 }
   503                 case opc_ifnull: {
   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 opc_if_icmpne:
   511                     i = generateIf(byteCodes, i, "!=");
   512                     break;
   513                 case opc_if_icmplt:
   514                     i = generateIf(byteCodes, i, ">");
   515                     break;
   516                 case opc_if_icmple:
   517                     i = generateIf(byteCodes, i, ">=");
   518                     break;
   519                 case opc_if_icmpgt:
   520                     i = generateIf(byteCodes, i, "<");
   521                     break;
   522                 case opc_if_icmpge:
   523                     i = generateIf(byteCodes, i, "<=");
   524                     break;
   525                 case opc_goto: {
   526                     int indx = i + readIntArg(byteCodes, i);
   527                     out.append("gt = " + indx).append("; continue;");
   528                     i += 2;
   529                     break;
   530                 }
   531                 case opc_lookupswitch: {
   532                     int table = i / 4 * 4 + 4;
   533                     int dflt = i + readInt4(byteCodes, table);
   534                     table += 4;
   535                     int n = readInt4(byteCodes, table);
   536                     table += 4;
   537                     out.append("switch (stack.pop()) {\n");
   538                     while (n-- > 0) {
   539                         int cnstnt = readInt4(byteCodes, table);
   540                         table += 4;
   541                         int offset = i + readInt4(byteCodes, table);
   542                         table += 4;
   543                         out.append("  case " + cnstnt).append(": gt = " + offset).append("; continue;\n");
   544                     }
   545                     out.append("  default: gt = " + dflt).append("; continue;\n}");
   546                     i = table - 1;
   547                     break;
   548                 }
   549                 case opc_tableswitch: {
   550                     int table = i / 4 * 4 + 4;
   551                     int dflt = i + readInt4(byteCodes, table);
   552                     table += 4;
   553                     int low = readInt4(byteCodes, table);
   554                     table += 4;
   555                     int high = readInt4(byteCodes, table);
   556                     table += 4;
   557                     out.append("switch (stack.pop()) {\n");
   558                     while (low <= high) {
   559                         int offset = i + readInt4(byteCodes, table);
   560                         table += 4;
   561                         out.append("  case " + low).append(": gt = " + offset).append("; continue;\n");
   562                         low++;
   563                     }
   564                     out.append("  default: gt = " + dflt).append("; continue;\n}");
   565                     i = table - 1;
   566                     break;
   567                 }
   568                 case opc_invokeinterface: {
   569                     i = invokeVirtualMethod(byteCodes, i) + 2;
   570                     break;
   571                 }
   572                 case opc_invokevirtual:
   573                     i = invokeVirtualMethod(byteCodes, i);
   574                     break;
   575                 case opc_invokespecial:
   576                     i = invokeStaticMethod(byteCodes, i, false);
   577                     break;
   578                 case opc_invokestatic:
   579                     i = invokeStaticMethod(byteCodes, i, true);
   580                     break;
   581                 case opc_new: {
   582                     int indx = readIntArg(byteCodes, i);
   583                     String ci = jc.getClassName(indx);
   584                     out.append("stack.push(");
   585                     out.append("new ").append(ci.replace('/','_'));
   586                     out.append(");");
   587                     addReference(ci);
   588                     i += 2;
   589                     break;
   590                 }
   591                 case opc_newarray: {
   592                     int type = byteCodes[i++];
   593                     out.append("stack.push(new Array(stack.pop()));");
   594                     break;
   595                 }
   596                 case opc_anewarray: {
   597                     i += 2; // skip type of array
   598                     out.append("stack.push(new Array(stack.pop()));");
   599                     break;
   600                 }
   601                 case opc_multianewarray: {
   602                     i += 2;
   603                     int dim = readByte(byteCodes, ++i);
   604                     out.append("{ var a0 = new Array(stack.pop());");
   605                     for (int d = 1; d < dim; d++) {
   606                         out.append("\n  var l" + d).append(" = stack.pop();");
   607                         out.append("\n  for (var i" + d).append (" = 0; i" + d).
   608                             append(" < a" + (d - 1)).
   609                             append(".length; i" + d).append("++) {");
   610                         out.append("\n    var a" + d).
   611                             append (" = new Array(l" + d).append(");");
   612                         out.append("\n    a" + (d - 1)).append("[i" + d).append("] = a" + d).
   613                             append(";");
   614                     }
   615                     for (int d = 1; d < dim; d++) {
   616                         out.append("\n  }");
   617                     }
   618                     out.append("\nstack.push(a0); }");
   619                     break;
   620                 }
   621                 case opc_arraylength:
   622                     out.append("stack.push(stack.pop().length);");
   623                     break;
   624                 case opc_iastore:
   625                 case opc_lastore:
   626                 case opc_fastore:
   627                 case opc_dastore:
   628                 case opc_aastore:
   629                 case opc_bastore:
   630                 case opc_castore:
   631                 case opc_sastore: {
   632                     out.append("{ var value = stack.pop(); var indx = stack.pop(); stack.pop()[indx] = value; }");
   633                     break;
   634                 }
   635                 case opc_iaload:
   636                 case opc_laload:
   637                 case opc_faload:
   638                 case opc_daload:
   639                 case opc_aaload:
   640                 case opc_baload:
   641                 case opc_caload:
   642                 case opc_saload: {
   643                     out.append("{ var indx = stack.pop(); stack.push(stack.pop()[indx]); }");
   644                     break;
   645                 }
   646                 case opc_pop2:
   647                     out.append("stack.pop();");
   648                 case opc_pop:
   649                     out.append("stack.pop();");
   650                     break;
   651                 case opc_dup:
   652                     out.append("stack.push(stack[stack.length - 1]);");
   653                     break;
   654                 case opc_bipush:
   655                     out.append("stack.push(" + byteCodes[++i] + ");");
   656                     break;
   657                 case opc_sipush:
   658                     out.append("stack.push(" + readIntArg(byteCodes, i) + ");");
   659                     i += 2;
   660                     break;
   661                 case opc_getfield: {
   662                     int indx = readIntArg(byteCodes, i);
   663                     String[] fi = jc.getFieldInfoName(indx);
   664                     out.append("stack.push(stack.pop().fld_").
   665                         append(fi[1]).append(");");
   666                     i += 2;
   667                     break;
   668                 }
   669                 case opc_getstatic: {
   670                     int indx = readIntArg(byteCodes, i);
   671                     String[] fi = jc.getFieldInfoName(indx);
   672                     out.append("stack.push(").append(fi[0].replace('/', '_'));
   673                     out.append('_').append(fi[1]).append(");");
   674                     i += 2;
   675                     addReference(fi[0]);
   676                     break;
   677                 }
   678                 case opc_putstatic: {
   679                     int indx = readIntArg(byteCodes, i);
   680                     String[] fi = jc.getFieldInfoName(indx);
   681                     out.append(fi[0].replace('/', '_'));
   682                     out.append('_').append(fi[1]).append(" = stack.pop();");
   683                     i += 2;
   684                     addReference(fi[0]);
   685                     break;
   686                 }
   687                 case opc_putfield: {
   688                     int indx = readIntArg(byteCodes, i);
   689                     String[] fi = jc.getFieldInfoName(indx);
   690                     out.append("{ var v = stack.pop(); stack.pop().fld_")
   691                        .append(fi[1]).append(" = v; }");
   692                     i += 2;
   693                     break;
   694                 }
   695                 case opc_checkcast: {
   696                     int indx = readIntArg(byteCodes, i);
   697                     final String type = jc.getClassName(indx);
   698                     if (!type.startsWith("[")) {
   699                         // no way to check arrays right now
   700                         out.append("if(stack[stack.length - 1].$instOf_")
   701                            .append(type.replace('/', '_'))
   702                            .append(" != 1) throw {};"); // XXX proper exception
   703                     }
   704                     i += 2;
   705                     break;
   706                 }
   707                 case opc_instanceof: {
   708                     int indx = readIntArg(byteCodes, i);
   709                     final String type = jc.getClassName(indx);
   710                     out.append("stack.push(stack.pop().$instOf_")
   711                        .append(type.replace('/', '_'))
   712                        .append(" ? 1 : 0);");
   713                     i += 2;
   714                     break;
   715                 }
   716                 case opc_athrow: {
   717                     out.append("{ var t = stack.pop(); stack = new Array(1); stack[0] = t; throw t; }");
   718                     break;
   719                 }
   720                 default: {
   721                     out.append("throw 'unknown bytecode " + c + "';");
   722                 }
   723                     
   724             }
   725             out.append(" //");
   726             for (int j = prev; j <= i; j++) {
   727                 out.append(" ");
   728                 final int cc = readByte(byteCodes, j);
   729                 out.append(Integer.toString(cc));
   730             }
   731             out.append("\n");
   732         }
   733         out.append("  }\n");
   734     }
   735 
   736     private int generateIf(byte[] byteCodes, int i, final String test) throws IOException {
   737         int indx = i + readIntArg(byteCodes, i);
   738         out.append("if (stack.pop() ").append(test).append(" stack.pop()) { gt = " + indx);
   739         out.append("; continue; }");
   740         return i + 2;
   741     }
   742 
   743     private int readIntArg(byte[] byteCodes, int offsetInstruction) {
   744         final int indxHi = byteCodes[offsetInstruction + 1] << 8;
   745         final int indxLo = byteCodes[offsetInstruction + 2];
   746         return (indxHi & 0xffffff00) | (indxLo & 0xff);
   747     }
   748     private int readInt4(byte[] byteCodes, int offsetInstruction) {
   749         final int d = byteCodes[offsetInstruction + 0] << 24;
   750         final int c = byteCodes[offsetInstruction + 1] << 16;
   751         final int b = byteCodes[offsetInstruction + 2] << 8;
   752         final int a = byteCodes[offsetInstruction + 3];
   753         return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
   754     }
   755     private int readByte(byte[] byteCodes, int offsetInstruction) {
   756         return (byteCodes[offsetInstruction] + 256) % 256;
   757     }
   758     
   759     private static void countArgs(String descriptor, boolean[] hasReturnType, StringBuilder sig, StringBuilder cnt) {
   760         int i = 0;
   761         Boolean count = null;
   762         boolean array = false;
   763         int firstPos = sig.length();
   764         while (i < descriptor.length()) {
   765             char ch = descriptor.charAt(i++);
   766             switch (ch) {
   767                 case '(':
   768                     count = true;
   769                     continue;
   770                 case ')':
   771                     count = false;
   772                     continue;
   773                 case 'A':
   774                     array = true;
   775                     break;
   776                 case 'B': 
   777                 case 'C': 
   778                 case 'D': 
   779                 case 'F': 
   780                 case 'I': 
   781                 case 'J': 
   782                 case 'S': 
   783                 case 'Z': 
   784                     if (count) {
   785                         if (array) {
   786                             sig.append('A');
   787                         }
   788                         sig.append(ch);
   789                         if (ch == 'J' || ch == 'D') {
   790                             cnt.append('1');
   791                         } else {
   792                             cnt.append('0');
   793                         }
   794                     } else {
   795                         hasReturnType[0] = true;
   796                         sig.insert(firstPos, ch);
   797                         if (array) {
   798                             sig.insert(firstPos, 'A');
   799                         }
   800                     }
   801                     array = false;
   802                     continue;
   803                 case 'V': 
   804                     assert !count;
   805                     hasReturnType[0] = false;
   806                     sig.insert(firstPos, 'V');
   807                     continue;
   808                 case 'L':
   809                     int next = descriptor.indexOf(';', i);
   810                     if (count) {
   811                         if (array) {
   812                             sig.append('A');
   813                         }
   814                         sig.append(ch);
   815                         sig.append(descriptor.substring(i, next).replace('/', '_'));
   816                         cnt.append('0');
   817                     } else {
   818                         sig.insert(firstPos, descriptor.substring(i, next).replace('/', '_'));
   819                         sig.insert(firstPos, ch);
   820                         if (array) {
   821                             sig.insert(firstPos, 'A');
   822                         }
   823                         hasReturnType[0] = true;
   824                     }
   825                     i = next + 1;
   826                     continue;
   827                 case '[':
   828                     //arrays++;
   829                     continue;
   830                 default:
   831                     break; // invalid character
   832             }
   833         }
   834     }
   835 
   836     private void generateStaticField(FieldData v) throws IOException {
   837         out.append("\nvar ")
   838            .append(className(jc))
   839            .append('_').append(v.getName()).append(" = 0;");
   840     }
   841 
   842     private String findMethodName(MethodData m, StringBuilder cnt) {
   843         StringBuilder name = new StringBuilder();
   844         if ("<init>".equals(m.getName())) { // NOI18N
   845             name.append("cons"); // NOI18N
   846         } else if ("<clinit>".equals(m.getName())) { // NOI18N
   847             name.append("class"); // NOI18N
   848         } else {
   849             name.append(m.getName());
   850         } 
   851         
   852         boolean hasReturn[] = { false };
   853         countArgs(findDescriptor(m.getInternalSig()), hasReturn, name, cnt);
   854         return name.toString();
   855     }
   856 
   857     private String findMethodName(String[] mi, StringBuilder cnt, boolean[] hasReturn) {
   858         StringBuilder name = new StringBuilder();
   859         String descr = mi[2];//mi.getDescriptor();
   860         String nm= mi[1];
   861         if ("<init>".equals(nm)) { // NOI18N
   862             name.append("cons"); // NOI18N
   863         } else {
   864             name.append(nm);
   865         }
   866         countArgs(findDescriptor(descr), hasReturn, name, cnt);
   867         return name.toString();
   868     }
   869 
   870     private int invokeStaticMethod(byte[] byteCodes, int i, boolean isStatic)
   871     throws IOException {
   872         int methodIndex = readIntArg(byteCodes, i);
   873         String[] mi = jc.getFieldInfoName(methodIndex);
   874         boolean[] hasReturn = { false };
   875         StringBuilder cnt = new StringBuilder();
   876         String mn = findMethodName(mi, cnt, hasReturn);
   877         out.append("{ ");
   878         for (int j = cnt.length() - 1; j >= 0; j--) {
   879             out.append("var v" + j).append(" = stack.pop(); ");
   880         }
   881         
   882         if (hasReturn[0]) {
   883             out.append("stack.push(");
   884         }
   885         final String in = mi[0];
   886         out.append(in.replace('/', '_'));
   887         if (isStatic) {
   888             out.append(".prototype.");
   889         } else {
   890             out.append('_');
   891         }
   892         out.append(mn);
   893         out.append('(');
   894         String sep = "";
   895         if (!isStatic) {
   896             out.append("stack.pop()");
   897             sep = ", ";
   898         }
   899         for (int j = 0; j < cnt.length(); j++) {
   900             out.append(sep);
   901             out.append("v" + j);
   902             sep = ", ";
   903         }
   904         out.append(")");
   905         if (hasReturn[0]) {
   906             out.append(")");
   907         }
   908         out.append("; }");
   909         i += 2;
   910         addReference(in);
   911         return i;
   912     }
   913     private int invokeVirtualMethod(byte[] byteCodes, int i)
   914     throws IOException {
   915         int methodIndex = readIntArg(byteCodes, i);
   916         String[] mi = jc.getFieldInfoName(methodIndex);
   917         boolean[] hasReturn = { false };
   918         StringBuilder cnt = new StringBuilder();
   919         String mn = findMethodName(mi, cnt, hasReturn);
   920         out.append("{ ");
   921         for (int j = cnt.length() - 1; j >= 0; j--) {
   922             out.append("var v" + j).append(" = stack.pop(); ");
   923         }
   924         out.append("var self = stack.pop(); ");
   925         if (hasReturn[0]) {
   926             out.append("stack.push(");
   927         }
   928         out.append("self.");
   929         out.append(mn);
   930         out.append('(');
   931         out.append("self");
   932         for (int j = 0; j < cnt.length(); j++) {
   933             out.append(", ");
   934             out.append("v" + j);
   935         }
   936         out.append(")");
   937         if (hasReturn[0]) {
   938             out.append(")");
   939         }
   940         out.append("; }");
   941         i += 2;
   942         return i;
   943     }
   944     
   945     private void addReference(String cn) throws IOException {
   946         if (requireReference(cn)) {
   947             out.append(" /* needs ").append(cn).append(" */");
   948         }
   949     }
   950 
   951     private void outType(String d, StringBuilder out) {
   952         int arr = 0;
   953         while (d.charAt(0) == '[') {
   954             out.append('A');
   955             d = d.substring(1);
   956         }
   957         if (d.charAt(0) == 'L') {
   958             assert d.charAt(d.length() - 1) == ';';
   959             out.append(d.replace('/', '_').substring(0, d.length() - 1));
   960         } else {
   961             out.append(d);
   962         }
   963     }
   964 
   965     private String encodeConstant(int entryIndex) {
   966         String s = jc.stringValue(entryIndex, true);
   967         return s;
   968     }
   969 
   970     private String findDescriptor(String d) {
   971         return d.replace('[', 'A');
   972     }
   973 
   974     private boolean javaScriptBody(MethodData m, boolean isStatic) throws IOException {
   975         byte[] arr = m.findAnnotationData(true);
   976         if (arr == null) {
   977             return false;
   978         }
   979         final String jvmType = "L" + JavaScriptBody.class.getName().replace('.', '/') + ";";
   980         class P extends AnnotationParser {
   981             int cnt;
   982             String[] args = new String[30];
   983             String body;
   984             
   985             @Override
   986             protected void visitAttr(String type, String attr, String value) {
   987                 if (type.equals(jvmType)) {
   988                     if ("body".equals(attr)) {
   989                         body = value;
   990                     } else if ("args".equals(attr)) {
   991                         args[cnt++] = value;
   992                     } else {
   993                         throw new IllegalArgumentException(attr);
   994                     }
   995                 }
   996             }
   997         }
   998         P p = new P();
   999         p.parse(arr, jc);
  1000         if (p.body == null) {
  1001             return false;
  1002         }
  1003         StringBuilder cnt = new StringBuilder();
  1004         out.append("\nfunction ").append(className(jc)).append('_').
  1005             append(findMethodName(m, cnt));
  1006         out.append("(");
  1007         String space;
  1008         int index;
  1009         if (!isStatic) {                
  1010             out.append(p.args[0]);
  1011             space = ",";
  1012             index = 1;
  1013         } else {
  1014             space = "";
  1015             index = 0;
  1016         }
  1017         for (int i = 0; i < cnt.length(); i++) {
  1018             out.append(space);
  1019             out.append(p.args[index]);
  1020             index++;
  1021             space = ",";
  1022         }
  1023         out.append(") {").append("\n");
  1024         out.append(p.body);
  1025         out.append("\n}\n");
  1026         return true;
  1027     }
  1028     private static String className(ClassData jc) {
  1029         //return jc.getName().getInternalName().replace('/', '_');
  1030         return jc.getClassName().replace('/', '_');
  1031     }
  1032     
  1033     private static String[] findAnnotation(
  1034         byte[] arr, ClassData cd, final String className, 
  1035         final String... attrNames
  1036     ) throws IOException {
  1037         if (arr == null) {
  1038             return null;
  1039         }
  1040         final String[] values = new String[attrNames.length];
  1041         final boolean[] found = { false };
  1042         final String jvmType = "L" + className.replace('.', '/') + ";";
  1043         AnnotationParser ap = new AnnotationParser() {
  1044             @Override
  1045             protected void visitAttr(String type, String attr, String value) {
  1046                 if (type.equals(jvmType)) {
  1047                     found[0] = true;
  1048                     for (int i = 0; i < attrNames.length; i++) {
  1049                         if (attrNames[i].equals(attr)) {
  1050                             values[i] = value;
  1051                         }
  1052                     }
  1053                 }
  1054             }
  1055             
  1056         };
  1057         ap.parse(arr, cd);
  1058         return found[0] ? values : null;
  1059     }
  1060 }