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