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