vm/src/main/java/org/apidesign/vm4brwsr/ByteCodeToJavaScript.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Mon, 24 Dec 2012 08:19:55 +0100
branchexceptions
changeset 376 059cb07ac9b3
parent 358 f6a165f7f00f
parent 292 fc3f6ea5e246
child 392 44a5802816be
child 407 b2f68438b0e2
permissions -rw-r--r--
Initial attempt to merge current default branch with exceptions
     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 org.apidesign.javap.StackMapIterator;
    27 import static org.apidesign.javap.RuntimeConstants.*;
    28 import org.apidesign.javap.TrapData;
    29 import org.apidesign.javap.TrapDataIterator;
    30 
    31 /** Translator of the code inside class files to JavaScript.
    32  *
    33  * @author Jaroslav Tulach <jtulach@netbeans.org>
    34  */
    35 abstract class ByteCodeToJavaScript {
    36     private ClassData jc;
    37     final Appendable out;
    38 
    39     protected ByteCodeToJavaScript(Appendable out) {
    40         this.out = out;
    41     }
    42     
    43     /* Collects additional required resources.
    44      * 
    45      * @param internalClassName classes that were referenced and should be loaded in order the
    46      *   generated JavaScript code works properly. The names are in internal 
    47      *   JVM form so String is <code>java/lang/String</code>. 
    48      */
    49     protected abstract boolean requireReference(String internalClassName);
    50     
    51     /*
    52      * @param resourcePath name of resources to read
    53      */
    54     protected abstract void requireScript(String resourcePath);
    55     
    56     /** Allows subclasses to redefine what field a function representing a
    57      * class gets assigned. By default it returns the suggested name followed
    58      * by <code>" = "</code>;
    59      * 
    60      * @param className suggested name of the class
    61      */
    62     /* protected */ String assignClass(String className) {
    63         return className + " = ";
    64     }
    65     /* protected */ String accessClass(String classOperation) {
    66         return classOperation;
    67     }
    68 
    69     /**
    70      * Converts a given class file to a JavaScript version.
    71      *
    72      * @param classFile input stream with code of the .class file
    73      * @return the initialization code for this class, if any. Otherwise <code>null</code>
    74      * 
    75      * @throws IOException if something goes wrong during read or write or translating
    76      */
    77     
    78     public String compile(InputStream classFile) throws IOException {
    79         this.jc = new ClassData(classFile);
    80         if (jc.getMajor_version() < 50) {
    81             throw new IOException("Can't compile " + jc.getClassName() + ". Class file version " + jc.getMajor_version() + "."
    82                 + jc.getMinor_version() + " - recompile with -target 1.6 (at least)."
    83             );
    84         }
    85         byte[] arrData = jc.findAnnotationData(true);
    86         String[] arr = findAnnotation(arrData, jc, 
    87             "org.apidesign.bck2brwsr.core.ExtraJavaScript", 
    88             "resource", "processByteCode"
    89         );
    90         if (arr != null) {
    91             requireScript(arr[0]);
    92             if ("0".equals(arr[1])) {
    93                 return null;
    94             }
    95         }
    96         String[] proto = findAnnotation(arrData, jc, 
    97             "org.apidesign.bck2brwsr.core.JavaScriptPrototype", 
    98             "container", "prototype"
    99         );
   100         StringArray toInitilize = new StringArray();
   101         final String className = className(jc);
   102         out.append("\n\n").append(assignClass(className));
   103         out.append("function CLS() {");
   104         out.append("\n  if (!CLS.prototype.$instOf_").append(className).append(") {");
   105         for (FieldData v : jc.getFields()) {
   106             if (v.isStatic()) {
   107                 out.append("\n  CLS.").append(v.getName()).append(initField(v));
   108             }
   109         }
   110         if (proto == null) {
   111             String sc = jc.getSuperClassName(); // with _
   112             out.append("\n    var pp = ").
   113                 append(accessClass(sc.replace('/', '_'))).append("(true);");
   114             out.append("\n    var p = CLS.prototype = pp;");
   115             out.append("\n    var c = p;");
   116             out.append("\n    var sprcls = pp.constructor.$class;");
   117         } else {
   118             out.append("\n    var p = CLS.prototype = ").append(proto[1]).append(";");
   119             if (proto[0] == null) {
   120                 proto[0] = "p";
   121             }
   122             out.append("\n    var c = ").append(proto[0]).append(";");
   123             out.append("\n    var sprcls = null;");
   124         }
   125         for (MethodData m : jc.getMethods()) {
   126             byte[] onlyArr = m.findAnnotationData(true);
   127             String[] only = findAnnotation(onlyArr, jc, 
   128                 "org.apidesign.bck2brwsr.core.JavaScriptOnly", 
   129                 "name", "value"
   130             );
   131             if (only != null) {
   132                 if (only[0] != null && only[1] != null) {
   133                     out.append("\n    p.").append(only[0]).append(" = ")
   134                         .append(only[1]).append(";");
   135                 }
   136                 continue;
   137             }
   138             String mn;
   139             if (m.isStatic()) {
   140                 mn = generateStaticMethod("\n    c.", m, toInitilize);
   141             } else {
   142                 mn = generateInstanceMethod("\n    c.", m);
   143             }
   144             byte[] runAnno = m.findAnnotationData(false);
   145             if (runAnno != null) {
   146                 out.append("\n    c.").append(mn).append(".anno = {");
   147                 generateAnno(jc, out, runAnno);
   148                 out.append("\n    };");
   149             }
   150         }
   151         out.append("\n    c.constructor = CLS;");
   152         out.append("\n    c.$instOf_").append(className).append(" = true;");
   153         for (String superInterface : jc.getSuperInterfaces()) {
   154             out.append("\n    c.$instOf_").append(superInterface.replace('/', '_')).append(" = true;");
   155         }
   156         out.append("\n    CLS.$class = ");
   157         out.append(accessClass("java_lang_Class(true);"));
   158         out.append("\n    CLS.$class.jvmName = '").append(jc.getClassName()).append("';");
   159         out.append("\n    CLS.$class.superclass = sprcls;");
   160         out.append("\n    CLS.$class.access = ").append(jc.getAccessFlags()+";");
   161         out.append("\n    CLS.$class.cnstr = CLS;");
   162         byte[] classAnno = jc.findAnnotationData(false);
   163         if (classAnno != null) {
   164             out.append("\n    CLS.$class.anno = {");
   165             generateAnno(jc, out, classAnno);
   166             out.append("\n    };");
   167         }
   168         out.append("\n  }");
   169         out.append("\n  if (arguments.length === 0) {");
   170         out.append("\n    if (!(this instanceof CLS)) {");
   171         out.append("\n      return new CLS();");
   172         out.append("\n    }");
   173         for (FieldData v : jc.getFields()) {
   174             byte[] onlyArr = v.findAnnotationData(true);
   175             String[] only = findAnnotation(onlyArr, jc, 
   176                 "org.apidesign.bck2brwsr.core.JavaScriptOnly", 
   177                 "name", "value"
   178             );
   179             if (only != null) {
   180                 if (only[0] != null && only[1] != null) {
   181                     out.append("\n    p.").append(only[0]).append(" = ")
   182                         .append(only[1]).append(";");
   183                 }
   184                 continue;
   185             }
   186             if (!v.isStatic()) {
   187                 out.append("\n    this.fld_").
   188                     append(v.getName()).append(initField(v));
   189             }
   190         }
   191         out.append("\n    return this;");
   192         out.append("\n  }");
   193         out.append("\n  return arguments[0] ? new CLS() : CLS.prototype;");
   194         out.append("\n}");
   195         StringBuilder sb = new StringBuilder();
   196         for (String init : toInitilize.toArray()) {
   197             sb.append("\n").append(init).append("();");
   198         }
   199         return sb.toString();
   200     }
   201     private String generateStaticMethod(String prefix, MethodData m, StringArray toInitilize) throws IOException {
   202         String jsb = javaScriptBody(prefix, m, true);
   203         if (jsb != null) {
   204             return jsb;
   205         }
   206         final String mn = findMethodName(m, new StringBuilder());
   207         if (mn.equals("class__V")) {
   208             toInitilize.add(accessClass(className(jc)) + "(false)." + mn);
   209         }
   210         generateMethod(prefix, mn, m);
   211         return mn;
   212     }
   213 
   214     private String generateInstanceMethod(String prefix, MethodData m) throws IOException {
   215         String jsb = javaScriptBody(prefix, m, false);
   216         if (jsb != null) {
   217             return jsb;
   218         }
   219         final String mn = findMethodName(m, new StringBuilder());
   220         generateMethod(prefix, mn, m);
   221         return mn;
   222     }
   223 
   224     private void generateMethod(String prefix, String name, MethodData m)
   225             throws IOException {
   226         final StackMapIterator stackMapIterator = m.createStackMapIterator();
   227         TrapDataIterator trap = m.getTrapDataIterator();
   228         final LocalsMapper lmapper =
   229                 new LocalsMapper(stackMapIterator.getArguments());
   230 
   231         out.append(prefix).append(name).append(" = function(");
   232         lmapper.outputArguments(out);
   233         out.append(") {").append("\n");
   234 
   235         final byte[] byteCodes = m.getCode();
   236         if (byteCodes == null) {
   237             out.append("  throw 'no code found for ")
   238                .append(m.getInternalSig()).append("';\n");
   239             out.append("};");
   240             return;
   241         }
   242 
   243         final StackMapper smapper = new StackMapper();
   244 
   245         final int maxLocals = m.getMaxLocals();
   246         if (maxLocals > 0) {
   247             // TODO: generate only used local variables
   248             for (int j = 0; j <= VarType.LAST; ++j) {
   249                 out.append("\n  var ").append(Variable.getLocalVariable(j, 0));
   250                 for (int i = 1; i < maxLocals; ++i) {
   251                     out.append(", ");
   252                     out.append(Variable.getLocalVariable(j, i));
   253                 }
   254                 out.append(';');
   255             }
   256         }
   257 
   258         // maxStack includes two stack positions for every pushed long / double
   259         // so this might generate more stack variables than we need
   260         final int maxStack = m.getMaxStack();
   261         if (maxStack > 0) {
   262             // TODO: generate only used stack variables
   263             for (int j = 0; j <= VarType.LAST; ++j) {
   264                 out.append("\n  var ").append(Variable.getStackVariable(j, 0));
   265                 for (int i = 1; i < maxStack; ++i) {
   266                     out.append(", ");
   267                     out.append(Variable.getStackVariable(j, i));
   268                 }
   269                 out.append(';');
   270             }
   271         }
   272 
   273         int lastStackFrame = -1;
   274 
   275         out.append("\n  var gt = 0;\n  for(;;) switch(gt) {\n");
   276         for (int i = 0; i < byteCodes.length; i++) {
   277             int prev = i;
   278             stackMapIterator.advanceTo(i);
   279             trap.advanceTo(i);
   280             if (lastStackFrame != stackMapIterator.getFrameIndex()) {
   281                 lastStackFrame = stackMapIterator.getFrameIndex();
   282                 lmapper.syncWithFrameLocals(stackMapIterator.getFrameLocals());
   283                 smapper.syncWithFrameStack(stackMapIterator.getFrameStack());
   284                 out.append("    case " + i).append(": ");            
   285             } else {
   286                 out.append("    /* " + i).append(" */ ");
   287             }
   288             if (trap.useTry()) {
   289                 out.append("try {");
   290             }
   291             final int c = readByte(byteCodes, i);
   292             switch (c) {
   293                 case opc_aload_0:
   294                     emit(out, "@1 = @2;", smapper.pushA(), lmapper.getA(0));
   295                     break;
   296                 case opc_iload_0:
   297                     emit(out, "@1 = @2;", smapper.pushI(), lmapper.getI(0));
   298                     break;
   299                 case opc_lload_0:
   300                     emit(out, "@1 = @2;", smapper.pushL(), lmapper.getL(0));
   301                     break;
   302                 case opc_fload_0:
   303                     emit(out, "@1 = @2;", smapper.pushF(), lmapper.getF(0));
   304                     break;
   305                 case opc_dload_0:
   306                     emit(out, "@1 = @2;", smapper.pushD(), lmapper.getD(0));
   307                     break;
   308                 case opc_aload_1:
   309                     emit(out, "@1 = @2;", smapper.pushA(), lmapper.getA(1));
   310                     break;
   311                 case opc_iload_1:
   312                     emit(out, "@1 = @2;", smapper.pushI(), lmapper.getI(1));
   313                     break;
   314                 case opc_lload_1:
   315                     emit(out, "@1 = @2;", smapper.pushL(), lmapper.getL(1));
   316                     break;
   317                 case opc_fload_1:
   318                     emit(out, "@1 = @2;", smapper.pushF(), lmapper.getF(1));
   319                     break;
   320                 case opc_dload_1:
   321                     emit(out, "@1 = @2;", smapper.pushD(), lmapper.getD(1));
   322                     break;
   323                 case opc_aload_2:
   324                     emit(out, "@1 = @2;", smapper.pushA(), lmapper.getA(2));
   325                     break;
   326                 case opc_iload_2:
   327                     emit(out, "@1 = @2;", smapper.pushI(), lmapper.getI(2));
   328                     break;
   329                 case opc_lload_2:
   330                     emit(out, "@1 = @2;", smapper.pushL(), lmapper.getL(2));
   331                     break;
   332                 case opc_fload_2:
   333                     emit(out, "@1 = @2;", smapper.pushF(), lmapper.getF(2));
   334                     break;
   335                 case opc_dload_2:
   336                     emit(out, "@1 = @2;", smapper.pushD(), lmapper.getD(2));
   337                     break;
   338                 case opc_aload_3:
   339                     emit(out, "@1 = @2;", smapper.pushA(), lmapper.getA(3));
   340                     break;
   341                 case opc_iload_3:
   342                     emit(out, "@1 = @2;", smapper.pushI(), lmapper.getI(3));
   343                     break;
   344                 case opc_lload_3:
   345                     emit(out, "@1 = @2;", smapper.pushL(), lmapper.getL(3));
   346                     break;
   347                 case opc_fload_3:
   348                     emit(out, "@1 = @2;", smapper.pushF(), lmapper.getF(3));
   349                     break;
   350                 case opc_dload_3:
   351                     emit(out, "@1 = @2;", smapper.pushD(), lmapper.getD(3));
   352                     break;
   353                 case opc_iload: {
   354                     final int indx = readByte(byteCodes, ++i);
   355                     emit(out, "@1 = @2;", smapper.pushI(), lmapper.getI(indx));
   356                     break;
   357                 }
   358                 case opc_lload: {
   359                     final int indx = readByte(byteCodes, ++i);
   360                     emit(out, "@1 = @2;", smapper.pushL(), lmapper.getL(indx));
   361                     break;
   362                 }
   363                 case opc_fload: {
   364                     final int indx = readByte(byteCodes, ++i);
   365                     emit(out, "@1 = @2;", smapper.pushF(), lmapper.getF(indx));
   366                     break;
   367                 }
   368                 case opc_dload: {
   369                     final int indx = readByte(byteCodes, ++i);
   370                     emit(out, "@1 = @2;", smapper.pushD(), lmapper.getD(indx));
   371                     break;
   372                 }
   373                 case opc_aload: {
   374                     final int indx = readByte(byteCodes, ++i);
   375                     emit(out, "@1 = @2;", smapper.pushA(), lmapper.getA(indx));
   376                     break;
   377                 }
   378                 case opc_istore: {
   379                     final int indx = readByte(byteCodes, ++i);
   380                     emit(out, "@1 = @2;", lmapper.setI(indx), smapper.popI());
   381                     break;
   382                 }
   383                 case opc_lstore: {
   384                     final int indx = readByte(byteCodes, ++i);
   385                     emit(out, "@1 = @2;", lmapper.setL(indx), smapper.popL());
   386                     break;
   387                 }
   388                 case opc_fstore: {
   389                     final int indx = readByte(byteCodes, ++i);
   390                     emit(out, "@1 = @2;", lmapper.setF(indx), smapper.popF());
   391                     break;
   392                 }
   393                 case opc_dstore: {
   394                     final int indx = readByte(byteCodes, ++i);
   395                     emit(out, "@1 = @2;", lmapper.setD(indx), smapper.popD());
   396                     break;
   397                 }
   398                 case opc_astore: {
   399                     final int indx = readByte(byteCodes, ++i);
   400                     emit(out, "@1 = @2;", lmapper.setA(indx), smapper.popA());
   401                     break;
   402                 }
   403                 case opc_astore_0:
   404                     emit(out, "@1 = @2;", lmapper.setA(0), smapper.popA());
   405                     break;
   406                 case opc_istore_0:
   407                     emit(out, "@1 = @2;", lmapper.setI(0), smapper.popI());
   408                     break;
   409                 case opc_lstore_0:
   410                     emit(out, "@1 = @2;", lmapper.setL(0), smapper.popL());
   411                     break;
   412                 case opc_fstore_0:
   413                     emit(out, "@1 = @2;", lmapper.setF(0), smapper.popF());
   414                     break;
   415                 case opc_dstore_0:
   416                     emit(out, "@1 = @2;", lmapper.setD(0), smapper.popD());
   417                     break;
   418                 case opc_astore_1:
   419                     emit(out, "@1 = @2;", lmapper.setA(1), smapper.popA());
   420                     break;
   421                 case opc_istore_1:
   422                     emit(out, "@1 = @2;", lmapper.setI(1), smapper.popI());
   423                     break;
   424                 case opc_lstore_1:
   425                     emit(out, "@1 = @2;", lmapper.setL(1), smapper.popL());
   426                     break;
   427                 case opc_fstore_1:
   428                     emit(out, "@1 = @2;", lmapper.setF(1), smapper.popF());
   429                     break;
   430                 case opc_dstore_1:
   431                     emit(out, "@1 = @2;", lmapper.setD(1), smapper.popD());
   432                     break;
   433                 case opc_astore_2:
   434                     emit(out, "@1 = @2;", lmapper.setA(2), smapper.popA());
   435                     break;
   436                 case opc_istore_2:
   437                     emit(out, "@1 = @2;", lmapper.setI(2), smapper.popI());
   438                     break;
   439                 case opc_lstore_2:
   440                     emit(out, "@1 = @2;", lmapper.setL(2), smapper.popL());
   441                     break;
   442                 case opc_fstore_2:
   443                     emit(out, "@1 = @2;", lmapper.setF(2), smapper.popF());
   444                     break;
   445                 case opc_dstore_2:
   446                     emit(out, "@1 = @2;", lmapper.setD(2), smapper.popD());
   447                     break;
   448                 case opc_astore_3:
   449                     emit(out, "@1 = @2;", lmapper.setA(3), smapper.popA());
   450                     break;
   451                 case opc_istore_3:
   452                     emit(out, "@1 = @2;", lmapper.setI(3), smapper.popI());
   453                     break;
   454                 case opc_lstore_3:
   455                     emit(out, "@1 = @2;", lmapper.setL(3), smapper.popL());
   456                     break;
   457                 case opc_fstore_3:
   458                     emit(out, "@1 = @2;", lmapper.setF(3), smapper.popF());
   459                     break;
   460                 case opc_dstore_3:
   461                     emit(out, "@1 = @2;", lmapper.setD(3), smapper.popD());
   462                     break;
   463                 case opc_iadd:
   464                     emit(out, "@1 += @2;", smapper.getI(1), smapper.popI());
   465                     break;
   466                 case opc_ladd:
   467                     emit(out, "@1 += @2;", smapper.getL(1), smapper.popL());
   468                     break;
   469                 case opc_fadd:
   470                     emit(out, "@1 += @2;", smapper.getF(1), smapper.popF());
   471                     break;
   472                 case opc_dadd:
   473                     emit(out, "@1 += @2;", smapper.getD(1), smapper.popD());
   474                     break;
   475                 case opc_isub:
   476                     emit(out, "@1 -= @2;", smapper.getI(1), smapper.popI());
   477                     break;
   478                 case opc_lsub:
   479                     emit(out, "@1 -= @2;", smapper.getL(1), smapper.popL());
   480                     break;
   481                 case opc_fsub:
   482                     emit(out, "@1 -= @2;", smapper.getF(1), smapper.popF());
   483                     break;
   484                 case opc_dsub:
   485                     emit(out, "@1 -= @2;", smapper.getD(1), smapper.popD());
   486                     break;
   487                 case opc_imul:
   488                     emit(out, "@1 *= @2;", smapper.getI(1), smapper.popI());
   489                     break;
   490                 case opc_lmul:
   491                     emit(out, "@1 *= @2;", smapper.getL(1), smapper.popL());
   492                     break;
   493                 case opc_fmul:
   494                     emit(out, "@1 *= @2;", smapper.getF(1), smapper.popF());
   495                     break;
   496                 case opc_dmul:
   497                     emit(out, "@1 *= @2;", smapper.getD(1), smapper.popD());
   498                     break;
   499                 case opc_idiv:
   500                     emit(out, "@1 = Math.floor(@1 / @2);",
   501                          smapper.getI(1), smapper.popI());
   502                     break;
   503                 case opc_ldiv:
   504                     emit(out, "@1 = Math.floor(@1 / @2);",
   505                          smapper.getL(1), smapper.popL());
   506                     break;
   507                 case opc_fdiv:
   508                     emit(out, "@1 /= @2;", smapper.getF(1), smapper.popF());
   509                     break;
   510                 case opc_ddiv:
   511                     emit(out, "@1 /= @2;", smapper.getD(1), smapper.popD());
   512                     break;
   513                 case opc_irem:
   514                     emit(out, "@1 %= @2;", smapper.getI(1), smapper.popI());
   515                     break;
   516                 case opc_lrem:
   517                     emit(out, "@1 %= @2;", smapper.getL(1), smapper.popL());
   518                     break;
   519                 case opc_frem:
   520                     emit(out, "@1 %= @2;", smapper.getF(1), smapper.popF());
   521                     break;
   522                 case opc_drem:
   523                     emit(out, "@1 %= @2;", smapper.getD(1), smapper.popD());
   524                     break;
   525                 case opc_iand:
   526                     emit(out, "@1 &= @2;", smapper.getI(1), smapper.popI());
   527                     break;
   528                 case opc_land:
   529                     emit(out, "@1 &= @2;", smapper.getL(1), smapper.popL());
   530                     break;
   531                 case opc_ior:
   532                     emit(out, "@1 |= @2;", smapper.getI(1), smapper.popI());
   533                     break;
   534                 case opc_lor:
   535                     emit(out, "@1 |= @2;", smapper.getL(1), smapper.popL());
   536                     break;
   537                 case opc_ixor:
   538                     emit(out, "@1 ^= @2;", smapper.getI(1), smapper.popI());
   539                     break;
   540                 case opc_lxor:
   541                     emit(out, "@1 ^= @2;", smapper.getL(1), smapper.popL());
   542                     break;
   543                 case opc_ineg:
   544                     emit(out, "@1 = -@1;", smapper.getI(0));
   545                     break;
   546                 case opc_lneg:
   547                     emit(out, "@1 = -@1;", smapper.getL(0));
   548                     break;
   549                 case opc_fneg:
   550                     emit(out, "@1 = -@1;", smapper.getF(0));
   551                     break;
   552                 case opc_dneg:
   553                     emit(out, "@1 = -@1;", smapper.getD(0));
   554                     break;
   555                 case opc_ishl:
   556                     emit(out, "@1 <<= @2;", smapper.getI(1), smapper.popI());
   557                     break;
   558                 case opc_lshl:
   559                     emit(out, "@1 <<= @2;", smapper.getL(1), smapper.popI());
   560                     break;
   561                 case opc_ishr:
   562                     emit(out, "@1 >>= @2;", smapper.getI(1), smapper.popI());
   563                     break;
   564                 case opc_lshr:
   565                     emit(out, "@1 >>= @2;", smapper.getL(1), smapper.popI());
   566                     break;
   567                 case opc_iushr:
   568                     emit(out, "@1 >>>= @2;", smapper.getI(1), smapper.popI());
   569                     break;
   570                 case opc_lushr:
   571                     emit(out, "@1 >>>= @2;", smapper.getL(1), smapper.popI());
   572                     break;
   573                 case opc_iinc: {
   574                     final int varIndx = readByte(byteCodes, ++i);
   575                     final int incrBy = byteCodes[++i];
   576                     if (incrBy == 1) {
   577                         emit(out, "@1++;", lmapper.getI(varIndx));
   578                     } else {
   579                         emit(out, "@1 += @2;",
   580                              lmapper.getI(varIndx),
   581                              Integer.toString(incrBy));
   582                     }
   583                     break;
   584                 }
   585                 case opc_return:
   586                     emit(out, "return;");
   587                     break;
   588                 case opc_ireturn:
   589                     emit(out, "return @1;", smapper.popI());
   590                     break;
   591                 case opc_lreturn:
   592                     emit(out, "return @1;", smapper.popL());
   593                     break;
   594                 case opc_freturn:
   595                     emit(out, "return @1;", smapper.popF());
   596                     break;
   597                 case opc_dreturn:
   598                     emit(out, "return @1;", smapper.popD());
   599                     break;
   600                 case opc_areturn:
   601                     emit(out, "return @1;", smapper.popA());
   602                     break;
   603                 case opc_i2l:
   604                     emit(out, "@2 = @1;", smapper.popI(), smapper.pushL());
   605                     break;
   606                 case opc_i2f:
   607                     emit(out, "@2 = @1;", smapper.popI(), smapper.pushF());
   608                     break;
   609                 case opc_i2d:
   610                     emit(out, "@2 = @1;", smapper.popI(), smapper.pushD());
   611                     break;
   612                 case opc_l2i:
   613                     emit(out, "@2 = @1;", smapper.popL(), smapper.pushI());
   614                     break;
   615                     // max int check?
   616                 case opc_l2f:
   617                     emit(out, "@2 = @1;", smapper.popL(), smapper.pushF());
   618                     break;
   619                 case opc_l2d:
   620                     emit(out, "@2 = @1;", smapper.popL(), smapper.pushD());
   621                     break;
   622                 case opc_f2d:
   623                     emit(out, "@2 = @1;", smapper.popF(), smapper.pushD());
   624                     break;
   625                 case opc_d2f:
   626                     emit(out, "@2 = @1;", smapper.popD(), smapper.pushF());
   627                     break;
   628                 case opc_f2i:
   629                     emit(out, "@2 = Math.floor(@1);",
   630                          smapper.popF(), smapper.pushI());
   631                     break;
   632                 case opc_f2l:
   633                     emit(out, "@2 = Math.floor(@1);",
   634                          smapper.popF(), smapper.pushL());
   635                     break;
   636                 case opc_d2i:
   637                     emit(out, "@2 = Math.floor(@1);",
   638                          smapper.popD(), smapper.pushI());
   639                     break;
   640                 case opc_d2l:
   641                     emit(out, "@2 = Math.floor(@1);",
   642                          smapper.popD(), smapper.pushL());
   643                     break;
   644                 case opc_i2b:
   645                 case opc_i2c:
   646                 case opc_i2s:
   647                     out.append("{ /* number conversion */ }");
   648                     break;
   649                 case opc_aconst_null:
   650                     emit(out, "@1 = null;", smapper.pushA());
   651                     break;
   652                 case opc_iconst_m1:
   653                     emit(out, "@1 = -1;", smapper.pushI());
   654                     break;
   655                 case opc_iconst_0:
   656                     emit(out, "@1 = 0;", smapper.pushI());
   657                     break;
   658                 case opc_dconst_0:
   659                     emit(out, "@1 = 0;", smapper.pushD());
   660                     break;
   661                 case opc_lconst_0:
   662                     emit(out, "@1 = 0;", smapper.pushL());
   663                     break;
   664                 case opc_fconst_0:
   665                     emit(out, "@1 = 0;", smapper.pushF());
   666                     break;
   667                 case opc_iconst_1:
   668                     emit(out, "@1 = 1;", smapper.pushI());
   669                     break;
   670                 case opc_lconst_1:
   671                     emit(out, "@1 = 1;", smapper.pushL());
   672                     break;
   673                 case opc_fconst_1:
   674                     emit(out, "@1 = 1;", smapper.pushF());
   675                     break;
   676                 case opc_dconst_1:
   677                     emit(out, "@1 = 1;", smapper.pushD());
   678                     break;
   679                 case opc_iconst_2:
   680                     emit(out, "@1 = 2;", smapper.pushI());
   681                     break;
   682                 case opc_fconst_2:
   683                     emit(out, "@1 = 2;", smapper.pushF());
   684                     break;
   685                 case opc_iconst_3:
   686                     emit(out, "@1 = 3;", smapper.pushI());
   687                     break;
   688                 case opc_iconst_4:
   689                     emit(out, "@1 = 4;", smapper.pushI());
   690                     break;
   691                 case opc_iconst_5:
   692                     emit(out, "@1 = 5;", smapper.pushI());
   693                     break;
   694                 case opc_ldc: {
   695                     int indx = readByte(byteCodes, ++i);
   696                     String v = encodeConstant(indx);
   697                     int type = VarType.fromConstantType(jc.getTag(indx));
   698                     emit(out, "@1 = @2;", smapper.pushT(type), v);
   699                     break;
   700                 }
   701                 case opc_ldc_w:
   702                 case opc_ldc2_w: {
   703                     int indx = readIntArg(byteCodes, i);
   704                     i += 2;
   705                     String v = encodeConstant(indx);
   706                     int type = VarType.fromConstantType(jc.getTag(indx));
   707                     emit(out, "@1 = @2;", smapper.pushT(type), v);
   708                     break;
   709                 }
   710                 case opc_lcmp:
   711                     emit(out, "@3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
   712                          smapper.popL(), smapper.popL(), smapper.pushI());
   713                     break;
   714                 case opc_fcmpl:
   715                 case opc_fcmpg:
   716                     emit(out, "@3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
   717                          smapper.popF(), smapper.popF(), smapper.pushI());
   718                     break;
   719                 case opc_dcmpl:
   720                 case opc_dcmpg:
   721                     emit(out, "@3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
   722                          smapper.popD(), smapper.popD(), smapper.pushI());
   723                     break;
   724                 case opc_if_acmpeq:
   725                     i = generateIf(byteCodes, i, smapper.popA(), smapper.popA(),
   726                                    "===");
   727                     break;
   728                 case opc_if_acmpne:
   729                     i = generateIf(byteCodes, i, smapper.popA(), smapper.popA(),
   730                                    "!=");
   731                     break;
   732                 case opc_if_icmpeq:
   733                     i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
   734                                    "==");
   735                     break;
   736                 case opc_ifeq: {
   737                     int indx = i + readIntArg(byteCodes, i);
   738                     emit(out, "if (@1 == 0) { gt = @2; continue; }",
   739                          smapper.popI(), Integer.toString(indx));
   740                     i += 2;
   741                     break;
   742                 }
   743                 case opc_ifne: {
   744                     int indx = i + readIntArg(byteCodes, i);
   745                     emit(out, "if (@1 != 0) { gt = @2; continue; }",
   746                          smapper.popI(), Integer.toString(indx));
   747                     i += 2;
   748                     break;
   749                 }
   750                 case opc_iflt: {
   751                     int indx = i + readIntArg(byteCodes, i);
   752                     emit(out, "if (@1 < 0) { gt = @2; continue; }",
   753                          smapper.popI(), Integer.toString(indx));
   754                     i += 2;
   755                     break;
   756                 }
   757                 case opc_ifle: {
   758                     int indx = i + readIntArg(byteCodes, i);
   759                     emit(out, "if (@1 <= 0) { gt = @2; continue; }",
   760                          smapper.popI(), Integer.toString(indx));
   761                     i += 2;
   762                     break;
   763                 }
   764                 case opc_ifgt: {
   765                     int indx = i + readIntArg(byteCodes, i);
   766                     emit(out, "if (@1 > 0) { gt = @2; continue; }",
   767                          smapper.popI(), Integer.toString(indx));
   768                     i += 2;
   769                     break;
   770                 }
   771                 case opc_ifge: {
   772                     int indx = i + readIntArg(byteCodes, i);
   773                     emit(out, "if (@1 >= 0) { gt = @2; continue; }",
   774                          smapper.popI(), Integer.toString(indx));
   775                     i += 2;
   776                     break;
   777                 }
   778                 case opc_ifnonnull: {
   779                     int indx = i + readIntArg(byteCodes, i);
   780                     emit(out, "if (@1 !== null) { gt = @2; continue; }",
   781                          smapper.popA(), Integer.toString(indx));
   782                     i += 2;
   783                     break;
   784                 }
   785                 case opc_ifnull: {
   786                     int indx = i + readIntArg(byteCodes, i);
   787                     emit(out, "if (@1 === null) { gt = @2; continue; }",
   788                          smapper.popA(), Integer.toString(indx));
   789                     i += 2;
   790                     break;
   791                 }
   792                 case opc_if_icmpne:
   793                     i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
   794                                    "!=");
   795                     break;
   796                 case opc_if_icmplt:
   797                     i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
   798                                    "<");
   799                     break;
   800                 case opc_if_icmple:
   801                     i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
   802                                    "<=");
   803                     break;
   804                 case opc_if_icmpgt:
   805                     i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
   806                                    ">");
   807                     break;
   808                 case opc_if_icmpge:
   809                     i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
   810                                    ">=");
   811                     break;
   812                 case opc_goto: {
   813                     int indx = i + readIntArg(byteCodes, i);
   814                     emit(out, "gt = @1; continue;", Integer.toString(indx));
   815                     i += 2;
   816                     break;
   817                 }
   818                 case opc_lookupswitch: {
   819                     int table = i / 4 * 4 + 4;
   820                     int dflt = i + readInt4(byteCodes, table);
   821                     table += 4;
   822                     int n = readInt4(byteCodes, table);
   823                     table += 4;
   824                     out.append("switch (").append(smapper.popI()).append(") {\n");
   825                     while (n-- > 0) {
   826                         int cnstnt = readInt4(byteCodes, table);
   827                         table += 4;
   828                         int offset = i + readInt4(byteCodes, table);
   829                         table += 4;
   830                         out.append("  case " + cnstnt).append(": gt = " + offset).append("; continue;\n");
   831                     }
   832                     out.append("  default: gt = " + dflt).append("; continue;\n}");
   833                     i = table - 1;
   834                     break;
   835                 }
   836                 case opc_tableswitch: {
   837                     int table = i / 4 * 4 + 4;
   838                     int dflt = i + readInt4(byteCodes, table);
   839                     table += 4;
   840                     int low = readInt4(byteCodes, table);
   841                     table += 4;
   842                     int high = readInt4(byteCodes, table);
   843                     table += 4;
   844                     out.append("switch (").append(smapper.popI()).append(") {\n");
   845                     while (low <= high) {
   846                         int offset = i + readInt4(byteCodes, table);
   847                         table += 4;
   848                         out.append("  case " + low).append(": gt = " + offset).append("; continue;\n");
   849                         low++;
   850                     }
   851                     out.append("  default: gt = " + dflt).append("; continue;\n}");
   852                     i = table - 1;
   853                     break;
   854                 }
   855                 case opc_invokeinterface: {
   856                     i = invokeVirtualMethod(byteCodes, i, smapper) + 2;
   857                     break;
   858                 }
   859                 case opc_invokevirtual:
   860                     i = invokeVirtualMethod(byteCodes, i, smapper);
   861                     break;
   862                 case opc_invokespecial:
   863                     i = invokeStaticMethod(byteCodes, i, smapper, false);
   864                     break;
   865                 case opc_invokestatic:
   866                     i = invokeStaticMethod(byteCodes, i, smapper, true);
   867                     break;
   868                 case opc_new: {
   869                     int indx = readIntArg(byteCodes, i);
   870                     String ci = jc.getClassName(indx);
   871                     emit(out, "@1 = new @2;",
   872                          smapper.pushA(), accessClass(ci.replace('/', '_')));
   873                     addReference(ci);
   874                     i += 2;
   875                     break;
   876                 }
   877                 case opc_newarray:
   878                     ++i; // skip type of array
   879                     emit(out, "@2 = new Array(@1).fillNulls();",
   880                          smapper.popI(), smapper.pushA());
   881                     break;
   882                 case opc_anewarray:
   883                     i += 2; // skip type of array
   884                     emit(out, "@2 = new Array(@1).fillNulls();",
   885                          smapper.popI(), smapper.pushA());
   886                     break;
   887                 case opc_multianewarray: {
   888                     i += 2;
   889                     int dim = readByte(byteCodes, ++i);
   890                     out.append("{ var a0 = new Array(").append(smapper.popI())
   891                        .append(").fillNulls();");
   892                     for (int d = 1; d < dim; d++) {
   893                         out.append("\n  var l" + d).append(" = ")
   894                            .append(smapper.popI()).append(';');
   895                         out.append("\n  for (var i" + d).append (" = 0; i" + d).
   896                             append(" < a" + (d - 1)).
   897                             append(".length; i" + d).append("++) {");
   898                         out.append("\n    var a" + d).
   899                             append (" = new Array(l" + d).append(").fillNulls();");
   900                         out.append("\n    a" + (d - 1)).append("[i" + d).append("] = a" + d).
   901                             append(";");
   902                     }
   903                     for (int d = 1; d < dim; d++) {
   904                         out.append("\n  }");
   905                     }
   906                     out.append("\n").append(smapper.pushA()).append(" = a0; }");
   907                     break;
   908                 }
   909                 case opc_arraylength:
   910                     emit(out, "@2 = @1.length;", smapper.popA(), smapper.pushI());
   911                     break;
   912                 case opc_lastore:
   913                     emit(out, "@3[@2] = @1;",
   914                          smapper.popL(), smapper.popI(), smapper.popA());
   915                     break;
   916                 case opc_fastore:
   917                     emit(out, "@3[@2] = @1;",
   918                          smapper.popF(), smapper.popI(), smapper.popA());
   919                     break;
   920                 case opc_dastore:
   921                     emit(out, "@3[@2] = @1;",
   922                          smapper.popD(), smapper.popI(), smapper.popA());
   923                     break;
   924                 case opc_aastore:
   925                     emit(out, "@3[@2] = @1;",
   926                          smapper.popA(), smapper.popI(), smapper.popA());
   927                     break;
   928                 case opc_iastore:
   929                 case opc_bastore:
   930                 case opc_castore:
   931                 case opc_sastore:
   932                     emit(out, "@3[@2] = @1;",
   933                          smapper.popI(), smapper.popI(), smapper.popA());
   934                     break;
   935                 case opc_laload:
   936                     emit(out, "@3 = @2[@1];",
   937                          smapper.popI(), smapper.popA(), smapper.pushL());
   938                     break;
   939                 case opc_faload:
   940                     emit(out, "@3 = @2[@1];",
   941                          smapper.popI(), smapper.popA(), smapper.pushF());
   942                     break;
   943                 case opc_daload:
   944                     emit(out, "@3 = @2[@1];",
   945                          smapper.popI(), smapper.popA(), smapper.pushD());
   946                     break;
   947                 case opc_aaload:
   948                     emit(out, "@3 = @2[@1];",
   949                          smapper.popI(), smapper.popA(), smapper.pushA());
   950                     break;
   951                 case opc_iaload:
   952                 case opc_baload:
   953                 case opc_caload:
   954                 case opc_saload:
   955                     emit(out, "@3 = @2[@1];",
   956                          smapper.popI(), smapper.popA(), smapper.pushI());
   957                     break;
   958                 case opc_pop:
   959                 case opc_pop2:
   960                     smapper.pop(1);
   961                     out.append("/* pop */");
   962                     break;
   963                 case opc_dup: {
   964                     final Variable v = smapper.get(0);
   965                     emit(out, "@1 = @2;", smapper.pushT(v.getType()), v);
   966                     break;
   967                 }
   968                 case opc_dup2: {
   969                     if (smapper.get(0).isCategory2()) {
   970                         final Variable v = smapper.get(0);
   971                         emit(out, "@1 = @2;", smapper.pushT(v.getType()), v);
   972                     } else {
   973                         final Variable v1 = smapper.get(0);
   974                         final Variable v2 = smapper.get(1);
   975                         emit(out, "{ @1 = @2; @3 = @4; }",
   976                              smapper.pushT(v2.getType()), v2,
   977                              smapper.pushT(v1.getType()), v1);
   978                     }
   979                     break;
   980                 }
   981                 case opc_dup_x1: {
   982                     final Variable vi1 = smapper.pop();
   983                     final Variable vi2 = smapper.pop();
   984                     final Variable vo3 = smapper.pushT(vi1.getType());
   985                     final Variable vo2 = smapper.pushT(vi2.getType());
   986                     final Variable vo1 = smapper.pushT(vi1.getType());
   987 
   988                     emit(out, "{ @1 = @2; @3 = @4; @5 = @6; }",
   989                          vo1, vi1, vo2, vi2, vo3, vo1);
   990                     break;
   991                 }
   992                 case opc_dup_x2: {
   993                     if (smapper.get(1).isCategory2()) {
   994                         final Variable vi1 = smapper.pop();
   995                         final Variable vi2 = smapper.pop();
   996                         final Variable vo3 = smapper.pushT(vi1.getType());
   997                         final Variable vo2 = smapper.pushT(vi2.getType());
   998                         final Variable vo1 = smapper.pushT(vi1.getType());
   999 
  1000                         emit(out, "{ @1 = @2; @3 = @4; @5 = @6; }",
  1001                              vo1, vi1, vo2, vi2, vo3, vo1);
  1002                     } else {
  1003                         final Variable vi1 = smapper.pop();
  1004                         final Variable vi2 = smapper.pop();
  1005                         final Variable vi3 = smapper.pop();
  1006                         final Variable vo4 = smapper.pushT(vi1.getType());
  1007                         final Variable vo3 = smapper.pushT(vi3.getType());
  1008                         final Variable vo2 = smapper.pushT(vi2.getType());
  1009                         final Variable vo1 = smapper.pushT(vi1.getType());
  1010 
  1011                         emit(out, "{ @1 = @2; @3 = @4; @5 = @6; @7 = @8; }",
  1012                              vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
  1013                     }
  1014                     break;
  1015                 }
  1016                 case opc_bipush:
  1017                     emit(out, "@1 = @2;",
  1018                          smapper.pushI(), Integer.toString(byteCodes[++i]));
  1019                     break;
  1020                 case opc_sipush:
  1021                     emit(out, "@1 = @2;",
  1022                          smapper.pushI(),
  1023                          Integer.toString(readIntArg(byteCodes, i)));
  1024                     i += 2;
  1025                     break;
  1026                 case opc_getfield: {
  1027                     int indx = readIntArg(byteCodes, i);
  1028                     String[] fi = jc.getFieldInfoName(indx);
  1029                     final int type = VarType.fromFieldType(fi[2].charAt(0));
  1030                     emit(out, "@2 = @1.fld_@3;",
  1031                          smapper.popA(), smapper.pushT(type), fi[1]);
  1032                     i += 2;
  1033                     break;
  1034                 }
  1035                 case opc_getstatic: {
  1036                     int indx = readIntArg(byteCodes, i);
  1037                     String[] fi = jc.getFieldInfoName(indx);
  1038                     final int type = VarType.fromFieldType(fi[2].charAt(0));
  1039                     emit(out, "@1 = @2(false).constructor.@3;",
  1040                          smapper.pushT(type),
  1041                          accessClass(fi[0].replace('/', '_')), fi[1]);
  1042                     i += 2;
  1043                     addReference(fi[0]);
  1044                     break;
  1045                 }
  1046                 case opc_putfield: {
  1047                     int indx = readIntArg(byteCodes, i);
  1048                     String[] fi = jc.getFieldInfoName(indx);
  1049                     final int type = VarType.fromFieldType(fi[2].charAt(0));
  1050                     emit(out, "@2.fld_@3 = @1;",
  1051                          smapper.popT(type), smapper.popA(), fi[1]);
  1052                     i += 2;
  1053                     break;
  1054                 }
  1055                 case opc_putstatic: {
  1056                     int indx = readIntArg(byteCodes, i);
  1057                     String[] fi = jc.getFieldInfoName(indx);
  1058                     final int type = VarType.fromFieldType(fi[2].charAt(0));
  1059                     emit(out, "@1(false).constructor.@2 = @3;",
  1060                          accessClass(fi[0].replace('/', '_')), fi[1],
  1061                          smapper.popT(type));
  1062                     i += 2;
  1063                     addReference(fi[0]);
  1064                     break;
  1065                 }
  1066                 case opc_checkcast: {
  1067                     int indx = readIntArg(byteCodes, i);
  1068                     final String type = jc.getClassName(indx);
  1069                     if (!type.startsWith("[")) {
  1070                         // no way to check arrays right now
  1071                         // XXX proper exception
  1072                         emit(out,
  1073                              "if (@1 !== null && !@1.$instOf_@2) throw {};",
  1074                              smapper.getA(0), type.replace('/', '_'));
  1075                     }
  1076                     i += 2;
  1077                     break;
  1078                 }
  1079                 case opc_instanceof: {
  1080                     int indx = readIntArg(byteCodes, i);
  1081                     final String type = jc.getClassName(indx);
  1082                     emit(out, "@2 = @1.$instOf_@3 ? 1 : 0;",
  1083                          smapper.popA(), smapper.pushI(),
  1084                          type.replace('/', '_'));
  1085                     i += 2;
  1086                     break;
  1087                 }
  1088                 case opc_athrow: {
  1089                     final Variable v = smapper.popA();
  1090                     smapper.clear();
  1091 
  1092                     emit(out, "{ @1 = @2; throw @2; }",
  1093                          smapper.pushA(), v);
  1094                     break;
  1095                 }
  1096 
  1097                 case opc_monitorenter: {
  1098                     out.append("/* monitor enter */");
  1099                     smapper.popA();
  1100                     break;
  1101                 }
  1102 
  1103                 case opc_monitorexit: {
  1104                     out.append("/* monitor exit */");
  1105                     smapper.popA();
  1106                     break;
  1107                 }
  1108 
  1109                 default: {
  1110                     emit(out, "throw 'unknown bytecode @1';",
  1111                          Integer.toString(c));
  1112                 }
  1113             }
  1114             if (trap.useTry()) {
  1115                 out.append("} catch (e) {");
  1116                 for (TrapData e : trap.current()) {
  1117                     if (e == null) {
  1118                         break;
  1119                     }
  1120                     if (e.catch_cpx != 0) { //not finally
  1121                         final String classInternalName = jc.getClassName(e.catch_cpx);
  1122                         addReference(classInternalName);
  1123                         out.append("if (e.$instOf_"+classInternalName.replace('/', '_')+") {");
  1124                         out.append("gt="+e.handler_pc+"; continue;");
  1125                         out.append("} ");
  1126                     } else {
  1127                         //finally - todo
  1128                     }
  1129                 }
  1130                 out.append("throw e;");
  1131                 out.append("}");
  1132             }
  1133             out.append(" //");
  1134             for (int j = prev; j <= i; j++) {
  1135                 out.append(" ");
  1136                 final int cc = readByte(byteCodes, j);
  1137                 out.append(Integer.toString(cc));
  1138             }
  1139             out.append("\n");            
  1140         }
  1141         out.append("  }\n");
  1142         out.append("};");
  1143     }
  1144 
  1145     private int generateIf(byte[] byteCodes, int i,
  1146                            final Variable v2, final Variable v1,
  1147                            final String test) throws IOException {
  1148         int indx = i + readIntArg(byteCodes, i);
  1149         out.append("if (").append(v1)
  1150            .append(' ').append(test).append(' ')
  1151            .append(v2).append(") { gt = " + indx)
  1152            .append("; continue; }");
  1153         return i + 2;
  1154     }
  1155 
  1156     private int readIntArg(byte[] byteCodes, int offsetInstruction) {
  1157         final int indxHi = byteCodes[offsetInstruction + 1] << 8;
  1158         final int indxLo = byteCodes[offsetInstruction + 2];
  1159         return (indxHi & 0xffffff00) | (indxLo & 0xff);
  1160     }
  1161     private int readInt4(byte[] byteCodes, int offsetInstruction) {
  1162         final int d = byteCodes[offsetInstruction + 0] << 24;
  1163         final int c = byteCodes[offsetInstruction + 1] << 16;
  1164         final int b = byteCodes[offsetInstruction + 2] << 8;
  1165         final int a = byteCodes[offsetInstruction + 3];
  1166         return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
  1167     }
  1168     private int readByte(byte[] byteCodes, int offsetInstruction) {
  1169         return byteCodes[offsetInstruction] & 0xff;
  1170     }
  1171     
  1172     private static void countArgs(String descriptor, char[] returnType, StringBuilder sig, StringBuilder cnt) {
  1173         int i = 0;
  1174         Boolean count = null;
  1175         boolean array = false;
  1176         sig.append("__");
  1177         int firstPos = sig.length();
  1178         while (i < descriptor.length()) {
  1179             char ch = descriptor.charAt(i++);
  1180             switch (ch) {
  1181                 case '(':
  1182                     count = true;
  1183                     continue;
  1184                 case ')':
  1185                     count = false;
  1186                     continue;
  1187                 case 'B': 
  1188                 case 'C': 
  1189                 case 'D': 
  1190                 case 'F': 
  1191                 case 'I': 
  1192                 case 'J': 
  1193                 case 'S': 
  1194                 case 'Z': 
  1195                     if (count) {
  1196                         if (array) {
  1197                             sig.append("_3");
  1198                         }
  1199                         sig.append(ch);
  1200                         if (ch == 'J' || ch == 'D') {
  1201                             cnt.append('1');
  1202                         } else {
  1203                             cnt.append('0');
  1204                         }
  1205                     } else {
  1206                         sig.insert(firstPos, ch);
  1207                         if (array) {
  1208                             returnType[0] = '[';
  1209                             sig.insert(firstPos, "_3");
  1210                         } else {
  1211                             returnType[0] = ch;
  1212                         }
  1213                     }
  1214                     array = false;
  1215                     continue;
  1216                 case 'V': 
  1217                     assert !count;
  1218                     returnType[0] = 'V';
  1219                     sig.insert(firstPos, 'V');
  1220                     continue;
  1221                 case 'L':
  1222                     int next = descriptor.indexOf(';', i);
  1223                     String realSig = mangleSig(descriptor, i - 1, next + 1);
  1224                     if (count) {
  1225                         if (array) {
  1226                             sig.append("_3");
  1227                         }
  1228                         sig.append(realSig);
  1229                         cnt.append('0');
  1230                     } else {
  1231                         sig.insert(firstPos, realSig);
  1232                         if (array) {
  1233                             sig.insert(firstPos, "_3");
  1234                         }
  1235                         returnType[0] = 'L';
  1236                     }
  1237                     i = next + 1;
  1238                     continue;
  1239                 case '[':
  1240                     array = true;
  1241                     continue;
  1242                 default:
  1243                     throw new IllegalStateException("Invalid char: " + ch);
  1244             }
  1245         }
  1246     }
  1247     
  1248     private static String mangleSig(String txt, int first, int last) {
  1249         StringBuilder sb = new StringBuilder();
  1250         for (int i = first; i < last; i++) {
  1251             final char ch = txt.charAt(i);
  1252             switch (ch) {
  1253                 case '/': sb.append('_'); break;
  1254                 case '_': sb.append("_1"); break;
  1255                 case ';': sb.append("_2"); break;
  1256                 case '[': sb.append("_3"); break;
  1257                 default: sb.append(ch); break;
  1258             }
  1259         }
  1260         return sb.toString();
  1261     }
  1262 
  1263     private static String findMethodName(MethodData m, StringBuilder cnt) {
  1264         StringBuilder name = new StringBuilder();
  1265         if ("<init>".equals(m.getName())) { // NOI18N
  1266             name.append("cons"); // NOI18N
  1267         } else if ("<clinit>".equals(m.getName())) { // NOI18N
  1268             name.append("class"); // NOI18N
  1269         } else {
  1270             name.append(m.getName());
  1271         } 
  1272         
  1273         countArgs(m.getInternalSig(), new char[1], name, cnt);
  1274         return name.toString();
  1275     }
  1276 
  1277     static String findMethodName(String[] mi, StringBuilder cnt, char[] returnType) {
  1278         StringBuilder name = new StringBuilder();
  1279         String descr = mi[2];//mi.getDescriptor();
  1280         String nm= mi[1];
  1281         if ("<init>".equals(nm)) { // NOI18N
  1282             name.append("cons"); // NOI18N
  1283         } else {
  1284             name.append(nm);
  1285         }
  1286         countArgs(descr, returnType, name, cnt);
  1287         return name.toString();
  1288     }
  1289 
  1290     private int invokeStaticMethod(byte[] byteCodes, int i, final StackMapper mapper, boolean isStatic)
  1291     throws IOException {
  1292         int methodIndex = readIntArg(byteCodes, i);
  1293         String[] mi = jc.getFieldInfoName(methodIndex);
  1294         char[] returnType = { 'V' };
  1295         StringBuilder cnt = new StringBuilder();
  1296         String mn = findMethodName(mi, cnt, returnType);
  1297 
  1298         final int numArguments = isStatic ? cnt.length() : cnt.length() + 1;
  1299         final Variable[] vars = new Variable[numArguments];
  1300 
  1301         for (int j = numArguments - 1; j >= 0; --j) {
  1302             vars[j] = mapper.pop();
  1303         }
  1304 
  1305         if (returnType[0] != 'V') {
  1306             out.append(mapper.pushT(VarType.fromFieldType(returnType[0])))
  1307                .append(" = ");
  1308         }
  1309 
  1310         final String in = mi[0];
  1311         out.append(accessClass(in.replace('/', '_')));
  1312         out.append("(false).");
  1313         out.append(mn);
  1314         out.append('(');
  1315         if (numArguments > 0) {
  1316             out.append(vars[0]);
  1317             for (int j = 1; j < numArguments; ++j) {
  1318                 out.append(", ");
  1319                 out.append(vars[j]);
  1320             }
  1321         }
  1322         out.append(");");
  1323         i += 2;
  1324         addReference(in);
  1325         return i;
  1326     }
  1327     private int invokeVirtualMethod(byte[] byteCodes, int i, final StackMapper mapper)
  1328     throws IOException {
  1329         int methodIndex = readIntArg(byteCodes, i);
  1330         String[] mi = jc.getFieldInfoName(methodIndex);
  1331         char[] returnType = { 'V' };
  1332         StringBuilder cnt = new StringBuilder();
  1333         String mn = findMethodName(mi, cnt, returnType);
  1334 
  1335         final int numArguments = cnt.length() + 1;
  1336         final Variable[] vars = new Variable[numArguments];
  1337 
  1338         for (int j = numArguments - 1; j >= 0; --j) {
  1339             vars[j] = mapper.pop();
  1340         }
  1341 
  1342         if (returnType[0] != 'V') {
  1343             out.append(mapper.pushT(VarType.fromFieldType(returnType[0])))
  1344                .append(" = ");
  1345         }
  1346 
  1347         out.append(vars[0]).append('.');
  1348         out.append(mn);
  1349         out.append('(');
  1350         out.append(vars[0]);
  1351         for (int j = 1; j < numArguments; ++j) {
  1352             out.append(", ");
  1353             out.append(vars[j]);
  1354         }
  1355         out.append(");");
  1356         i += 2;
  1357         return i;
  1358     }
  1359 
  1360     private void addReference(String cn) throws IOException {
  1361         if (requireReference(cn)) {
  1362             out.append(" /* needs ").append(cn).append(" */");
  1363         }
  1364     }
  1365 
  1366     private void outType(String d, StringBuilder out) {
  1367         int arr = 0;
  1368         while (d.charAt(0) == '[') {
  1369             out.append('A');
  1370             d = d.substring(1);
  1371         }
  1372         if (d.charAt(0) == 'L') {
  1373             assert d.charAt(d.length() - 1) == ';';
  1374             out.append(d.replace('/', '_').substring(0, d.length() - 1));
  1375         } else {
  1376             out.append(d);
  1377         }
  1378     }
  1379 
  1380     private String encodeConstant(int entryIndex) throws IOException {
  1381         String[] classRef = { null };
  1382         String s = jc.stringValue(entryIndex, classRef);
  1383         if (classRef[0] != null) {
  1384             addReference(classRef[0]);
  1385             s = accessClass(s.replace('/', '_')) + "(false).constructor.$class";
  1386         }
  1387         return s;
  1388     }
  1389 
  1390     private String javaScriptBody(String prefix, MethodData m, boolean isStatic) throws IOException {
  1391         byte[] arr = m.findAnnotationData(true);
  1392         if (arr == null) {
  1393             return null;
  1394         }
  1395         final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
  1396         class P extends AnnotationParser {
  1397             public P() {
  1398                 super(false);
  1399             }
  1400             
  1401             int cnt;
  1402             String[] args = new String[30];
  1403             String body;
  1404             
  1405             @Override
  1406             protected void visitAttr(String type, String attr, String at, String value) {
  1407                 if (type.equals(jvmType)) {
  1408                     if ("body".equals(attr)) {
  1409                         body = value;
  1410                     } else if ("args".equals(attr)) {
  1411                         args[cnt++] = value;
  1412                     } else {
  1413                         throw new IllegalArgumentException(attr);
  1414                     }
  1415                 }
  1416             }
  1417         }
  1418         P p = new P();
  1419         p.parse(arr, jc);
  1420         if (p.body == null) {
  1421             return null;
  1422         }
  1423         StringBuilder cnt = new StringBuilder();
  1424         final String mn = findMethodName(m, cnt);
  1425         out.append(prefix).append(mn);
  1426         out.append(" = function(");
  1427         String space;
  1428         int index;
  1429         if (!isStatic) {                
  1430             space = outputArg(out, p.args, 0);
  1431             index = 1;
  1432         } else {
  1433             space = "";
  1434             index = 0;
  1435         }
  1436         for (int i = 0; i < cnt.length(); i++) {
  1437             out.append(space);
  1438             space = outputArg(out, p.args, index);
  1439             index++;
  1440         }
  1441         out.append(") {").append("\n");
  1442         out.append(p.body);
  1443         out.append("\n}\n");
  1444         return mn;
  1445     }
  1446     private static String className(ClassData jc) {
  1447         //return jc.getName().getInternalName().replace('/', '_');
  1448         return jc.getClassName().replace('/', '_');
  1449     }
  1450     
  1451     private static String[] findAnnotation(
  1452         byte[] arr, ClassData cd, final String className, 
  1453         final String... attrNames
  1454     ) throws IOException {
  1455         if (arr == null) {
  1456             return null;
  1457         }
  1458         final String[] values = new String[attrNames.length];
  1459         final boolean[] found = { false };
  1460         final String jvmType = "L" + className.replace('.', '/') + ";";
  1461         AnnotationParser ap = new AnnotationParser(false) {
  1462             @Override
  1463             protected void visitAttr(String type, String attr, String at, String value) {
  1464                 if (type.equals(jvmType)) {
  1465                     found[0] = true;
  1466                     for (int i = 0; i < attrNames.length; i++) {
  1467                         if (attrNames[i].equals(attr)) {
  1468                             values[i] = value;
  1469                         }
  1470                     }
  1471                 }
  1472             }
  1473             
  1474         };
  1475         ap.parse(arr, cd);
  1476         return found[0] ? values : null;
  1477     }
  1478 
  1479     private CharSequence initField(FieldData v) {
  1480         final String is = v.getInternalSig();
  1481         if (is.length() == 1) {
  1482             switch (is.charAt(0)) {
  1483                 case 'S':
  1484                 case 'J':
  1485                 case 'B':
  1486                 case 'Z':
  1487                 case 'C':
  1488                 case 'I': return " = 0;";
  1489                 case 'F': 
  1490                 case 'D': return " = 0.0;";
  1491                 default:
  1492                     throw new IllegalStateException(is);
  1493             }
  1494         }
  1495         return " = null;";
  1496     }
  1497 
  1498     private static void generateAnno(ClassData cd, final Appendable out, byte[] data) throws IOException {
  1499         AnnotationParser ap = new AnnotationParser(true) {
  1500             int anno;
  1501             int cnt;
  1502             
  1503             @Override
  1504             protected void visitAnnotationStart(String type) throws IOException {
  1505                 if (anno++ > 0) {
  1506                     out.append(",");
  1507                 }
  1508                 out.append('"').append(type).append("\" : {\n");
  1509                 cnt = 0;
  1510             }
  1511 
  1512             @Override
  1513             protected void visitAnnotationEnd(String type) throws IOException {
  1514                 out.append("\n}\n");
  1515             }
  1516             
  1517             @Override
  1518             protected void visitAttr(String type, String attr, String attrType, String value) 
  1519             throws IOException {
  1520                 if (attr == null) {
  1521                     return;
  1522                 }
  1523                 if (cnt++ > 0) {
  1524                     out.append(",\n");
  1525                 }
  1526                 out.append(attr).append("__").append(attrType).append(" : ").append(value);
  1527             }
  1528         };
  1529         ap.parse(data, cd);
  1530     }
  1531 
  1532     private static String outputArg(Appendable out, String[] args, int indx) throws IOException {
  1533         final String name = args[indx];
  1534         if (name == null) {
  1535             return "";
  1536         }
  1537         if (name.contains(",")) {
  1538             throw new IOException("Wrong parameter with ',': " + name);
  1539         }
  1540         out.append(name);
  1541         return ",";
  1542     }
  1543 
  1544     private static void emit(final Appendable out,
  1545                              final String format,
  1546                              final CharSequence... params) throws IOException {
  1547         final int length = format.length();
  1548 
  1549         int processed = 0;
  1550         int paramOffset = format.indexOf('@');
  1551         while ((paramOffset != -1) && (paramOffset < (length - 1))) {
  1552             final char paramChar = format.charAt(paramOffset + 1);
  1553             if ((paramChar >= '1') && (paramChar <= '9')) {
  1554                 final int paramIndex = paramChar - '0' - 1;
  1555 
  1556                 out.append(format, processed, paramOffset);
  1557                 out.append(params[paramIndex]);
  1558 
  1559                 ++paramOffset;
  1560                 processed = paramOffset + 1;
  1561             }
  1562 
  1563             paramOffset = format.indexOf('@', paramOffset + 1);
  1564         }
  1565 
  1566         out.append(format, processed, length);
  1567     }
  1568 }