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