vm/src/main/java/org/apidesign/vm4brwsr/ByteCodeToJavaScript.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Tue, 15 Jan 2013 11:53:07 +0100
changeset 456 f2f769bafeef
parent 453 5aca91d00356
parent 446 5b3d5ed03014
child 457 b0e82dcf51fb
permissions -rw-r--r--
Bringing Martin's integer, short, byte arithmetic to default branch
     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.add32(@2);", 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.sub32(@2);", 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.mul32(@2);", 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                     emit(out, "@1 = @1.toInt8();", smapper.getI(0));
   679                     break;
   680                 case opc_i2c:
   681                     out.append("{ /* number conversion */ }");
   682                     break;
   683                 case opc_i2s:
   684                     emit(out, "@1 = @1.toInt16();", smapper.getI(0));
   685                     break;
   686                 case opc_aconst_null:
   687                     emit(out, "@1 = null;", smapper.pushA());
   688                     break;
   689                 case opc_iconst_m1:
   690                     emit(out, "@1 = -1;", smapper.pushI());
   691                     break;
   692                 case opc_iconst_0:
   693                     emit(out, "@1 = 0;", smapper.pushI());
   694                     break;
   695                 case opc_dconst_0:
   696                     emit(out, "@1 = 0;", smapper.pushD());
   697                     break;
   698                 case opc_lconst_0:
   699                     emit(out, "@1 = 0;", smapper.pushL());
   700                     break;
   701                 case opc_fconst_0:
   702                     emit(out, "@1 = 0;", smapper.pushF());
   703                     break;
   704                 case opc_iconst_1:
   705                     emit(out, "@1 = 1;", smapper.pushI());
   706                     break;
   707                 case opc_lconst_1:
   708                     emit(out, "@1 = 1;", smapper.pushL());
   709                     break;
   710                 case opc_fconst_1:
   711                     emit(out, "@1 = 1;", smapper.pushF());
   712                     break;
   713                 case opc_dconst_1:
   714                     emit(out, "@1 = 1;", smapper.pushD());
   715                     break;
   716                 case opc_iconst_2:
   717                     emit(out, "@1 = 2;", smapper.pushI());
   718                     break;
   719                 case opc_fconst_2:
   720                     emit(out, "@1 = 2;", smapper.pushF());
   721                     break;
   722                 case opc_iconst_3:
   723                     emit(out, "@1 = 3;", smapper.pushI());
   724                     break;
   725                 case opc_iconst_4:
   726                     emit(out, "@1 = 4;", smapper.pushI());
   727                     break;
   728                 case opc_iconst_5:
   729                     emit(out, "@1 = 5;", smapper.pushI());
   730                     break;
   731                 case opc_ldc: {
   732                     int indx = readByte(byteCodes, ++i);
   733                     String v = encodeConstant(indx);
   734                     int type = VarType.fromConstantType(jc.getTag(indx));
   735                     emit(out, "@1 = @2;", smapper.pushT(type), v);
   736                     break;
   737                 }
   738                 case opc_ldc_w:
   739                 case opc_ldc2_w: {
   740                     int indx = readIntArg(byteCodes, i);
   741                     i += 2;
   742                     String v = encodeConstant(indx);
   743                     int type = VarType.fromConstantType(jc.getTag(indx));
   744                     emit(out, "@1 = @2;", smapper.pushT(type), v);
   745                     break;
   746                 }
   747                 case opc_lcmp:
   748                     emit(out, "@3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
   749                          smapper.popL(), smapper.popL(), smapper.pushI());
   750                     break;
   751                 case opc_fcmpl:
   752                 case opc_fcmpg:
   753                     emit(out, "@3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
   754                          smapper.popF(), smapper.popF(), smapper.pushI());
   755                     break;
   756                 case opc_dcmpl:
   757                 case opc_dcmpg:
   758                     emit(out, "@3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
   759                          smapper.popD(), smapper.popD(), smapper.pushI());
   760                     break;
   761                 case opc_if_acmpeq:
   762                     i = generateIf(byteCodes, i, smapper.popA(), smapper.popA(),
   763                                    "===");
   764                     break;
   765                 case opc_if_acmpne:
   766                     i = generateIf(byteCodes, i, smapper.popA(), smapper.popA(),
   767                                    "!=");
   768                     break;
   769                 case opc_if_icmpeq:
   770                     i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
   771                                    "==");
   772                     break;
   773                 case opc_ifeq: {
   774                     int indx = i + readIntArg(byteCodes, i);
   775                     emit(out, "if (@1 == 0) { gt = @2; continue; }",
   776                          smapper.popI(), Integer.toString(indx));
   777                     i += 2;
   778                     break;
   779                 }
   780                 case opc_ifne: {
   781                     int indx = i + readIntArg(byteCodes, i);
   782                     emit(out, "if (@1 != 0) { gt = @2; continue; }",
   783                          smapper.popI(), Integer.toString(indx));
   784                     i += 2;
   785                     break;
   786                 }
   787                 case opc_iflt: {
   788                     int indx = i + readIntArg(byteCodes, i);
   789                     emit(out, "if (@1 < 0) { gt = @2; continue; }",
   790                          smapper.popI(), Integer.toString(indx));
   791                     i += 2;
   792                     break;
   793                 }
   794                 case opc_ifle: {
   795                     int indx = i + readIntArg(byteCodes, i);
   796                     emit(out, "if (@1 <= 0) { gt = @2; continue; }",
   797                          smapper.popI(), Integer.toString(indx));
   798                     i += 2;
   799                     break;
   800                 }
   801                 case opc_ifgt: {
   802                     int indx = i + readIntArg(byteCodes, i);
   803                     emit(out, "if (@1 > 0) { gt = @2; continue; }",
   804                          smapper.popI(), Integer.toString(indx));
   805                     i += 2;
   806                     break;
   807                 }
   808                 case opc_ifge: {
   809                     int indx = i + readIntArg(byteCodes, i);
   810                     emit(out, "if (@1 >= 0) { gt = @2; continue; }",
   811                          smapper.popI(), Integer.toString(indx));
   812                     i += 2;
   813                     break;
   814                 }
   815                 case opc_ifnonnull: {
   816                     int indx = i + readIntArg(byteCodes, i);
   817                     emit(out, "if (@1 !== null) { gt = @2; continue; }",
   818                          smapper.popA(), Integer.toString(indx));
   819                     i += 2;
   820                     break;
   821                 }
   822                 case opc_ifnull: {
   823                     int indx = i + readIntArg(byteCodes, i);
   824                     emit(out, "if (@1 === null) { gt = @2; continue; }",
   825                          smapper.popA(), Integer.toString(indx));
   826                     i += 2;
   827                     break;
   828                 }
   829                 case opc_if_icmpne:
   830                     i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
   831                                    "!=");
   832                     break;
   833                 case opc_if_icmplt:
   834                     i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
   835                                    "<");
   836                     break;
   837                 case opc_if_icmple:
   838                     i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
   839                                    "<=");
   840                     break;
   841                 case opc_if_icmpgt:
   842                     i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
   843                                    ">");
   844                     break;
   845                 case opc_if_icmpge:
   846                     i = generateIf(byteCodes, i, smapper.popI(), smapper.popI(),
   847                                    ">=");
   848                     break;
   849                 case opc_goto: {
   850                     int indx = i + readIntArg(byteCodes, i);
   851                     emit(out, "gt = @1; continue;", Integer.toString(indx));
   852                     i += 2;
   853                     break;
   854                 }
   855                 case opc_lookupswitch: {
   856                     int table = i / 4 * 4 + 4;
   857                     int dflt = i + readInt4(byteCodes, table);
   858                     table += 4;
   859                     int n = readInt4(byteCodes, table);
   860                     table += 4;
   861                     out.append("switch (").append(smapper.popI()).append(") {\n");
   862                     while (n-- > 0) {
   863                         int cnstnt = readInt4(byteCodes, table);
   864                         table += 4;
   865                         int offset = i + readInt4(byteCodes, table);
   866                         table += 4;
   867                         out.append("  case " + cnstnt).append(": gt = " + offset).append("; continue;\n");
   868                     }
   869                     out.append("  default: gt = " + dflt).append("; continue;\n}");
   870                     i = table - 1;
   871                     break;
   872                 }
   873                 case opc_tableswitch: {
   874                     int table = i / 4 * 4 + 4;
   875                     int dflt = i + readInt4(byteCodes, table);
   876                     table += 4;
   877                     int low = readInt4(byteCodes, table);
   878                     table += 4;
   879                     int high = readInt4(byteCodes, table);
   880                     table += 4;
   881                     out.append("switch (").append(smapper.popI()).append(") {\n");
   882                     while (low <= high) {
   883                         int offset = i + readInt4(byteCodes, table);
   884                         table += 4;
   885                         out.append("  case " + low).append(": gt = " + offset).append("; continue;\n");
   886                         low++;
   887                     }
   888                     out.append("  default: gt = " + dflt).append("; continue;\n}");
   889                     i = table - 1;
   890                     break;
   891                 }
   892                 case opc_invokeinterface: {
   893                     i = invokeVirtualMethod(byteCodes, i, smapper) + 2;
   894                     break;
   895                 }
   896                 case opc_invokevirtual:
   897                     i = invokeVirtualMethod(byteCodes, i, smapper);
   898                     break;
   899                 case opc_invokespecial:
   900                     i = invokeStaticMethod(byteCodes, i, smapper, false);
   901                     break;
   902                 case opc_invokestatic:
   903                     i = invokeStaticMethod(byteCodes, i, smapper, true);
   904                     break;
   905                 case opc_new: {
   906                     int indx = readIntArg(byteCodes, i);
   907                     String ci = jc.getClassName(indx);
   908                     emit(out, "@1 = new @2;",
   909                          smapper.pushA(), accessClass(ci.replace('/', '_')));
   910                     addReference(ci);
   911                     i += 2;
   912                     break;
   913                 }
   914                 case opc_newarray:
   915                     int atype = readByte(byteCodes, ++i);
   916                     String jvmType;
   917                     switch (atype) {
   918                         case 4: jvmType = "[Z"; break;
   919                         case 5: jvmType = "[C"; break;
   920                         case 6: jvmType = "[F"; break;
   921                         case 7: jvmType = "[D"; break;
   922                         case 8: jvmType = "[B"; break;
   923                         case 9: jvmType = "[S"; break;
   924                         case 10: jvmType = "[I"; break;
   925                         case 11: jvmType = "[J"; break;
   926                         default: throw new IllegalStateException("Array type: " + atype);
   927                     }
   928                     emit(out, "@2 = new Array(@1).initWith('@3', 0);",
   929                          smapper.popI(), smapper.pushA(), jvmType);
   930                     break;
   931                 case opc_anewarray: {
   932                     int type = readIntArg(byteCodes, i);
   933                     i += 2;
   934                     String typeName = jc.getClassName(type);
   935                     if (typeName.startsWith("[")) {
   936                         typeName = "[" + typeName;
   937                     } else {
   938                         typeName = "[L" + typeName + ";";
   939                     }
   940                     emit(out, "@2 = new Array(@1).initWith('@3', null);",
   941                          smapper.popI(), smapper.pushA(), typeName);
   942                     break;
   943                 }
   944                 case opc_multianewarray: {
   945                     int type = readIntArg(byteCodes, i);
   946                     i += 2;
   947                     String typeName = jc.getClassName(type);
   948                     int dim = readByte(byteCodes, ++i);
   949                     out.append("{ var a0 = new Array(").append(smapper.popI())
   950                        .append(").initWith('").append(typeName).append("', null);");
   951                     for (int d = 1; d < dim; d++) {
   952                         typeName = typeName.substring(1);
   953                         out.append("\n  var l" + d).append(" = ")
   954                            .append(smapper.popI()).append(';');
   955                         out.append("\n  for (var i" + d).append (" = 0; i" + d).
   956                             append(" < a" + (d - 1)).
   957                             append(".length; i" + d).append("++) {");
   958                         out.append("\n    var a" + d).
   959                             append (" = new Array(l" + d).append(").initWith('")
   960                             .append(typeName).append("', null);");
   961                         out.append("\n    a" + (d - 1)).append("[i" + d).append("] = a" + d).
   962                             append(";");
   963                     }
   964                     for (int d = 1; d < dim; d++) {
   965                         out.append("\n  }");
   966                     }
   967                     out.append("\n").append(smapper.pushA()).append(" = a0; }");
   968                     break;
   969                 }
   970                 case opc_arraylength:
   971                     emit(out, "@2 = @1.length;", smapper.popA(), smapper.pushI());
   972                     break;
   973                 case opc_lastore:
   974                     emit(out, "@3[@2] = @1;",
   975                          smapper.popL(), smapper.popI(), smapper.popA());
   976                     break;
   977                 case opc_fastore:
   978                     emit(out, "@3[@2] = @1;",
   979                          smapper.popF(), smapper.popI(), smapper.popA());
   980                     break;
   981                 case opc_dastore:
   982                     emit(out, "@3[@2] = @1;",
   983                          smapper.popD(), smapper.popI(), smapper.popA());
   984                     break;
   985                 case opc_aastore:
   986                     emit(out, "@3[@2] = @1;",
   987                          smapper.popA(), smapper.popI(), smapper.popA());
   988                     break;
   989                 case opc_iastore:
   990                 case opc_bastore:
   991                 case opc_castore:
   992                 case opc_sastore:
   993                     emit(out, "@3[@2] = @1;",
   994                          smapper.popI(), smapper.popI(), smapper.popA());
   995                     break;
   996                 case opc_laload:
   997                     emit(out, "@3 = @2[@1];",
   998                          smapper.popI(), smapper.popA(), smapper.pushL());
   999                     break;
  1000                 case opc_faload:
  1001                     emit(out, "@3 = @2[@1];",
  1002                          smapper.popI(), smapper.popA(), smapper.pushF());
  1003                     break;
  1004                 case opc_daload:
  1005                     emit(out, "@3 = @2[@1];",
  1006                          smapper.popI(), smapper.popA(), smapper.pushD());
  1007                     break;
  1008                 case opc_aaload:
  1009                     emit(out, "@3 = @2[@1];",
  1010                          smapper.popI(), smapper.popA(), smapper.pushA());
  1011                     break;
  1012                 case opc_iaload:
  1013                 case opc_baload:
  1014                 case opc_caload:
  1015                 case opc_saload:
  1016                     emit(out, "@3 = @2[@1];",
  1017                          smapper.popI(), smapper.popA(), smapper.pushI());
  1018                     break;
  1019                 case opc_pop:
  1020                 case opc_pop2:
  1021                     smapper.pop(1);
  1022                     debug("/* pop */");
  1023                     break;
  1024                 case opc_dup: {
  1025                     final Variable v = smapper.get(0);
  1026                     emit(out, "@1 = @2;", smapper.pushT(v.getType()), v);
  1027                     break;
  1028                 }
  1029                 case opc_dup2: {
  1030                     if (smapper.get(0).isCategory2()) {
  1031                         final Variable v = smapper.get(0);
  1032                         emit(out, "@1 = @2;", smapper.pushT(v.getType()), v);
  1033                     } else {
  1034                         final Variable v1 = smapper.get(0);
  1035                         final Variable v2 = smapper.get(1);
  1036                         emit(out, "{ @1 = @2; @3 = @4; }",
  1037                              smapper.pushT(v2.getType()), v2,
  1038                              smapper.pushT(v1.getType()), v1);
  1039                     }
  1040                     break;
  1041                 }
  1042                 case opc_dup_x1: {
  1043                     final Variable vi1 = smapper.pop();
  1044                     final Variable vi2 = smapper.pop();
  1045                     final Variable vo3 = smapper.pushT(vi1.getType());
  1046                     final Variable vo2 = smapper.pushT(vi2.getType());
  1047                     final Variable vo1 = smapper.pushT(vi1.getType());
  1048 
  1049                     emit(out, "{ @1 = @2; @3 = @4; @5 = @6; }",
  1050                          vo1, vi1, vo2, vi2, vo3, vo1);
  1051                     break;
  1052                 }
  1053                 case opc_dup_x2: {
  1054                     if (smapper.get(1).isCategory2()) {
  1055                         final Variable vi1 = smapper.pop();
  1056                         final Variable vi2 = smapper.pop();
  1057                         final Variable vo3 = smapper.pushT(vi1.getType());
  1058                         final Variable vo2 = smapper.pushT(vi2.getType());
  1059                         final Variable vo1 = smapper.pushT(vi1.getType());
  1060 
  1061                         emit(out, "{ @1 = @2; @3 = @4; @5 = @6; }",
  1062                              vo1, vi1, vo2, vi2, vo3, vo1);
  1063                     } else {
  1064                         final Variable vi1 = smapper.pop();
  1065                         final Variable vi2 = smapper.pop();
  1066                         final Variable vi3 = smapper.pop();
  1067                         final Variable vo4 = smapper.pushT(vi1.getType());
  1068                         final Variable vo3 = smapper.pushT(vi3.getType());
  1069                         final Variable vo2 = smapper.pushT(vi2.getType());
  1070                         final Variable vo1 = smapper.pushT(vi1.getType());
  1071 
  1072                         emit(out, "{ @1 = @2; @3 = @4; @5 = @6; @7 = @8; }",
  1073                              vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
  1074                     }
  1075                     break;
  1076                 }
  1077                 case opc_bipush:
  1078                     emit(out, "@1 = @2;",
  1079                          smapper.pushI(), Integer.toString(byteCodes[++i]));
  1080                     break;
  1081                 case opc_sipush:
  1082                     emit(out, "@1 = @2;",
  1083                          smapper.pushI(),
  1084                          Integer.toString(readIntArg(byteCodes, i)));
  1085                     i += 2;
  1086                     break;
  1087                 case opc_getfield: {
  1088                     int indx = readIntArg(byteCodes, i);
  1089                     String[] fi = jc.getFieldInfoName(indx);
  1090                     final int type = VarType.fromFieldType(fi[2].charAt(0));
  1091                     emit(out, "@2 = @1.fld_@3;",
  1092                          smapper.popA(), smapper.pushT(type), fi[1]);
  1093                     i += 2;
  1094                     break;
  1095                 }
  1096                 case opc_getstatic: {
  1097                     int indx = readIntArg(byteCodes, i);
  1098                     String[] fi = jc.getFieldInfoName(indx);
  1099                     final int type = VarType.fromFieldType(fi[2].charAt(0));
  1100                     emit(out, "@1 = @2(false).constructor.@3;",
  1101                          smapper.pushT(type),
  1102                          accessClass(fi[0].replace('/', '_')), fi[1]);
  1103                     i += 2;
  1104                     addReference(fi[0]);
  1105                     break;
  1106                 }
  1107                 case opc_putfield: {
  1108                     int indx = readIntArg(byteCodes, i);
  1109                     String[] fi = jc.getFieldInfoName(indx);
  1110                     final int type = VarType.fromFieldType(fi[2].charAt(0));
  1111                     emit(out, "@2.fld_@3 = @1;",
  1112                          smapper.popT(type), smapper.popA(), fi[1]);
  1113                     i += 2;
  1114                     break;
  1115                 }
  1116                 case opc_putstatic: {
  1117                     int indx = readIntArg(byteCodes, i);
  1118                     String[] fi = jc.getFieldInfoName(indx);
  1119                     final int type = VarType.fromFieldType(fi[2].charAt(0));
  1120                     emit(out, "@1(false).constructor.@2 = @3;",
  1121                          accessClass(fi[0].replace('/', '_')), fi[1],
  1122                          smapper.popT(type));
  1123                     i += 2;
  1124                     addReference(fi[0]);
  1125                     break;
  1126                 }
  1127                 case opc_checkcast: {
  1128                     int indx = readIntArg(byteCodes, i);
  1129                     final String type = jc.getClassName(indx);
  1130                     if (!type.startsWith("[")) {
  1131                         // no way to check arrays right now
  1132                         // XXX proper exception
  1133                         emit(out,
  1134                              "if (@1 !== null && !@1.$instOf_@2) throw {};",
  1135                              smapper.getA(0), type.replace('/', '_'));
  1136                     }
  1137                     i += 2;
  1138                     break;
  1139                 }
  1140                 case opc_instanceof: {
  1141                     int indx = readIntArg(byteCodes, i);
  1142                     final String type = jc.getClassName(indx);
  1143                     emit(out, "@2 = @1.$instOf_@3 ? 1 : 0;",
  1144                          smapper.popA(), smapper.pushI(),
  1145                          type.replace('/', '_'));
  1146                     i += 2;
  1147                     break;
  1148                 }
  1149                 case opc_athrow: {
  1150                     final Variable v = smapper.popA();
  1151                     smapper.clear();
  1152 
  1153                     emit(out, "{ @1 = @2; throw @2; }",
  1154                          smapper.pushA(), v);
  1155                     break;
  1156                 }
  1157 
  1158                 case opc_monitorenter: {
  1159                     out.append("/* monitor enter */");
  1160                     smapper.popA();
  1161                     break;
  1162                 }
  1163 
  1164                 case opc_monitorexit: {
  1165                     out.append("/* monitor exit */");
  1166                     smapper.popA();
  1167                     break;
  1168                 }
  1169 
  1170                 default: {
  1171                     emit(out, "throw 'unknown bytecode @1';",
  1172                          Integer.toString(c));
  1173                 }
  1174             }
  1175             if (debug(" //")) {
  1176                 for (int j = prev; j <= i; j++) {
  1177                     out.append(" ");
  1178                     final int cc = readByte(byteCodes, j);
  1179                     out.append(Integer.toString(cc));
  1180                 }
  1181             }
  1182             out.append("\n");            
  1183         }
  1184         if (previousTrap != null) {
  1185             generateCatch(previousTrap);
  1186         }
  1187         out.append("  }\n");
  1188         out.append("};");
  1189     }
  1190 
  1191     private int generateIf(byte[] byteCodes, int i,
  1192                            final Variable v2, final Variable v1,
  1193                            final String test) throws IOException {
  1194         int indx = i + readIntArg(byteCodes, i);
  1195         out.append("if (").append(v1)
  1196            .append(' ').append(test).append(' ')
  1197            .append(v2).append(") { gt = " + indx)
  1198            .append("; continue; }");
  1199         return i + 2;
  1200     }
  1201 
  1202     private int readIntArg(byte[] byteCodes, int offsetInstruction) {
  1203         final int indxHi = byteCodes[offsetInstruction + 1] << 8;
  1204         final int indxLo = byteCodes[offsetInstruction + 2];
  1205         return (indxHi & 0xffffff00) | (indxLo & 0xff);
  1206     }
  1207     private int readInt4(byte[] byteCodes, int offsetInstruction) {
  1208         final int d = byteCodes[offsetInstruction + 0] << 24;
  1209         final int c = byteCodes[offsetInstruction + 1] << 16;
  1210         final int b = byteCodes[offsetInstruction + 2] << 8;
  1211         final int a = byteCodes[offsetInstruction + 3];
  1212         return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
  1213     }
  1214     private int readByte(byte[] byteCodes, int offsetInstruction) {
  1215         return byteCodes[offsetInstruction] & 0xff;
  1216     }
  1217     
  1218     private static void countArgs(String descriptor, char[] returnType, StringBuilder sig, StringBuilder cnt) {
  1219         int i = 0;
  1220         Boolean count = null;
  1221         boolean array = false;
  1222         sig.append("__");
  1223         int firstPos = sig.length();
  1224         while (i < descriptor.length()) {
  1225             char ch = descriptor.charAt(i++);
  1226             switch (ch) {
  1227                 case '(':
  1228                     count = true;
  1229                     continue;
  1230                 case ')':
  1231                     count = false;
  1232                     continue;
  1233                 case 'B': 
  1234                 case 'C': 
  1235                 case 'D': 
  1236                 case 'F': 
  1237                 case 'I': 
  1238                 case 'J': 
  1239                 case 'S': 
  1240                 case 'Z': 
  1241                     if (count) {
  1242                         if (array) {
  1243                             sig.append("_3");
  1244                         }
  1245                         sig.append(ch);
  1246                         if (ch == 'J' || ch == 'D') {
  1247                             cnt.append('1');
  1248                         } else {
  1249                             cnt.append('0');
  1250                         }
  1251                     } else {
  1252                         sig.insert(firstPos, ch);
  1253                         if (array) {
  1254                             returnType[0] = '[';
  1255                             sig.insert(firstPos, "_3");
  1256                         } else {
  1257                             returnType[0] = ch;
  1258                         }
  1259                     }
  1260                     array = false;
  1261                     continue;
  1262                 case 'V': 
  1263                     assert !count;
  1264                     returnType[0] = 'V';
  1265                     sig.insert(firstPos, 'V');
  1266                     continue;
  1267                 case 'L':
  1268                     int next = descriptor.indexOf(';', i);
  1269                     String realSig = mangleSig(descriptor, i - 1, next + 1);
  1270                     if (count) {
  1271                         if (array) {
  1272                             sig.append("_3");
  1273                         }
  1274                         sig.append(realSig);
  1275                         cnt.append('0');
  1276                     } else {
  1277                         sig.insert(firstPos, realSig);
  1278                         if (array) {
  1279                             sig.insert(firstPos, "_3");
  1280                         }
  1281                         returnType[0] = 'L';
  1282                     }
  1283                     i = next + 1;
  1284                     array = false;
  1285                     continue;
  1286                 case '[':
  1287                     array = true;
  1288                     continue;
  1289                 default:
  1290                     throw new IllegalStateException("Invalid char: " + ch);
  1291             }
  1292         }
  1293     }
  1294     
  1295     private static String mangleSig(String txt, int first, int last) {
  1296         StringBuilder sb = new StringBuilder();
  1297         for (int i = first; i < last; i++) {
  1298             final char ch = txt.charAt(i);
  1299             switch (ch) {
  1300                 case '/': sb.append('_'); break;
  1301                 case '_': sb.append("_1"); break;
  1302                 case ';': sb.append("_2"); break;
  1303                 case '[': sb.append("_3"); break;
  1304                 default: sb.append(ch); break;
  1305             }
  1306         }
  1307         return sb.toString();
  1308     }
  1309 
  1310     private static String findMethodName(MethodData m, StringBuilder cnt) {
  1311         StringBuilder name = new StringBuilder();
  1312         if ("<init>".equals(m.getName())) { // NOI18N
  1313             name.append("cons"); // NOI18N
  1314         } else if ("<clinit>".equals(m.getName())) { // NOI18N
  1315             name.append("class"); // NOI18N
  1316         } else {
  1317             name.append(m.getName());
  1318         } 
  1319         
  1320         countArgs(m.getInternalSig(), new char[1], name, cnt);
  1321         return name.toString();
  1322     }
  1323 
  1324     static String findMethodName(String[] mi, StringBuilder cnt, char[] returnType) {
  1325         StringBuilder name = new StringBuilder();
  1326         String descr = mi[2];//mi.getDescriptor();
  1327         String nm= mi[1];
  1328         if ("<init>".equals(nm)) { // NOI18N
  1329             name.append("cons"); // NOI18N
  1330         } else {
  1331             name.append(nm);
  1332         }
  1333         countArgs(descr, returnType, name, cnt);
  1334         return name.toString();
  1335     }
  1336 
  1337     private int invokeStaticMethod(byte[] byteCodes, int i, final StackMapper mapper, boolean isStatic)
  1338     throws IOException {
  1339         int methodIndex = readIntArg(byteCodes, i);
  1340         String[] mi = jc.getFieldInfoName(methodIndex);
  1341         char[] returnType = { 'V' };
  1342         StringBuilder cnt = new StringBuilder();
  1343         String mn = findMethodName(mi, cnt, returnType);
  1344 
  1345         final int numArguments = isStatic ? cnt.length() : cnt.length() + 1;
  1346         final Variable[] vars = new Variable[numArguments];
  1347 
  1348         for (int j = numArguments - 1; j >= 0; --j) {
  1349             vars[j] = mapper.pop();
  1350         }
  1351 
  1352         if (returnType[0] != 'V') {
  1353             out.append(mapper.pushT(VarType.fromFieldType(returnType[0])))
  1354                .append(" = ");
  1355         }
  1356 
  1357         final String in = mi[0];
  1358         out.append(accessClass(in.replace('/', '_')));
  1359         out.append("(false).");
  1360         if (mn.startsWith("cons_")) {
  1361             out.append("constructor.");
  1362         }
  1363         out.append(mn);
  1364         if (isStatic) {
  1365             out.append('(');
  1366         } else {
  1367             out.append(".call(");
  1368         }
  1369         if (numArguments > 0) {
  1370             out.append(vars[0]);
  1371             for (int j = 1; j < numArguments; ++j) {
  1372                 out.append(", ");
  1373                 out.append(vars[j]);
  1374             }
  1375         }
  1376         out.append(");");
  1377         i += 2;
  1378         addReference(in);
  1379         return i;
  1380     }
  1381     private int invokeVirtualMethod(byte[] byteCodes, int i, final StackMapper mapper)
  1382     throws IOException {
  1383         int methodIndex = readIntArg(byteCodes, i);
  1384         String[] mi = jc.getFieldInfoName(methodIndex);
  1385         char[] returnType = { 'V' };
  1386         StringBuilder cnt = new StringBuilder();
  1387         String mn = findMethodName(mi, cnt, returnType);
  1388 
  1389         final int numArguments = cnt.length() + 1;
  1390         final Variable[] vars = new Variable[numArguments];
  1391 
  1392         for (int j = numArguments - 1; j >= 0; --j) {
  1393             vars[j] = mapper.pop();
  1394         }
  1395 
  1396         if (returnType[0] != 'V') {
  1397             out.append(mapper.pushT(VarType.fromFieldType(returnType[0])))
  1398                .append(" = ");
  1399         }
  1400 
  1401         out.append(vars[0]).append('.');
  1402         out.append(mn);
  1403         out.append('(');
  1404         String sep = "";
  1405         for (int j = 1; j < numArguments; ++j) {
  1406             out.append(sep);
  1407             out.append(vars[j]);
  1408             sep = ", ";
  1409         }
  1410         out.append(");");
  1411         i += 2;
  1412         return i;
  1413     }
  1414 
  1415     private void addReference(String cn) throws IOException {
  1416         if (requireReference(cn)) {
  1417             debug(" /* needs " + cn + " */");
  1418         }
  1419     }
  1420 
  1421     private void outType(String d, StringBuilder out) {
  1422         int arr = 0;
  1423         while (d.charAt(0) == '[') {
  1424             out.append('A');
  1425             d = d.substring(1);
  1426         }
  1427         if (d.charAt(0) == 'L') {
  1428             assert d.charAt(d.length() - 1) == ';';
  1429             out.append(d.replace('/', '_').substring(0, d.length() - 1));
  1430         } else {
  1431             out.append(d);
  1432         }
  1433     }
  1434 
  1435     private String encodeConstant(int entryIndex) throws IOException {
  1436         String[] classRef = { null };
  1437         String s = jc.stringValue(entryIndex, classRef);
  1438         if (classRef[0] != null) {
  1439             addReference(classRef[0]);
  1440             s = accessClass(s.replace('/', '_')) + "(false).constructor.$class";
  1441         }
  1442         return s;
  1443     }
  1444 
  1445     private String javaScriptBody(String prefix, MethodData m, boolean isStatic) throws IOException {
  1446         byte[] arr = m.findAnnotationData(true);
  1447         if (arr == null) {
  1448             return null;
  1449         }
  1450         final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
  1451         class P extends AnnotationParser {
  1452             public P() {
  1453                 super(false);
  1454             }
  1455             
  1456             int cnt;
  1457             String[] args = new String[30];
  1458             String body;
  1459             
  1460             @Override
  1461             protected void visitAttr(String type, String attr, String at, String value) {
  1462                 if (type.equals(jvmType)) {
  1463                     if ("body".equals(attr)) {
  1464                         body = value;
  1465                     } else if ("args".equals(attr)) {
  1466                         args[cnt++] = value;
  1467                     } else {
  1468                         throw new IllegalArgumentException(attr);
  1469                     }
  1470                 }
  1471             }
  1472         }
  1473         P p = new P();
  1474         p.parse(arr, jc);
  1475         if (p.body == null) {
  1476             return null;
  1477         }
  1478         StringBuilder cnt = new StringBuilder();
  1479         final String mn = findMethodName(m, cnt);
  1480         out.append(prefix).append(mn);
  1481         out.append(" = function(");
  1482         String space = "";
  1483         int index = 0;
  1484         for (int i = 0; i < cnt.length(); i++) {
  1485             out.append(space);
  1486             space = outputArg(out, p.args, index);
  1487             index++;
  1488         }
  1489         out.append(") {").append("\n");
  1490         out.append(p.body);
  1491         out.append("\n}\n");
  1492         return mn;
  1493     }
  1494     private static String className(ClassData jc) {
  1495         //return jc.getName().getInternalName().replace('/', '_');
  1496         return jc.getClassName().replace('/', '_');
  1497     }
  1498     
  1499     private static String[] findAnnotation(
  1500         byte[] arr, ClassData cd, final String className, 
  1501         final String... attrNames
  1502     ) throws IOException {
  1503         if (arr == null) {
  1504             return null;
  1505         }
  1506         final String[] values = new String[attrNames.length];
  1507         final boolean[] found = { false };
  1508         final String jvmType = "L" + className.replace('.', '/') + ";";
  1509         AnnotationParser ap = new AnnotationParser(false) {
  1510             @Override
  1511             protected void visitAttr(String type, String attr, String at, String value) {
  1512                 if (type.equals(jvmType)) {
  1513                     found[0] = true;
  1514                     for (int i = 0; i < attrNames.length; i++) {
  1515                         if (attrNames[i].equals(attr)) {
  1516                             values[i] = value;
  1517                         }
  1518                     }
  1519                 }
  1520             }
  1521             
  1522         };
  1523         ap.parse(arr, cd);
  1524         return found[0] ? values : null;
  1525     }
  1526 
  1527     private CharSequence initField(FieldData v) {
  1528         final String is = v.getInternalSig();
  1529         if (is.length() == 1) {
  1530             switch (is.charAt(0)) {
  1531                 case 'S':
  1532                 case 'J':
  1533                 case 'B':
  1534                 case 'Z':
  1535                 case 'C':
  1536                 case 'I': return " = 0;";
  1537                 case 'F': 
  1538                 case 'D': return " = 0.0;";
  1539                 default:
  1540                     throw new IllegalStateException(is);
  1541             }
  1542         }
  1543         return " = null;";
  1544     }
  1545 
  1546     private static void generateAnno(ClassData cd, final Appendable out, byte[] data) throws IOException {
  1547         AnnotationParser ap = new AnnotationParser(true) {
  1548             int anno;
  1549             int cnt;
  1550             
  1551             @Override
  1552             protected void visitAnnotationStart(String type) throws IOException {
  1553                 if (anno++ > 0) {
  1554                     out.append(",");
  1555                 }
  1556                 out.append('"').append(type).append("\" : {\n");
  1557                 cnt = 0;
  1558             }
  1559 
  1560             @Override
  1561             protected void visitAnnotationEnd(String type) throws IOException {
  1562                 out.append("\n}\n");
  1563             }
  1564             
  1565             @Override
  1566             protected void visitAttr(String type, String attr, String attrType, String value) 
  1567             throws IOException {
  1568                 if (attr == null) {
  1569                     return;
  1570                 }
  1571                 if (cnt++ > 0) {
  1572                     out.append(",\n");
  1573                 }
  1574                 out.append(attr).append("__").append(attrType).append(" : ").append(value);
  1575             }
  1576         };
  1577         ap.parse(data, cd);
  1578     }
  1579 
  1580     private static String outputArg(Appendable out, String[] args, int indx) throws IOException {
  1581         final String name = args[indx];
  1582         if (name == null) {
  1583             return "";
  1584         }
  1585         if (name.contains(",")) {
  1586             throw new IOException("Wrong parameter with ',': " + name);
  1587         }
  1588         out.append(name);
  1589         return ",";
  1590     }
  1591 
  1592     private static void emit(final Appendable out,
  1593                              final String format,
  1594                              final CharSequence... params) throws IOException {
  1595         final int length = format.length();
  1596 
  1597         int processed = 0;
  1598         int paramOffset = format.indexOf('@');
  1599         while ((paramOffset != -1) && (paramOffset < (length - 1))) {
  1600             final char paramChar = format.charAt(paramOffset + 1);
  1601             if ((paramChar >= '1') && (paramChar <= '9')) {
  1602                 final int paramIndex = paramChar - '0' - 1;
  1603 
  1604                 out.append(format, processed, paramOffset);
  1605                 out.append(params[paramIndex]);
  1606 
  1607                 ++paramOffset;
  1608                 processed = paramOffset + 1;
  1609             }
  1610 
  1611             paramOffset = format.indexOf('@', paramOffset + 1);
  1612         }
  1613 
  1614         out.append(format, processed, length);
  1615     }
  1616 
  1617     private void generateCatch(TrapData[] traps) throws IOException {
  1618         out.append("} catch (e) {\n");
  1619         int finallyPC = -1;
  1620         for (TrapData e : traps) {
  1621             if (e == null) {
  1622                 break;
  1623             }
  1624             if (e.catch_cpx != 0) { //not finally
  1625                 final String classInternalName = jc.getClassName(e.catch_cpx);
  1626                 addReference(classInternalName);
  1627                 if ("java/lang/Throwable".equals(classInternalName)) {
  1628                     out.append("if (e.$instOf_java_lang_Throwable) {");
  1629                     out.append("  stA0 = e;");
  1630                     out.append("} else {");
  1631                     out.append("  stA0 = vm.java_lang_Throwable(true);");
  1632                     out.append("  vm.java_lang_Throwable.cons__VLjava_lang_String_2.call(stA0, e.toString());");
  1633                     out.append("}");
  1634                     out.append("gt=" + e.handler_pc + "; continue;");
  1635                 } else {
  1636                     out.append("if (e.$instOf_" + classInternalName.replace('/', '_') + ") {");
  1637                     out.append("gt=" + e.handler_pc + "; stA0 = e; continue;");
  1638                     out.append("}\n");
  1639                 }
  1640             } else {
  1641                 finallyPC = e.handler_pc;
  1642             }
  1643         }
  1644         if (finallyPC == -1) {
  1645             out.append("throw e;");
  1646         } else {
  1647             out.append("gt=" + finallyPC + "; stA0 = e; continue;");
  1648         }
  1649         out.append("\n}");
  1650     }
  1651 }