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