vm/src/main/java/org/apidesign/vm4brwsr/ByteCodeToJavaScript.java
author tzezula
Sat, 08 Dec 2012 10:32:04 +0100
branchexceptions
changeset 287 6f696a0ef12f
parent 272 a6a23aa7a546
parent 285 c8be2d837788
child 288 6d1e8eccdc98
permissions -rw-r--r--
'synched w/ trunk'
     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.Vector;
    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(code, m.getexception_table());
   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(code, m.getexception_table());
   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(byte[] byteCodes, Vector exceptionTable) throws IOException {
   265 
   266         final java.util.Map<Short, TrapData> exStart = new java.util.HashMap<Short, TrapData>();
   267         final java.util.Map<Short, TrapData> exStop = new java.util.HashMap<Short, TrapData>();
   268         for (int i=0 ; i < exceptionTable.size(); i++) {
   269             final TrapData td = (TrapData)exceptionTable.elementAt(i);
   270             exStart.put(td.start_pc, td);
   271             exStop.put(td.end_pc, td);
   272         }
   273         final java.util.Deque<TrapData> current = new java.util.ArrayDeque<TrapData>();
   274         out.append("\n  var gt = 0;\n  for(;;) switch(gt) {\n");
   275 
   276         for (int i = 0; i < byteCodes.length; i++) {
   277 
   278             {
   279                 TrapData e = exStart.get((short)i);
   280                 if (e != null) {
   281                     current.addFirst(e);
   282                 }
   283                 e = exStop.get((short)i);
   284                 if (e != null) {
   285                     current.remove(e);
   286                 }
   287             }
   288             int prev = i;
   289             out.append("    case " + i).append(": ");            
   290             if (!current.isEmpty()) {
   291                 out.append("try {");
   292             }
   293             final int c = readByte(byteCodes, i);
   294             switch (c) {
   295                 case opc_aload_0:
   296                 case opc_iload_0:
   297                 case opc_lload_0:
   298                 case opc_fload_0:
   299                 case opc_dload_0:
   300                     out.append("s.push(arg0);");
   301                     break;
   302                 case opc_aload_1:
   303                 case opc_iload_1:
   304                 case opc_lload_1:
   305                 case opc_fload_1:
   306                 case opc_dload_1:
   307                     out.append("s.push(arg1);");
   308                     break;
   309                 case opc_aload_2:
   310                 case opc_iload_2:
   311                 case opc_lload_2:
   312                 case opc_fload_2:
   313                 case opc_dload_2:
   314                     out.append("s.push(arg2);");
   315                     break;
   316                 case opc_aload_3:
   317                 case opc_iload_3:
   318                 case opc_lload_3:
   319                 case opc_fload_3:
   320                 case opc_dload_3:
   321                     out.append("s.push(arg3);");
   322                     break;
   323                 case opc_iload:
   324                 case opc_lload:
   325                 case opc_fload:
   326                 case opc_dload:
   327                 case opc_aload: {
   328                     final int indx = readByte(byteCodes, ++i);
   329                     out.append("s.push(arg").append(indx + ");");
   330                     break;
   331                 }
   332                 case opc_istore:
   333                 case opc_lstore:
   334                 case opc_fstore:
   335                 case opc_dstore:
   336                 case opc_astore: {
   337                     final int indx = readByte(byteCodes, ++i);
   338                     out.append("arg" + indx).append(" = s.pop();");
   339                     break;
   340                 }
   341                 case opc_astore_0:
   342                 case opc_istore_0:
   343                 case opc_lstore_0:
   344                 case opc_fstore_0:
   345                 case opc_dstore_0:
   346                     out.append("arg0 = s.pop();");
   347                     break;
   348                 case opc_astore_1:
   349                 case opc_istore_1:
   350                 case opc_lstore_1:
   351                 case opc_fstore_1:
   352                 case opc_dstore_1:
   353                     out.append("arg1 = s.pop();");
   354                     break;
   355                 case opc_astore_2:
   356                 case opc_istore_2:
   357                 case opc_lstore_2:
   358                 case opc_fstore_2:
   359                 case opc_dstore_2:
   360                     out.append("arg2 = s.pop();");
   361                     break;
   362                 case opc_astore_3:
   363                 case opc_istore_3:
   364                 case opc_lstore_3:
   365                 case opc_fstore_3:
   366                 case opc_dstore_3:
   367                     out.append("arg3 = s.pop();");
   368                     break;
   369                 case opc_iadd:
   370                 case opc_ladd:
   371                 case opc_fadd:
   372                 case opc_dadd:
   373                     out.append("s.push(s.pop() + s.pop());");
   374                     break;
   375                 case opc_isub:
   376                 case opc_lsub:
   377                 case opc_fsub:
   378                 case opc_dsub:
   379                     out.append("{ var tmp = s.pop(); s.push(s.pop() - tmp); }");
   380                     break;
   381                 case opc_imul:
   382                 case opc_lmul:
   383                 case opc_fmul:
   384                 case opc_dmul:
   385                     out.append("s.push(s.pop() * s.pop());");
   386                     break;
   387                 case opc_idiv:
   388                 case opc_ldiv:
   389                     out.append("{ var tmp = s.pop(); s.push(Math.floor(s.pop() / tmp)); }");
   390                     break;
   391                 case opc_fdiv:
   392                 case opc_ddiv:
   393                     out.append("{ var tmp = s.pop(); s.push(s.pop() / tmp); }");
   394                     break;
   395                 case opc_irem:
   396                 case opc_lrem:
   397                 case opc_frem:
   398                 case opc_drem:
   399                     out.append("{ var d = s.pop(); s.push(s.pop() % d); }");
   400                     break;
   401                 case opc_iand:
   402                 case opc_land:
   403                     out.append("s.push(s.pop() & s.pop());");
   404                     break;
   405                 case opc_ior:
   406                 case opc_lor:
   407                     out.append("s.push(s.pop() | s.pop());");
   408                     break;
   409                 case opc_ixor:
   410                 case opc_lxor:
   411                     out.append("s.push(s.pop() ^ s.pop());");
   412                     break;
   413                 case opc_ineg:
   414                 case opc_lneg:
   415                 case opc_fneg:
   416                 case opc_dneg:
   417                     out.append("s.push(- s.pop());");
   418                     break;
   419                 case opc_ishl:
   420                 case opc_lshl:
   421                     out.append("{ var v = s.pop(); s.push(s.pop() << v); }");
   422                     break;
   423                 case opc_ishr:
   424                 case opc_lshr:
   425                     out.append("{ var v = s.pop(); s.push(s.pop() >> v); }");
   426                     break;
   427                 case opc_iushr:
   428                 case opc_lushr:
   429                     out.append("{ var v = s.pop(); s.push(s.pop() >>> v); }");
   430                     break;
   431                 case opc_iinc: {
   432                     final int varIndx = readByte(byteCodes, ++i);
   433                     final int incrBy = byteCodes[++i];
   434                     if (incrBy == 1) {
   435                         out.append("arg" + varIndx).append("++;");
   436                     } else {
   437                         out.append("arg" + varIndx).append(" += " + incrBy).append(";");
   438                     }
   439                     break;
   440                 }
   441                 case opc_return:
   442                     out.append("return;");
   443                     break;
   444                 case opc_ireturn:
   445                 case opc_lreturn:
   446                 case opc_freturn:
   447                 case opc_dreturn:
   448                 case opc_areturn:
   449                     out.append("return s.pop();");
   450                     break;
   451                 case opc_i2l:
   452                 case opc_i2f:
   453                 case opc_i2d:
   454                 case opc_l2i:
   455                     // max int check?
   456                 case opc_l2f:
   457                 case opc_l2d:
   458                 case opc_f2d:
   459                 case opc_d2f:
   460                     out.append("/* number conversion */");
   461                     break;
   462                 case opc_f2i:
   463                 case opc_f2l:
   464                 case opc_d2i:
   465                 case opc_d2l:
   466                     out.append("s.push(Math.floor(s.pop()));");
   467                     break;
   468                 case opc_i2b:
   469                 case opc_i2c:
   470                 case opc_i2s:
   471                     out.append("/* number conversion */");
   472                     break;
   473                 case opc_aconst_null:
   474                     out.append("s.push(null);");
   475                     break;
   476                 case opc_iconst_m1:
   477                     out.append("s.push(-1);");
   478                     break;
   479                 case opc_iconst_0:
   480                 case opc_dconst_0:
   481                 case opc_lconst_0:
   482                 case opc_fconst_0:
   483                     out.append("s.push(0);");
   484                     break;
   485                 case opc_iconst_1:
   486                 case opc_lconst_1:
   487                 case opc_fconst_1:
   488                 case opc_dconst_1:
   489                     out.append("s.push(1);");
   490                     break;
   491                 case opc_iconst_2:
   492                 case opc_fconst_2:
   493                     out.append("s.push(2);");
   494                     break;
   495                 case opc_iconst_3:
   496                     out.append("s.push(3);");
   497                     break;
   498                 case opc_iconst_4:
   499                     out.append("s.push(4);");
   500                     break;
   501                 case opc_iconst_5:
   502                     out.append("s.push(5);");
   503                     break;
   504                 case opc_ldc: {
   505                     int indx = readByte(byteCodes, ++i);
   506                     String v = encodeConstant(indx);
   507                     out.append("s.push(").append(v).append(");");
   508                     break;
   509                 }
   510                 case opc_ldc_w:
   511                 case opc_ldc2_w: {
   512                     int indx = readIntArg(byteCodes, i);
   513                     i += 2;
   514                     String v = encodeConstant(indx);
   515                     out.append("s.push(").append(v).append(");");
   516                     break;
   517                 }
   518                 case opc_lcmp:
   519                 case opc_fcmpl:
   520                 case opc_fcmpg:
   521                 case opc_dcmpl:
   522                 case opc_dcmpg: {
   523                     out.append("{ var delta = s.pop() - s.pop(); s.push(delta < 0 ?-1 : (delta == 0 ? 0 : 1)); }");
   524                     break;
   525                 }
   526                 case opc_if_acmpeq:
   527                     i = generateIf(byteCodes, i, "===");
   528                     break;
   529                 case opc_if_acmpne:
   530                     i = generateIf(byteCodes, i, "!=");
   531                     break;
   532                 case opc_if_icmpeq: {
   533                     i = generateIf(byteCodes, i, "==");
   534                     break;
   535                 }
   536                 case opc_ifeq: {
   537                     int indx = i + readIntArg(byteCodes, i);
   538                     out.append("if (s.pop() == 0) { gt = " + indx);
   539                     out.append("; continue; }");
   540                     i += 2;
   541                     break;
   542                 }
   543                 case opc_ifne: {
   544                     int indx = i + readIntArg(byteCodes, i);
   545                     out.append("if (s.pop() != 0) { gt = " + indx);
   546                     out.append("; continue; }");
   547                     i += 2;
   548                     break;
   549                 }
   550                 case opc_iflt: {
   551                     int indx = i + readIntArg(byteCodes, i);
   552                     out.append("if (s.pop() < 0) { gt = " + indx);
   553                     out.append("; continue; }");
   554                     i += 2;
   555                     break;
   556                 }
   557                 case opc_ifle: {
   558                     int indx = i + readIntArg(byteCodes, i);
   559                     out.append("if (s.pop() <= 0) { gt = " + indx);
   560                     out.append("; continue; }");
   561                     i += 2;
   562                     break;
   563                 }
   564                 case opc_ifgt: {
   565                     int indx = i + readIntArg(byteCodes, i);
   566                     out.append("if (s.pop() > 0) { gt = " + indx);
   567                     out.append("; continue; }");
   568                     i += 2;
   569                     break;
   570                 }
   571                 case opc_ifge: {
   572                     int indx = i + readIntArg(byteCodes, i);
   573                     out.append("if (s.pop() >= 0) { gt = " + indx);
   574                     out.append("; continue; }");
   575                     i += 2;
   576                     break;
   577                 }
   578                 case opc_ifnonnull: {
   579                     int indx = i + readIntArg(byteCodes, i);
   580                     out.append("if (s.pop() !== null) { gt = " + indx);
   581                     out.append("; continue; }");
   582                     i += 2;
   583                     break;
   584                 }
   585                 case opc_ifnull: {
   586                     int indx = i + readIntArg(byteCodes, i);
   587                     out.append("if (s.pop() === null) { gt = " + indx);
   588                     out.append("; continue; }");
   589                     i += 2;
   590                     break;
   591                 }
   592                 case opc_if_icmpne:
   593                     i = generateIf(byteCodes, i, "!=");
   594                     break;
   595                 case opc_if_icmplt:
   596                     i = generateIf(byteCodes, i, ">");
   597                     break;
   598                 case opc_if_icmple:
   599                     i = generateIf(byteCodes, i, ">=");
   600                     break;
   601                 case opc_if_icmpgt:
   602                     i = generateIf(byteCodes, i, "<");
   603                     break;
   604                 case opc_if_icmpge:
   605                     i = generateIf(byteCodes, i, "<=");
   606                     break;
   607                 case opc_goto: {
   608                     int indx = i + readIntArg(byteCodes, i);
   609                     out.append("gt = " + indx).append("; continue;");
   610                     i += 2;
   611                     break;
   612                 }
   613                 case opc_lookupswitch: {
   614                     int table = i / 4 * 4 + 4;
   615                     int dflt = i + readInt4(byteCodes, table);
   616                     table += 4;
   617                     int n = readInt4(byteCodes, table);
   618                     table += 4;
   619                     out.append("switch (s.pop()) {\n");
   620                     while (n-- > 0) {
   621                         int cnstnt = readInt4(byteCodes, table);
   622                         table += 4;
   623                         int offset = i + readInt4(byteCodes, table);
   624                         table += 4;
   625                         out.append("  case " + cnstnt).append(": gt = " + offset).append("; continue;\n");
   626                     }
   627                     out.append("  default: gt = " + dflt).append("; continue;\n}");
   628                     i = table - 1;
   629                     break;
   630                 }
   631                 case opc_tableswitch: {
   632                     int table = i / 4 * 4 + 4;
   633                     int dflt = i + readInt4(byteCodes, table);
   634                     table += 4;
   635                     int low = readInt4(byteCodes, table);
   636                     table += 4;
   637                     int high = readInt4(byteCodes, table);
   638                     table += 4;
   639                     out.append("switch (s.pop()) {\n");
   640                     while (low <= high) {
   641                         int offset = i + readInt4(byteCodes, table);
   642                         table += 4;
   643                         out.append("  case " + low).append(": gt = " + offset).append("; continue;\n");
   644                         low++;
   645                     }
   646                     out.append("  default: gt = " + dflt).append("; continue;\n}");
   647                     i = table - 1;
   648                     break;
   649                 }
   650                 case opc_invokeinterface: {
   651                     i = invokeVirtualMethod(byteCodes, i) + 2;
   652                     break;
   653                 }
   654                 case opc_invokevirtual:
   655                     i = invokeVirtualMethod(byteCodes, i);
   656                     break;
   657                 case opc_invokespecial:
   658                     i = invokeStaticMethod(byteCodes, i, false);
   659                     break;
   660                 case opc_invokestatic:
   661                     i = invokeStaticMethod(byteCodes, i, true);
   662                     break;
   663                 case opc_new: {
   664                     int indx = readIntArg(byteCodes, i);
   665                     String ci = jc.getClassName(indx);
   666                     out.append("s.push(new ");
   667                     out.append(ci.replace('/','_'));
   668                     out.append("());");
   669                     addReference(ci);
   670                     i += 2;
   671                     break;
   672                 }
   673                 case opc_newarray: {
   674                     int type = byteCodes[i++];
   675                     out.append("s.push(new Array(s.pop()).fillNulls());");
   676                     break;
   677                 }
   678                 case opc_anewarray: {
   679                     i += 2; // skip type of array
   680                     out.append("s.push(new Array(s.pop()).fillNulls());");
   681                     break;
   682                 }
   683                 case opc_multianewarray: {
   684                     i += 2;
   685                     int dim = readByte(byteCodes, ++i);
   686                     out.append("{ var a0 = new Array(s.pop()).fillNulls();");
   687                     for (int d = 1; d < dim; d++) {
   688                         out.append("\n  var l" + d).append(" = s.pop();");
   689                         out.append("\n  for (var i" + d).append (" = 0; i" + d).
   690                             append(" < a" + (d - 1)).
   691                             append(".length; i" + d).append("++) {");
   692                         out.append("\n    var a" + d).
   693                             append (" = new Array(l" + d).append(").fillNulls();");
   694                         out.append("\n    a" + (d - 1)).append("[i" + d).append("] = a" + d).
   695                             append(";");
   696                     }
   697                     for (int d = 1; d < dim; d++) {
   698                         out.append("\n  }");
   699                     }
   700                     out.append("\ns.push(a0); }");
   701                     break;
   702                 }
   703                 case opc_arraylength:
   704                     out.append("s.push(s.pop().length);");
   705                     break;
   706                 case opc_iastore:
   707                 case opc_lastore:
   708                 case opc_fastore:
   709                 case opc_dastore:
   710                 case opc_aastore:
   711                 case opc_bastore:
   712                 case opc_castore:
   713                 case opc_sastore: {
   714                     out.append("{ var value = s.pop(); var indx = s.pop(); s.pop()[indx] = value; }");
   715                     break;
   716                 }
   717                 case opc_iaload:
   718                 case opc_laload:
   719                 case opc_faload:
   720                 case opc_daload:
   721                 case opc_aaload:
   722                 case opc_baload:
   723                 case opc_caload:
   724                 case opc_saload: {
   725                     out.append("{ var indx = s.pop(); s.push(s.pop()[indx]); }");
   726                     break;
   727                 }
   728                 case opc_pop2:
   729                     out.append("s.pop();");
   730                 case opc_pop:
   731                     out.append("s.pop();");
   732                     break;
   733                 case opc_dup:
   734                     out.append("s.push(s[s.length - 1]);");
   735                     break;
   736                 case opc_dup_x1:
   737                     out.append("{ var v1 = s.pop(); var v2 = s.pop(); s.push(v1); s.push(v2); s.push(v1); }");
   738                     break;
   739                 case opc_dup_x2:
   740                     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); }");
   741                     break;
   742                 case opc_bipush:
   743                     out.append("s.push(" + byteCodes[++i] + ");");
   744                     break;
   745                 case opc_sipush:
   746                     out.append("s.push(" + readIntArg(byteCodes, i) + ");");
   747                     i += 2;
   748                     break;
   749                 case opc_getfield: {
   750                     int indx = readIntArg(byteCodes, i);
   751                     String[] fi = jc.getFieldInfoName(indx);
   752                     out.append("s.push(s.pop().fld_").
   753                         append(fi[1]).append(");");
   754                     i += 2;
   755                     break;
   756                 }
   757                 case opc_getstatic: {
   758                     int indx = readIntArg(byteCodes, i);
   759                     String[] fi = jc.getFieldInfoName(indx);
   760                     out.append("s.push(").append(fi[0].replace('/', '_'));
   761                     out.append('.').append(fi[1]).append(");");
   762                     i += 2;
   763                     addReference(fi[0]);
   764                     break;
   765                 }
   766                 case opc_putstatic: {
   767                     int indx = readIntArg(byteCodes, i);
   768                     String[] fi = jc.getFieldInfoName(indx);
   769                     out.append(fi[0].replace('/', '_'));
   770                     out.append('.').append(fi[1]).append(" = s.pop();");
   771                     i += 2;
   772                     addReference(fi[0]);
   773                     break;
   774                 }
   775                 case opc_putfield: {
   776                     int indx = readIntArg(byteCodes, i);
   777                     String[] fi = jc.getFieldInfoName(indx);
   778                     out.append("{ var v = s.pop(); s.pop().fld_")
   779                        .append(fi[1]).append(" = v; }");
   780                     i += 2;
   781                     break;
   782                 }
   783                 case opc_checkcast: {
   784                     int indx = readIntArg(byteCodes, i);
   785                     final String type = jc.getClassName(indx);
   786                     if (!type.startsWith("[")) {
   787                         // no way to check arrays right now
   788                         out.append("if(s[s.length - 1].$instOf_")
   789                            .append(type.replace('/', '_'))
   790                            .append(" != 1) throw {};"); // XXX proper exception
   791                     }
   792                     i += 2;
   793                     break;
   794                 }
   795                 case opc_instanceof: {
   796                     int indx = readIntArg(byteCodes, i);
   797                     final String type = jc.getClassName(indx);
   798                     out.append("s.push(s.pop().$instOf_")
   799                        .append(type.replace('/', '_'))
   800                        .append(" ? 1 : 0);");
   801                     i += 2;
   802                     break;
   803                 }
   804                 case opc_athrow: {
   805                     out.append("{ var t = s.pop(); s = new Array(1); s[0] = t; throw t; }");
   806                     break;
   807                 }
   808                 default: {
   809                     out.append("throw 'unknown bytecode " + c + "';");
   810                 }
   811                     
   812             }
   813             if (!current.isEmpty()) {
   814                 out.append("} catch (e) {");
   815                 for (TrapData e : current) {
   816                     if (e.catch_cpx != 0) { //not finally
   817                         final String classInternalName = jc.getClassName(e.catch_cpx);
   818                         addReference(classInternalName);
   819                         out.append("if (e.$instOf_"+classInternalName.replace('/', '_')+") {");
   820                         out.append("gt="+e.handler_pc+"; continue;");
   821                         out.append("} ");
   822                     } else {
   823                         //finally - todo
   824                     }
   825                 }
   826                 out.append("throw e;");
   827                 out.append("}");
   828             }
   829             out.append(" //");
   830             for (int j = prev; j <= i; j++) {
   831                 out.append(" ");
   832                 final int cc = readByte(byteCodes, j);
   833                 out.append(Integer.toString(cc));
   834             }
   835             out.append("\n");            
   836         }
   837         out.append("  }\n");
   838     }
   839 
   840     private int generateIf(byte[] byteCodes, int i, final String test) throws IOException {
   841         int indx = i + readIntArg(byteCodes, i);
   842         out.append("if (s.pop() ").append(test).append(" s.pop()) { gt = " + indx);
   843         out.append("; continue; }");
   844         return i + 2;
   845     }
   846 
   847     private int readIntArg(byte[] byteCodes, int offsetInstruction) {
   848         final int indxHi = byteCodes[offsetInstruction + 1] << 8;
   849         final int indxLo = byteCodes[offsetInstruction + 2];
   850         return (indxHi & 0xffffff00) | (indxLo & 0xff);
   851     }
   852     private int readInt4(byte[] byteCodes, int offsetInstruction) {
   853         final int d = byteCodes[offsetInstruction + 0] << 24;
   854         final int c = byteCodes[offsetInstruction + 1] << 16;
   855         final int b = byteCodes[offsetInstruction + 2] << 8;
   856         final int a = byteCodes[offsetInstruction + 3];
   857         return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
   858     }
   859     private int readByte(byte[] byteCodes, int offsetInstruction) {
   860         return (byteCodes[offsetInstruction] + 256) % 256;
   861     }
   862     
   863     private static void countArgs(String descriptor, boolean[] hasReturnType, StringBuilder sig, StringBuilder cnt) {
   864         int i = 0;
   865         Boolean count = null;
   866         boolean array = false;
   867         sig.append("__");
   868         int firstPos = sig.length();
   869         while (i < descriptor.length()) {
   870             char ch = descriptor.charAt(i++);
   871             switch (ch) {
   872                 case '(':
   873                     count = true;
   874                     continue;
   875                 case ')':
   876                     count = false;
   877                     continue;
   878                 case 'B': 
   879                 case 'C': 
   880                 case 'D': 
   881                 case 'F': 
   882                 case 'I': 
   883                 case 'J': 
   884                 case 'S': 
   885                 case 'Z': 
   886                     if (count) {
   887                         if (array) {
   888                             sig.append("_3");
   889                         }
   890                         sig.append(ch);
   891                         if (ch == 'J' || ch == 'D') {
   892                             cnt.append('1');
   893                         } else {
   894                             cnt.append('0');
   895                         }
   896                     } else {
   897                         hasReturnType[0] = true;
   898                         sig.insert(firstPos, ch);
   899                         if (array) {
   900                             sig.insert(firstPos, "_3");
   901                         }
   902                     }
   903                     array = false;
   904                     continue;
   905                 case 'V': 
   906                     assert !count;
   907                     hasReturnType[0] = false;
   908                     sig.insert(firstPos, 'V');
   909                     continue;
   910                 case 'L':
   911                     int next = descriptor.indexOf(';', i);
   912                     String realSig = mangleSig(descriptor, i - 1, next + 1);
   913                     if (count) {
   914                         if (array) {
   915                             sig.append("_3");
   916                         }
   917                         sig.append(realSig);
   918                         cnt.append('0');
   919                     } else {
   920                         sig.insert(firstPos, realSig);
   921                         if (array) {
   922                             sig.insert(firstPos, "_3");
   923                         }
   924                         hasReturnType[0] = true;
   925                     }
   926                     i = next + 1;
   927                     continue;
   928                 case '[':
   929                     array = true;
   930                     continue;
   931                 default:
   932                     throw new IllegalStateException("Invalid char: " + ch);
   933             }
   934         }
   935     }
   936     
   937     private static String mangleSig(String txt, int first, int last) {
   938         StringBuilder sb = new StringBuilder();
   939         for (int i = first; i < last; i++) {
   940             final char ch = txt.charAt(i);
   941             switch (ch) {
   942                 case '/': sb.append('_'); break;
   943                 case '_': sb.append("_1"); break;
   944                 case ';': sb.append("_2"); break;
   945                 case '[': sb.append("_3"); break;
   946                 default: sb.append(ch); break;
   947             }
   948         }
   949         return sb.toString();
   950     }
   951 
   952     private static String findMethodName(MethodData m, StringBuilder cnt) {
   953         StringBuilder name = new StringBuilder();
   954         if ("<init>".equals(m.getName())) { // NOI18N
   955             name.append("cons"); // NOI18N
   956         } else if ("<clinit>".equals(m.getName())) { // NOI18N
   957             name.append("class"); // NOI18N
   958         } else {
   959             name.append(m.getName());
   960         } 
   961         
   962         boolean hasReturn[] = { false };
   963         countArgs(m.getInternalSig(), hasReturn, name, cnt);
   964         return name.toString();
   965     }
   966 
   967     static String findMethodName(String[] mi, StringBuilder cnt, boolean[] hasReturn) {
   968         StringBuilder name = new StringBuilder();
   969         String descr = mi[2];//mi.getDescriptor();
   970         String nm= mi[1];
   971         if ("<init>".equals(nm)) { // NOI18N
   972             name.append("cons"); // NOI18N
   973         } else {
   974             name.append(nm);
   975         }
   976         countArgs(descr, hasReturn, name, cnt);
   977         return name.toString();
   978     }
   979 
   980     private int invokeStaticMethod(byte[] byteCodes, int i, boolean isStatic)
   981     throws IOException {
   982         int methodIndex = readIntArg(byteCodes, i);
   983         String[] mi = jc.getFieldInfoName(methodIndex);
   984         boolean[] hasReturn = { false };
   985         StringBuilder cnt = new StringBuilder();
   986         String mn = findMethodName(mi, cnt, hasReturn);
   987         out.append("{ ");
   988         for (int j = cnt.length() - 1; j >= 0; j--) {
   989             out.append("var v" + j).append(" = s.pop(); ");
   990         }
   991         
   992         if (hasReturn[0]) {
   993             out.append("s.push(");
   994         }
   995         final String in = mi[0];
   996         out.append(in.replace('/', '_'));
   997         out.append("(false).");
   998         out.append(mn);
   999         out.append('(');
  1000         String sep = "";
  1001         if (!isStatic) {
  1002             out.append("s.pop()");
  1003             sep = ", ";
  1004         }
  1005         for (int j = 0; j < cnt.length(); j++) {
  1006             out.append(sep);
  1007             out.append("v" + j);
  1008             sep = ", ";
  1009         }
  1010         out.append(")");
  1011         if (hasReturn[0]) {
  1012             out.append(")");
  1013         }
  1014         out.append("; }");
  1015         i += 2;
  1016         addReference(in);
  1017         return i;
  1018     }
  1019     private int invokeVirtualMethod(byte[] byteCodes, int i)
  1020     throws IOException {
  1021         int methodIndex = readIntArg(byteCodes, i);
  1022         String[] mi = jc.getFieldInfoName(methodIndex);
  1023         boolean[] hasReturn = { false };
  1024         StringBuilder cnt = new StringBuilder();
  1025         String mn = findMethodName(mi, cnt, hasReturn);
  1026         out.append("{ ");
  1027         for (int j = cnt.length() - 1; j >= 0; j--) {
  1028             out.append("var v" + j).append(" = s.pop(); ");
  1029         }
  1030         out.append("var self = s.pop(); ");
  1031         if (hasReturn[0]) {
  1032             out.append("s.push(");
  1033         }
  1034         out.append("self.");
  1035         out.append(mn);
  1036         out.append('(');
  1037         out.append("self");
  1038         for (int j = 0; j < cnt.length(); j++) {
  1039             out.append(", ");
  1040             out.append("v" + j);
  1041         }
  1042         out.append(")");
  1043         if (hasReturn[0]) {
  1044             out.append(")");
  1045         }
  1046         out.append("; }");
  1047         i += 2;
  1048         return i;
  1049     }
  1050     
  1051     private void addReference(String cn) throws IOException {
  1052         if (requireReference(cn)) {
  1053             out.append(" /* needs ").append(cn).append(" */");
  1054         }
  1055     }
  1056 
  1057     private void outType(String d, StringBuilder out) {
  1058         int arr = 0;
  1059         while (d.charAt(0) == '[') {
  1060             out.append('A');
  1061             d = d.substring(1);
  1062         }
  1063         if (d.charAt(0) == 'L') {
  1064             assert d.charAt(d.length() - 1) == ';';
  1065             out.append(d.replace('/', '_').substring(0, d.length() - 1));
  1066         } else {
  1067             out.append(d);
  1068         }
  1069     }
  1070 
  1071     private String encodeConstant(int entryIndex) throws IOException {
  1072         String[] classRef = { null };
  1073         String s = jc.stringValue(entryIndex, classRef);
  1074         if (classRef[0] != null) {
  1075             addReference(classRef[0]);
  1076         }
  1077         return s;
  1078     }
  1079 
  1080     private String javaScriptBody(String prefix, MethodData m, boolean isStatic) throws IOException {
  1081         byte[] arr = m.findAnnotationData(true);
  1082         if (arr == null) {
  1083             return null;
  1084         }
  1085         final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
  1086         class P extends AnnotationParser {
  1087             public P() {
  1088                 super(false);
  1089             }
  1090             
  1091             int cnt;
  1092             String[] args = new String[30];
  1093             String body;
  1094             
  1095             @Override
  1096             protected void visitAttr(String type, String attr, String at, String value) {
  1097                 if (type.equals(jvmType)) {
  1098                     if ("body".equals(attr)) {
  1099                         body = value;
  1100                     } else if ("args".equals(attr)) {
  1101                         args[cnt++] = value;
  1102                     } else {
  1103                         throw new IllegalArgumentException(attr);
  1104                     }
  1105                 }
  1106             }
  1107         }
  1108         P p = new P();
  1109         p.parse(arr, jc);
  1110         if (p.body == null) {
  1111             return null;
  1112         }
  1113         StringBuilder cnt = new StringBuilder();
  1114         final String mn = findMethodName(m, cnt);
  1115         out.append(prefix).append(mn);
  1116         out.append(" = function(");
  1117         String space;
  1118         int index;
  1119         if (!isStatic) {                
  1120             out.append(p.args[0]);
  1121             space = ",";
  1122             index = 1;
  1123         } else {
  1124             space = "";
  1125             index = 0;
  1126         }
  1127         for (int i = 0; i < cnt.length(); i++) {
  1128             out.append(space);
  1129             out.append(p.args[index]);
  1130             index++;
  1131             space = ",";
  1132         }
  1133         out.append(") {").append("\n");
  1134         out.append(p.body);
  1135         out.append("\n}\n");
  1136         return mn;
  1137     }
  1138     private static String className(ClassData jc) {
  1139         //return jc.getName().getInternalName().replace('/', '_');
  1140         return jc.getClassName().replace('/', '_');
  1141     }
  1142     
  1143     private static String[] findAnnotation(
  1144         byte[] arr, ClassData cd, final String className, 
  1145         final String... attrNames
  1146     ) throws IOException {
  1147         if (arr == null) {
  1148             return null;
  1149         }
  1150         final String[] values = new String[attrNames.length];
  1151         final boolean[] found = { false };
  1152         final String jvmType = "L" + className.replace('.', '/') + ";";
  1153         AnnotationParser ap = new AnnotationParser(false) {
  1154             @Override
  1155             protected void visitAttr(String type, String attr, String at, String value) {
  1156                 if (type.equals(jvmType)) {
  1157                     found[0] = true;
  1158                     for (int i = 0; i < attrNames.length; i++) {
  1159                         if (attrNames[i].equals(attr)) {
  1160                             values[i] = value;
  1161                         }
  1162                     }
  1163                 }
  1164             }
  1165             
  1166         };
  1167         ap.parse(arr, cd);
  1168         return found[0] ? values : null;
  1169     }
  1170 
  1171     private CharSequence initField(FieldData v) {
  1172         final String is = v.getInternalSig();
  1173         if (is.length() == 1) {
  1174             switch (is.charAt(0)) {
  1175                 case 'S':
  1176                 case 'J':
  1177                 case 'B':
  1178                 case 'Z':
  1179                 case 'C':
  1180                 case 'I': return " = 0;";
  1181                 case 'F': 
  1182                 case 'D': return " = 0.0;";
  1183                 default:
  1184                     throw new IllegalStateException(is);
  1185             }
  1186         }
  1187         return " = null;";
  1188     }
  1189 
  1190     private static void generateAnno(ClassData cd, final Appendable out, byte[] data) throws IOException {
  1191         AnnotationParser ap = new AnnotationParser(true) {
  1192             int anno;
  1193             int cnt;
  1194             
  1195             @Override
  1196             protected void visitAnnotationStart(String type) throws IOException {
  1197                 if (anno++ > 0) {
  1198                     out.append(",");
  1199                 }
  1200                 out.append('"').append(type).append("\" : {\n");
  1201                 cnt = 0;
  1202             }
  1203 
  1204             @Override
  1205             protected void visitAnnotationEnd(String type) throws IOException {
  1206                 out.append("\n}\n");
  1207             }
  1208             
  1209             @Override
  1210             protected void visitAttr(String type, String attr, String attrType, String value) 
  1211             throws IOException {
  1212                 if (attr == null) {
  1213                     return;
  1214                 }
  1215                 if (cnt++ > 0) {
  1216                     out.append(",\n");
  1217                 }
  1218                 out.append(attr).append("__").append(attrType).append(" : ").append(value);
  1219             }
  1220         };
  1221         ap.parse(data, cd);
  1222     }
  1223 }