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