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