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