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