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