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