vm/src/main/java/org/apidesign/vm4brwsr/ByteCodeToJavaScript.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Wed, 17 Oct 2012 15:59:04 +0200
changeset 115 3d5597011af0
parent 106 346633cd13d6
child 127 5134b17d623c
permissions -rw-r--r--
Support for switch
jaroslav@106
     1
/**
jaroslav@106
     2
 * Back 2 Browser Bytecode Translator
jaroslav@106
     3
 * Copyright (C) 2012 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
jaroslav@106
     4
 *
jaroslav@106
     5
 * This program is free software: you can redistribute it and/or modify
jaroslav@106
     6
 * it under the terms of the GNU General Public License as published by
jaroslav@106
     7
 * the Free Software Foundation, version 2 of the License.
jaroslav@106
     8
 *
jaroslav@106
     9
 * This program is distributed in the hope that it will be useful,
jaroslav@106
    10
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
jaroslav@106
    11
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
jaroslav@106
    12
 * GNU General Public License for more details.
jaroslav@106
    13
 *
jaroslav@106
    14
 * You should have received a copy of the GNU General Public License
jaroslav@106
    15
 * along with this program. Look for COPYING file in the top folder.
jaroslav@106
    16
 * If not, see http://opensource.org/licenses/GPL-2.0.
jaroslav@106
    17
 */
jaroslav@0
    18
/*
jaroslav@0
    19
Java 4 Browser Bytecode Translator
jaroslav@0
    20
Copyright (C) 2012-2012 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
jaroslav@0
    21
jaroslav@0
    22
This program is free software: you can redistribute it and/or modify
jaroslav@0
    23
it under the terms of the GNU General Public License as published by
jaroslav@0
    24
the Free Software Foundation, version 2 of the License.
jaroslav@0
    25
jaroslav@0
    26
This program is distributed in the hope that it will be useful,
jaroslav@0
    27
but WITHOUT ANY WARRANTY; without even the implied warranty of
jaroslav@0
    28
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
jaroslav@0
    29
GNU General Public License for more details.
jaroslav@0
    30
jaroslav@0
    31
You should have received a copy of the GNU General Public License
jaroslav@0
    32
along with this program. Look for COPYING file in the top folder.
jaroslav@0
    33
If not, see http://opensource.org/licenses/GPL-2.0.
jaroslav@0
    34
*/
jaroslav@22
    35
package org.apidesign.vm4brwsr;
jaroslav@0
    36
jaroslav@0
    37
import java.io.IOException;
jaroslav@0
    38
import java.io.InputStream;
jaroslav@21
    39
import java.util.ArrayList;
jaroslav@18
    40
import java.util.Collection;
jaroslav@0
    41
import java.util.List;
jaroslav@91
    42
import org.apidesign.bck2brwsr.core.ExtraJavaScript;
jaroslav@94
    43
import org.apidesign.bck2brwsr.core.JavaScriptBody;
jaroslav@91
    44
import org.netbeans.modules.classfile.Annotation;
jaroslav@91
    45
import org.netbeans.modules.classfile.AnnotationComponent;
jaroslav@94
    46
import org.netbeans.modules.classfile.ArrayElementValue;
jaroslav@2
    47
import static org.netbeans.modules.classfile.ByteCodes.*;
jaroslav@8
    48
import org.netbeans.modules.classfile.CPClassInfo;
jaroslav@8
    49
import org.netbeans.modules.classfile.CPEntry;
jaroslav@8
    50
import org.netbeans.modules.classfile.CPFieldInfo;
jaroslav@4
    51
import org.netbeans.modules.classfile.CPMethodInfo;
jaroslav@21
    52
import org.netbeans.modules.classfile.CPStringInfo;
jaroslav@0
    53
import org.netbeans.modules.classfile.ClassFile;
jaroslav@13
    54
import org.netbeans.modules.classfile.ClassName;
jaroslav@0
    55
import org.netbeans.modules.classfile.Code;
jaroslav@91
    56
import org.netbeans.modules.classfile.ElementValue;
jaroslav@0
    57
import org.netbeans.modules.classfile.Method;
jaroslav@0
    58
import org.netbeans.modules.classfile.Parameter;
jaroslav@91
    59
import org.netbeans.modules.classfile.PrimitiveElementValue;
jaroslav@9
    60
import org.netbeans.modules.classfile.Variable;
jaroslav@0
    61
jaroslav@0
    62
/** Translator of the code inside class files to JavaScript.
jaroslav@0
    63
 *
jaroslav@0
    64
 * @author Jaroslav Tulach <jtulach@netbeans.org>
jaroslav@0
    65
 */
jaroslav@0
    66
public final class ByteCodeToJavaScript {
jaroslav@0
    67
    private final ClassFile jc;
jaroslav@0
    68
    private final Appendable out;
jaroslav@18
    69
    private final Collection<? super String> references;
jaroslav@0
    70
jaroslav@18
    71
    private ByteCodeToJavaScript(
jaroslav@18
    72
        ClassFile jc, Appendable out, Collection<? super String> references
jaroslav@18
    73
    ) {
jaroslav@0
    74
        this.jc = jc;
jaroslav@0
    75
        this.out = out;
jaroslav@18
    76
        this.references = references;
jaroslav@0
    77
    }
jaroslav@18
    78
jaroslav@18
    79
    /**
jaroslav@18
    80
     * Converts a given class file to a JavaScript version.
jaroslav@18
    81
     *
jaroslav@0
    82
     * @param classFile input stream with code of the .class file
jaroslav@0
    83
     * @param out a {@link StringBuilder} or similar to generate the output to
jaroslav@18
    84
     * @param references a write only collection where the system adds list of
jaroslav@18
    85
     *   other classes that were referenced and should be loaded in order the
jaroslav@18
    86
     *   generated JavaScript code works properly. The names are in internal 
jaroslav@18
    87
     *   JVM form so String is <code>java/lang/String</code>. Can be <code>null</code>
jaroslav@18
    88
     *   if one is not interested in knowing references
jaroslav@91
    89
     * @param scripts write only collection with names of resources to read
jaroslav@97
    90
     * @return the initialization code for this class, if any. Otherwise <code>null</code>
jaroslav@91
    91
     * 
jaroslav@0
    92
     * @throws IOException if something goes wrong during read or write or translating
jaroslav@0
    93
     */
jaroslav@18
    94
    
jaroslav@97
    95
    public static String compile(
jaroslav@18
    96
        InputStream classFile, Appendable out,
jaroslav@91
    97
        Collection<? super String> references,
jaroslav@91
    98
        Collection<? super String> scripts
jaroslav@18
    99
    ) throws IOException {
jaroslav@0
   100
        ClassFile jc = new ClassFile(classFile, true);
jaroslav@91
   101
        final ClassName extraAnn = ClassName.getClassName(ExtraJavaScript.class.getName().replace('.', '/'));
jaroslav@91
   102
        Annotation a = jc.getAnnotation(extraAnn);
jaroslav@91
   103
        if (a != null) {
jaroslav@91
   104
            final ElementValue annVal = a.getComponent("resource").getValue();
jaroslav@91
   105
            String res = ((PrimitiveElementValue)annVal).getValue().getValue().toString();
jaroslav@91
   106
            scripts.add(res);
jaroslav@91
   107
            final AnnotationComponent process = a.getComponent("processByteCode");
jaroslav@93
   108
            if (process != null && "const=0".equals(process.getValue().toString())) {
jaroslav@97
   109
                return null;
jaroslav@91
   110
            }
jaroslav@91
   111
        }
jaroslav@91
   112
        
jaroslav@18
   113
        ByteCodeToJavaScript compiler = new ByteCodeToJavaScript(
jaroslav@18
   114
            jc, out, references
jaroslav@18
   115
        );
jaroslav@21
   116
        List<String> toInitilize = new ArrayList<String>();
jaroslav@0
   117
        for (Method m : jc.getMethods()) {
jaroslav@0
   118
            if (m.isStatic()) {
jaroslav@21
   119
                compiler.generateStaticMethod(m, toInitilize);
jaroslav@10
   120
            } else {
jaroslav@10
   121
                compiler.generateInstanceMethod(m);
jaroslav@0
   122
            }
jaroslav@0
   123
        }
jaroslav@9
   124
        for (Variable v : jc.getVariables()) {
jaroslav@9
   125
            if (v.isStatic()) {
jaroslav@9
   126
                compiler.generateStaticField(v);
jaroslav@9
   127
            }
jaroslav@9
   128
        }
jaroslav@10
   129
        
jaroslav@18
   130
        final String className = jc.getName().getInternalName().replace('/', '_');
jaroslav@13
   131
        out.append("\nfunction ").append(className);
jaroslav@10
   132
        out.append("() {");
jaroslav@10
   133
        for (Variable v : jc.getVariables()) {
jaroslav@10
   134
            if (!v.isStatic()) {
jaroslav@10
   135
                out.append("\n  this." + v.getName() + " = 0;");
jaroslav@10
   136
            }
jaroslav@10
   137
        }
jaroslav@98
   138
        out.append("\n}\n\nfunction ").append(className).append("_proto() {");
jaroslav@98
   139
        out.append("\n  if (").append(className).
jaroslav@98
   140
            append(".prototype.$instOf_").append(className).append(") {");
jaroslav@98
   141
        out.append("\n    return ").append(className).append(".prototype;");
jaroslav@98
   142
        out.append("\n  }");
jaroslav@13
   143
        ClassName sc = jc.getSuperClass();
jaroslav@13
   144
        if (sc != null) {
jaroslav@98
   145
            out.append("\n  ").append(sc.getInternalName().replace('/', '_')).append("_proto();");
jaroslav@98
   146
            out.append("\n  ").append(className)
jaroslav@39
   147
               .append(".prototype = new ").append(sc.getInternalName().replace('/', '_')).append(';');
jaroslav@13
   148
        }
jaroslav@38
   149
        for (Method m : jc.getMethods()) {
jaroslav@102
   150
            if (!m.getName().contains("<init>") && !m.getName().contains("<cinit>")) {
jaroslav@98
   151
                compiler.generateMethodReference("\n  " + className + ".prototype.", m);
jaroslav@38
   152
            }
jaroslav@38
   153
        }
jaroslav@98
   154
        out.append("\n  " + className + ".prototype.$instOf_").append(className).append(" = true;");
jaroslav@40
   155
        for (ClassName superInterface : jc.getInterfaces()) {
jaroslav@98
   156
            out.append("\n  " + className + ".prototype.$instOf_").append(superInterface.getInternalName().replace('/', '_')).append(" = true;");
jaroslav@40
   157
        }
jaroslav@98
   158
        out.append("\n  return ").append(className).append(".prototype;");
jaroslav@98
   159
        out.append("\n}");
jaroslav@98
   160
        out.append("\n").append(className).append("_proto();");
jaroslav@97
   161
        StringBuilder sb = new StringBuilder();
jaroslav@21
   162
        for (String init : toInitilize) {
jaroslav@97
   163
            sb.append("\n").append(init).append("();");
jaroslav@21
   164
        }
jaroslav@97
   165
        return sb.toString();
jaroslav@0
   166
    }
jaroslav@21
   167
    private void generateStaticMethod(Method m, List<String> toInitilize) throws IOException {
jaroslav@94
   168
        if (javaScriptBody(m, true)) {
jaroslav@94
   169
            return;
jaroslav@94
   170
        }
jaroslav@21
   171
        final String mn = findMethodName(m);
jaroslav@1
   172
        out.append("\nfunction ").append(
jaroslav@18
   173
            jc.getName().getInternalName().replace('/', '_')
jaroslav@21
   174
        ).append('_').append(mn);
jaroslav@21
   175
        if (mn.equals("classV")) {
jaroslav@21
   176
            toInitilize.add(jc.getName().getInternalName().replace('/', '_') + '_' + mn);
jaroslav@21
   177
        }
jaroslav@0
   178
        out.append('(');
jaroslav@0
   179
        String space = "";
jaroslav@10
   180
        List<Parameter> args = m.getParameters();
jaroslav@2
   181
        for (int index = 0, i = 0; i < args.size(); i++) {
jaroslav@0
   182
            out.append(space);
jaroslav@2
   183
            out.append("arg").append(String.valueOf(index));
jaroslav@0
   184
            space = ",";
jaroslav@32
   185
            final String desc = findDescriptor(args.get(i).getDescriptor());
jaroslav@3
   186
            if ("D".equals(desc) || "J".equals(desc)) {
jaroslav@2
   187
                index += 2;
jaroslav@2
   188
            } else {
jaroslav@2
   189
                index++;
jaroslav@2
   190
            }
jaroslav@0
   191
        }
jaroslav@5
   192
        out.append(") {").append("\n");
jaroslav@0
   193
        final Code code = m.getCode();
jaroslav@18
   194
        if (code != null) {
jaroslav@18
   195
            int len = code.getMaxLocals();
jaroslav@18
   196
            for (int index = args.size(), i = args.size(); i < len; i++) {
jaroslav@18
   197
                out.append("  var ");
jaroslav@18
   198
                out.append("arg").append(String.valueOf(i)).append(";\n");
jaroslav@18
   199
            }
jaroslav@21
   200
            out.append("  var stack = new Array();\n");
jaroslav@18
   201
            produceCode(code.getByteCodes());
jaroslav@18
   202
        } else {
jaroslav@18
   203
            out.append("  /* no code found for ").append(m.getTypeSignature()).append(" */\n");
jaroslav@0
   204
        }
jaroslav@10
   205
        out.append("}");
jaroslav@10
   206
    }
jaroslav@10
   207
    
jaroslav@38
   208
    private void generateMethodReference(String prefix, Method m) throws IOException {
jaroslav@12
   209
        final String name = findMethodName(m);
jaroslav@38
   210
        out.append(prefix).append(name).append(" = ")
jaroslav@18
   211
           .append(jc.getName().getInternalName().replace('/', '_'))
jaroslav@12
   212
           .append('_').append(name).append(";");
jaroslav@12
   213
    }
jaroslav@12
   214
    
jaroslav@10
   215
    private void generateInstanceMethod(Method m) throws IOException {
jaroslav@94
   216
        if (javaScriptBody(m, false)) {
jaroslav@94
   217
            return;
jaroslav@94
   218
        }
jaroslav@10
   219
        out.append("\nfunction ").append(
jaroslav@18
   220
            jc.getName().getInternalName().replace('/', '_')
jaroslav@10
   221
        ).append('_').append(findMethodName(m));
jaroslav@10
   222
        out.append("(arg0");
jaroslav@10
   223
        String space = ",";
jaroslav@10
   224
        List<Parameter> args = m.getParameters();
jaroslav@10
   225
        for (int index = 1, i = 0; i < args.size(); i++) {
jaroslav@10
   226
            out.append(space);
jaroslav@10
   227
            out.append("arg").append(String.valueOf(index));
jaroslav@32
   228
            final String desc = findDescriptor(args.get(i).getDescriptor());
jaroslav@10
   229
            if ("D".equals(desc) || "J".equals(desc)) {
jaroslav@10
   230
                index += 2;
jaroslav@10
   231
            } else {
jaroslav@10
   232
                index++;
jaroslav@10
   233
            }
jaroslav@10
   234
        }
jaroslav@10
   235
        out.append(") {").append("\n");
jaroslav@10
   236
        final Code code = m.getCode();
jaroslav@18
   237
        if (code != null) {
jaroslav@18
   238
            int len = code.getMaxLocals();
jaroslav@18
   239
            for (int index = args.size(), i = args.size(); i < len; i++) {
jaroslav@18
   240
                out.append("  var ");
jaroslav@18
   241
                out.append("arg").append(String.valueOf(i + 1)).append(";\n");
jaroslav@18
   242
            }
jaroslav@96
   243
            out.append(";\n  var stack = new Array();\n");
jaroslav@18
   244
            produceCode(code.getByteCodes());
jaroslav@18
   245
        } else {
jaroslav@18
   246
            out.append("  /* no code found for ").append(m.getTypeSignature()).append(" */\n");
jaroslav@10
   247
        }
jaroslav@0
   248
        out.append("}");
jaroslav@0
   249
    }
jaroslav@0
   250
jaroslav@0
   251
    private void produceCode(byte[] byteCodes) throws IOException {
jaroslav@10
   252
        out.append("\n  var gt = 0;\n  for(;;) switch(gt) {\n");
jaroslav@0
   253
        for (int i = 0; i < byteCodes.length; i++) {
jaroslav@0
   254
            int prev = i;
jaroslav@10
   255
            out.append("    case " + i).append(": ");
jaroslav@0
   256
            final int c = (byteCodes[i] + 256) % 256;
jaroslav@0
   257
            switch (c) {
jaroslav@2
   258
                case bc_aload_0:
jaroslav@2
   259
                case bc_iload_0:
jaroslav@2
   260
                case bc_lload_0:
jaroslav@2
   261
                case bc_fload_0:
jaroslav@2
   262
                case bc_dload_0:
jaroslav@0
   263
                    out.append("stack.push(arg0);");
jaroslav@0
   264
                    break;
jaroslav@2
   265
                case bc_aload_1:
jaroslav@2
   266
                case bc_iload_1:
jaroslav@2
   267
                case bc_lload_1:
jaroslav@2
   268
                case bc_fload_1:
jaroslav@2
   269
                case bc_dload_1:
jaroslav@0
   270
                    out.append("stack.push(arg1);");
jaroslav@0
   271
                    break;
jaroslav@2
   272
                case bc_aload_2:
jaroslav@2
   273
                case bc_iload_2:
jaroslav@2
   274
                case bc_lload_2:
jaroslav@2
   275
                case bc_fload_2:
jaroslav@2
   276
                case bc_dload_2:
jaroslav@2
   277
                    out.append("stack.push(arg2);");
jaroslav@2
   278
                    break;
jaroslav@3
   279
                case bc_aload_3:
jaroslav@3
   280
                case bc_iload_3:
jaroslav@3
   281
                case bc_lload_3:
jaroslav@3
   282
                case bc_fload_3:
jaroslav@3
   283
                case bc_dload_3:
jaroslav@3
   284
                    out.append("stack.push(arg3);");
jaroslav@3
   285
                    break;
jaroslav@3
   286
                case bc_iload:
jaroslav@3
   287
                case bc_lload:
jaroslav@3
   288
                case bc_fload:
jaroslav@3
   289
                case bc_dload:
jaroslav@3
   290
                case bc_aload: {
jaroslav@3
   291
                    final int indx = (byteCodes[++i] + 256) % 256;
jaroslav@3
   292
                    out.append("stack.push(arg").append(indx + ");");
jaroslav@3
   293
                    break;
jaroslav@3
   294
                }
jaroslav@31
   295
                case bc_istore:
jaroslav@31
   296
                case bc_lstore:
jaroslav@31
   297
                case bc_fstore:
jaroslav@31
   298
                case bc_dstore:
jaroslav@31
   299
                case bc_astore: {
jaroslav@31
   300
                    final int indx = (byteCodes[++i] + 256) % 256;
jaroslav@31
   301
                    out.append("arg" + indx).append(" = stack.pop()");
jaroslav@31
   302
                    break;
jaroslav@31
   303
                }
jaroslav@8
   304
                case bc_astore_0:
jaroslav@5
   305
                case bc_istore_0:
jaroslav@5
   306
                case bc_lstore_0:
jaroslav@5
   307
                case bc_fstore_0:
jaroslav@5
   308
                case bc_dstore_0:
jaroslav@5
   309
                    out.append("arg0 = stack.pop();");
jaroslav@5
   310
                    break;
jaroslav@8
   311
                case bc_astore_1:
jaroslav@5
   312
                case bc_istore_1:
jaroslav@5
   313
                case bc_lstore_1:
jaroslav@5
   314
                case bc_fstore_1:
jaroslav@5
   315
                case bc_dstore_1:
jaroslav@5
   316
                    out.append("arg1 = stack.pop();");
jaroslav@5
   317
                    break;
jaroslav@8
   318
                case bc_astore_2:
jaroslav@5
   319
                case bc_istore_2:
jaroslav@5
   320
                case bc_lstore_2:
jaroslav@5
   321
                case bc_fstore_2:
jaroslav@5
   322
                case bc_dstore_2:
jaroslav@5
   323
                    out.append("arg2 = stack.pop();");
jaroslav@5
   324
                    break;
jaroslav@8
   325
                case bc_astore_3:
jaroslav@5
   326
                case bc_istore_3:
jaroslav@5
   327
                case bc_lstore_3:
jaroslav@5
   328
                case bc_fstore_3:
jaroslav@5
   329
                case bc_dstore_3:
jaroslav@5
   330
                    out.append("arg3 = stack.pop();");
jaroslav@5
   331
                    break;
jaroslav@2
   332
                case bc_iadd:
jaroslav@2
   333
                case bc_ladd:
jaroslav@2
   334
                case bc_fadd:
jaroslav@2
   335
                case bc_dadd:
jaroslav@0
   336
                    out.append("stack.push(stack.pop() + stack.pop());");
jaroslav@0
   337
                    break;
jaroslav@2
   338
                case bc_isub:
jaroslav@2
   339
                case bc_lsub:
jaroslav@2
   340
                case bc_fsub:
jaroslav@2
   341
                case bc_dsub:
jaroslav@3
   342
                    out.append("{ var tmp = stack.pop(); stack.push(stack.pop() - tmp); }");
jaroslav@2
   343
                    break;
jaroslav@2
   344
                case bc_imul:
jaroslav@2
   345
                case bc_lmul:
jaroslav@2
   346
                case bc_fmul:
jaroslav@2
   347
                case bc_dmul:
jaroslav@1
   348
                    out.append("stack.push(stack.pop() * stack.pop());");
jaroslav@1
   349
                    break;
jaroslav@3
   350
                case bc_idiv:
jaroslav@3
   351
                case bc_ldiv:
jaroslav@3
   352
                    out.append("{ var tmp = stack.pop(); stack.push(Math.floor(stack.pop() / tmp)); }");
jaroslav@3
   353
                    break;
jaroslav@3
   354
                case bc_fdiv:
jaroslav@3
   355
                case bc_ddiv:
jaroslav@3
   356
                    out.append("{ var tmp = stack.pop(); stack.push(stack.pop() / tmp); }");
jaroslav@3
   357
                    break;
jaroslav@7
   358
                case bc_iand:
jaroslav@7
   359
                case bc_land:
jaroslav@7
   360
                    out.append("stack.push(stack.pop() & stack.pop());");
jaroslav@7
   361
                    break;
jaroslav@7
   362
                case bc_ior:
jaroslav@7
   363
                case bc_lor:
jaroslav@7
   364
                    out.append("stack.push(stack.pop() | stack.pop());");
jaroslav@7
   365
                    break;
jaroslav@6
   366
                case bc_ixor:
jaroslav@6
   367
                case bc_lxor:
jaroslav@6
   368
                    out.append("stack.push(stack.pop() ^ stack.pop());");
jaroslav@6
   369
                    break;
jaroslav@93
   370
                case bc_ineg:
jaroslav@93
   371
                case bc_lneg:
jaroslav@93
   372
                case bc_fneg:
jaroslav@93
   373
                case bc_dneg:
jaroslav@93
   374
                    out.append("stack.push(- stack.pop());");
jaroslav@93
   375
                    break;
jaroslav@93
   376
                case bc_ishl:
jaroslav@93
   377
                case bc_lshl:
jaroslav@93
   378
                    out.append("{ var v = stack.pop(); stack.push(stack.pop() << v); }");
jaroslav@93
   379
                    break;
jaroslav@93
   380
                case bc_ishr:
jaroslav@93
   381
                case bc_lshr:
jaroslav@93
   382
                    out.append("{ var v = stack.pop(); stack.push(stack.pop() >> v); }");
jaroslav@93
   383
                    break;
jaroslav@93
   384
                case bc_iushr:
jaroslav@93
   385
                case bc_lushr:
jaroslav@93
   386
                    out.append("{ var v = stack.pop(); stack.push(stack.pop() >>> v); }");
jaroslav@93
   387
                    break;
jaroslav@5
   388
                case bc_iinc: {
jaroslav@5
   389
                    final int varIndx = (byteCodes[++i] + 256) % 256;
jaroslav@104
   390
                    final int incrBy = byteCodes[++i];
jaroslav@5
   391
                    if (incrBy == 1) {
jaroslav@5
   392
                        out.append("arg" + varIndx).append("++;");
jaroslav@5
   393
                    } else {
jaroslav@5
   394
                        out.append("arg" + varIndx).append(" += " + incrBy).append(";");
jaroslav@5
   395
                    }
jaroslav@5
   396
                    break;
jaroslav@5
   397
                }
jaroslav@10
   398
                case bc_return:
jaroslav@10
   399
                    out.append("return;");
jaroslav@10
   400
                    break;
jaroslav@2
   401
                case bc_ireturn:
jaroslav@2
   402
                case bc_lreturn:
jaroslav@2
   403
                case bc_freturn:
jaroslav@2
   404
                case bc_dreturn:
jaroslav@10
   405
                case bc_areturn:
jaroslav@0
   406
                    out.append("return stack.pop();");
jaroslav@1
   407
                    break;
jaroslav@2
   408
                case bc_i2l:
jaroslav@2
   409
                case bc_i2f:
jaroslav@2
   410
                case bc_i2d:
jaroslav@2
   411
                case bc_l2i:
jaroslav@3
   412
                    // max int check?
jaroslav@2
   413
                case bc_l2f:
jaroslav@2
   414
                case bc_l2d:
jaroslav@3
   415
                case bc_f2d:
jaroslav@3
   416
                case bc_d2f:
jaroslav@3
   417
                    out.append("/* number conversion */");
jaroslav@3
   418
                    break;
jaroslav@2
   419
                case bc_f2i:
jaroslav@2
   420
                case bc_f2l:
jaroslav@2
   421
                case bc_d2i:
jaroslav@2
   422
                case bc_d2l:
jaroslav@3
   423
                    out.append("stack.push(Math.floor(stack.pop()));");
jaroslav@3
   424
                    break;
jaroslav@2
   425
                case bc_i2b:
jaroslav@2
   426
                case bc_i2c:
jaroslav@2
   427
                case bc_i2s:
jaroslav@2
   428
                    out.append("/* number conversion */");
jaroslav@2
   429
                    break;
jaroslav@46
   430
                case bc_aconst_null:
jaroslav@46
   431
                    out.append("stack.push(null);");
jaroslav@46
   432
                    break;
jaroslav@48
   433
                case bc_iconst_m1:
jaroslav@48
   434
                    out.append("stack.push(-1);");
jaroslav@48
   435
                    break;
jaroslav@4
   436
                case bc_iconst_0:
jaroslav@4
   437
                case bc_dconst_0:
jaroslav@4
   438
                case bc_lconst_0:
jaroslav@4
   439
                case bc_fconst_0:
jaroslav@4
   440
                    out.append("stack.push(0);");
jaroslav@4
   441
                    break;
jaroslav@4
   442
                case bc_iconst_1:
jaroslav@4
   443
                case bc_lconst_1:
jaroslav@4
   444
                case bc_fconst_1:
jaroslav@4
   445
                case bc_dconst_1:
jaroslav@4
   446
                    out.append("stack.push(1);");
jaroslav@4
   447
                    break;
jaroslav@4
   448
                case bc_iconst_2:
jaroslav@4
   449
                case bc_fconst_2:
jaroslav@4
   450
                    out.append("stack.push(2);");
jaroslav@4
   451
                    break;
jaroslav@4
   452
                case bc_iconst_3:
jaroslav@4
   453
                    out.append("stack.push(3);");
jaroslav@4
   454
                    break;
jaroslav@4
   455
                case bc_iconst_4:
jaroslav@4
   456
                    out.append("stack.push(4);");
jaroslav@4
   457
                    break;
jaroslav@4
   458
                case bc_iconst_5:
jaroslav@4
   459
                    out.append("stack.push(5);");
jaroslav@4
   460
                    break;
jaroslav@20
   461
                case bc_ldc: {
jaroslav@21
   462
                    int indx = byteCodes[++i];
jaroslav@20
   463
                    CPEntry entry = jc.getConstantPool().get(indx);
jaroslav@21
   464
                    String v = encodeConstant(entry);
jaroslav@21
   465
                    out.append("stack.push(").append(v).append(");");
jaroslav@20
   466
                    break;
jaroslav@20
   467
                }
jaroslav@8
   468
                case bc_ldc_w:
jaroslav@8
   469
                case bc_ldc2_w: {
jaroslav@8
   470
                    int indx = readIntArg(byteCodes, i);
jaroslav@8
   471
                    CPEntry entry = jc.getConstantPool().get(indx);
jaroslav@8
   472
                    i += 2;
jaroslav@21
   473
                    String v = encodeConstant(entry);
jaroslav@21
   474
                    out.append("stack.push(").append(v).append(");");
jaroslav@8
   475
                    break;
jaroslav@8
   476
                }
jaroslav@20
   477
                case bc_lcmp:
jaroslav@20
   478
                case bc_fcmpl:
jaroslav@20
   479
                case bc_fcmpg:
jaroslav@20
   480
                case bc_dcmpl:
jaroslav@20
   481
                case bc_dcmpg: {
jaroslav@20
   482
                    out.append("{ var delta = stack.pop() - stack.pop(); stack.push(delta < 0 ?-1 : (delta == 0 ? 0 : 1)); }");
jaroslav@20
   483
                    break;
jaroslav@20
   484
                }
jaroslav@104
   485
                case bc_if_acmpeq:
jaroslav@104
   486
                    i = generateIf(byteCodes, i, "===");
jaroslav@104
   487
                    break;
jaroslav@104
   488
                case bc_if_acmpne:
jaroslav@104
   489
                    i = generateIf(byteCodes, i, "!=");
jaroslav@104
   490
                    break;
jaroslav@4
   491
                case bc_if_icmpeq: {
jaroslav@4
   492
                    i = generateIf(byteCodes, i, "==");
jaroslav@4
   493
                    break;
jaroslav@4
   494
                }
jaroslav@7
   495
                case bc_ifeq: {
jaroslav@7
   496
                    int indx = i + readIntArg(byteCodes, i);
jaroslav@7
   497
                    out.append("if (stack.pop() == 0) { gt = " + indx);
jaroslav@7
   498
                    out.append("; continue; }");
jaroslav@7
   499
                    i += 2;
jaroslav@7
   500
                    break;
jaroslav@7
   501
                }
jaroslav@20
   502
                case bc_ifne: {
jaroslav@20
   503
                    int indx = i + readIntArg(byteCodes, i);
jaroslav@20
   504
                    out.append("if (stack.pop() != 0) { gt = " + indx);
jaroslav@20
   505
                    out.append("; continue; }");
jaroslav@20
   506
                    i += 2;
jaroslav@20
   507
                    break;
jaroslav@20
   508
                }
jaroslav@20
   509
                case bc_iflt: {
jaroslav@20
   510
                    int indx = i + readIntArg(byteCodes, i);
jaroslav@20
   511
                    out.append("if (stack.pop() < 0) { gt = " + indx);
jaroslav@20
   512
                    out.append("; continue; }");
jaroslav@20
   513
                    i += 2;
jaroslav@20
   514
                    break;
jaroslav@20
   515
                }
jaroslav@20
   516
                case bc_ifle: {
jaroslav@20
   517
                    int indx = i + readIntArg(byteCodes, i);
jaroslav@20
   518
                    out.append("if (stack.pop() <= 0) { gt = " + indx);
jaroslav@20
   519
                    out.append("; continue; }");
jaroslav@20
   520
                    i += 2;
jaroslav@20
   521
                    break;
jaroslav@20
   522
                }
jaroslav@20
   523
                case bc_ifgt: {
jaroslav@20
   524
                    int indx = i + readIntArg(byteCodes, i);
jaroslav@20
   525
                    out.append("if (stack.pop() > 0) { gt = " + indx);
jaroslav@20
   526
                    out.append("; continue; }");
jaroslav@20
   527
                    i += 2;
jaroslav@20
   528
                    break;
jaroslav@20
   529
                }
jaroslav@20
   530
                case bc_ifge: {
jaroslav@20
   531
                    int indx = i + readIntArg(byteCodes, i);
jaroslav@20
   532
                    out.append("if (stack.pop() >= 0) { gt = " + indx);
jaroslav@20
   533
                    out.append("; continue; }");
jaroslav@20
   534
                    i += 2;
jaroslav@20
   535
                    break;
jaroslav@20
   536
                }
jaroslav@16
   537
                case bc_ifnonnull: {
jaroslav@16
   538
                    int indx = i + readIntArg(byteCodes, i);
jaroslav@16
   539
                    out.append("if (stack.pop()) { gt = " + indx);
jaroslav@16
   540
                    out.append("; continue; }");
jaroslav@16
   541
                    i += 2;
jaroslav@16
   542
                    break;
jaroslav@16
   543
                }
jaroslav@16
   544
                case bc_ifnull: {
jaroslav@16
   545
                    int indx = i + readIntArg(byteCodes, i);
jaroslav@16
   546
                    out.append("if (!stack.pop()) { gt = " + indx);
jaroslav@16
   547
                    out.append("; continue; }");
jaroslav@16
   548
                    i += 2;
jaroslav@16
   549
                    break;
jaroslav@16
   550
                }
jaroslav@4
   551
                case bc_if_icmpne:
jaroslav@4
   552
                    i = generateIf(byteCodes, i, "!=");
jaroslav@4
   553
                    break;
jaroslav@4
   554
                case bc_if_icmplt:
jaroslav@4
   555
                    i = generateIf(byteCodes, i, ">");
jaroslav@4
   556
                    break;
jaroslav@4
   557
                case bc_if_icmple:
jaroslav@4
   558
                    i = generateIf(byteCodes, i, ">=");
jaroslav@4
   559
                    break;
jaroslav@4
   560
                case bc_if_icmpgt:
jaroslav@4
   561
                    i = generateIf(byteCodes, i, "<");
jaroslav@4
   562
                    break;
jaroslav@4
   563
                case bc_if_icmpge:
jaroslav@4
   564
                    i = generateIf(byteCodes, i, "<=");
jaroslav@4
   565
                    break;
jaroslav@5
   566
                case bc_goto: {
jaroslav@5
   567
                    int indx = i + readIntArg(byteCodes, i);
jaroslav@5
   568
                    out.append("gt = " + indx).append("; continue;");
jaroslav@5
   569
                    i += 2;
jaroslav@5
   570
                    break;
jaroslav@5
   571
                }
jaroslav@115
   572
                case bc_lookupswitch: {
jaroslav@115
   573
                    int table = (i - 1) / 4 * 4 + 4;
jaroslav@115
   574
                    int dflt = i + readInt4(byteCodes, table);
jaroslav@115
   575
                    table += 4;
jaroslav@115
   576
                    int n = readInt4(byteCodes, table);
jaroslav@115
   577
                    table += 4;
jaroslav@115
   578
                    out.append("switch (stack.pop()) {\n");
jaroslav@115
   579
                    while (n-- > 0) {
jaroslav@115
   580
                        int cnstnt = readInt4(byteCodes, table);
jaroslav@115
   581
                        table += 4;
jaroslav@115
   582
                        int offset = i + readInt4(byteCodes, table);
jaroslav@115
   583
                        table += 4;
jaroslav@115
   584
                        out.append("  case " + cnstnt).append(": gt = " + offset).append("; continue;\n");
jaroslav@115
   585
                    }
jaroslav@115
   586
                    out.append("  default: gt = " + dflt).append("; continue;\n}");
jaroslav@115
   587
                    i = table - 1;
jaroslav@115
   588
                    break;
jaroslav@115
   589
                }
jaroslav@115
   590
                case bc_tableswitch: {
jaroslav@115
   591
                    int table = (i - 1) / 4 * 4 + 4;
jaroslav@115
   592
                    int dflt = i + readInt4(byteCodes, table);
jaroslav@115
   593
                    table += 4;
jaroslav@115
   594
                    int low = readInt4(byteCodes, table);
jaroslav@115
   595
                    table += 4;
jaroslav@115
   596
                    int high = readInt4(byteCodes, table);
jaroslav@115
   597
                    table += 4;
jaroslav@115
   598
                    out.append("switch (stack.pop()) {\n");
jaroslav@115
   599
                    while (low <= high) {
jaroslav@115
   600
                        int offset = i + readInt4(byteCodes, table);
jaroslav@115
   601
                        table += 4;
jaroslav@115
   602
                        out.append("  case " + low).append(": gt = " + offset).append("; continue;\n");
jaroslav@115
   603
                        low++;
jaroslav@115
   604
                    }
jaroslav@115
   605
                    out.append("  default: gt = " + dflt).append("; continue;\n}");
jaroslav@115
   606
                    i = table - 1;
jaroslav@115
   607
                    break;
jaroslav@115
   608
                }
jaroslav@46
   609
                case bc_invokeinterface: {
jaroslav@46
   610
                    i = invokeVirtualMethod(byteCodes, i) + 2;
jaroslav@46
   611
                    break;
jaroslav@46
   612
                }
jaroslav@12
   613
                case bc_invokevirtual:
jaroslav@12
   614
                    i = invokeVirtualMethod(byteCodes, i);
jaroslav@12
   615
                    break;
jaroslav@10
   616
                case bc_invokespecial:
jaroslav@10
   617
                    i = invokeStaticMethod(byteCodes, i, false);
jaroslav@4
   618
                    break;
jaroslav@10
   619
                case bc_invokestatic:
jaroslav@10
   620
                    i = invokeStaticMethod(byteCodes, i, true);
jaroslav@10
   621
                    break;
jaroslav@8
   622
                case bc_new: {
jaroslav@8
   623
                    int indx = readIntArg(byteCodes, i);
jaroslav@8
   624
                    CPClassInfo ci = jc.getConstantPool().getClass(indx);
jaroslav@8
   625
                    out.append("stack.push(");
jaroslav@18
   626
                    out.append("new ").append(ci.getClassName().getInternalName().replace('/','_'));
jaroslav@10
   627
                    out.append(");");
jaroslav@18
   628
                    addReference(ci.getClassName().getInternalName());
jaroslav@8
   629
                    i += 2;
jaroslav@8
   630
                    break;
jaroslav@8
   631
                }
jaroslav@21
   632
                case bc_newarray: {
jaroslav@21
   633
                    int type = byteCodes[i++];
jaroslav@21
   634
                    out.append("stack.push(new Array(stack.pop()));");
jaroslav@21
   635
                    break;
jaroslav@21
   636
                }
jaroslav@21
   637
                case bc_anewarray: {
jaroslav@21
   638
                    i += 2; // skip type of array
jaroslav@21
   639
                    out.append("stack.push(new Array(stack.pop()));");
jaroslav@21
   640
                    break;
jaroslav@21
   641
                }
jaroslav@21
   642
                case bc_arraylength:
jaroslav@21
   643
                    out.append("stack.push(stack.pop().length);");
jaroslav@21
   644
                    break;
jaroslav@21
   645
                case bc_iastore:
jaroslav@21
   646
                case bc_lastore:
jaroslav@21
   647
                case bc_fastore:
jaroslav@21
   648
                case bc_dastore:
jaroslav@21
   649
                case bc_aastore:
jaroslav@21
   650
                case bc_bastore:
jaroslav@21
   651
                case bc_castore:
jaroslav@21
   652
                case bc_sastore: {
jaroslav@21
   653
                    out.append("{ var value = stack.pop(); var indx = stack.pop(); stack.pop()[indx] = value; }");
jaroslav@21
   654
                    break;
jaroslav@21
   655
                }
jaroslav@21
   656
                case bc_iaload:
jaroslav@21
   657
                case bc_laload:
jaroslav@21
   658
                case bc_faload:
jaroslav@21
   659
                case bc_daload:
jaroslav@21
   660
                case bc_aaload:
jaroslav@21
   661
                case bc_baload:
jaroslav@21
   662
                case bc_caload:
jaroslav@21
   663
                case bc_saload: {
jaroslav@21
   664
                    out.append("{ var indx = stack.pop(); stack.push(stack.pop()[indx]); }");
jaroslav@21
   665
                    break;
jaroslav@21
   666
                }
jaroslav@93
   667
                case bc_pop2:
jaroslav@93
   668
                    out.append("stack.pop();");
jaroslav@93
   669
                case bc_pop:
jaroslav@93
   670
                    out.append("stack.pop();");
jaroslav@93
   671
                    break;
jaroslav@8
   672
                case bc_dup:
jaroslav@8
   673
                    out.append("stack.push(stack[stack.length - 1]);");
jaroslav@8
   674
                    break;
jaroslav@8
   675
                case bc_bipush:
jaroslav@8
   676
                    out.append("stack.push(" + byteCodes[++i] + ");");
jaroslav@8
   677
                    break;
jaroslav@31
   678
                case bc_sipush:
jaroslav@31
   679
                    out.append("stack.push(" + readIntArg(byteCodes, i) + ");");
jaroslav@31
   680
                    i += 2;
jaroslav@31
   681
                    break;
jaroslav@8
   682
                case bc_getfield: {
jaroslav@8
   683
                    int indx = readIntArg(byteCodes, i);
jaroslav@8
   684
                    CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
jaroslav@21
   685
                    out.append("stack.push(stack.pop().").append(fi.getFieldName()).append(");");
jaroslav@8
   686
                    i += 2;
jaroslav@8
   687
                    break;
jaroslav@8
   688
                }
jaroslav@9
   689
                case bc_getstatic: {
jaroslav@9
   690
                    int indx = readIntArg(byteCodes, i);
jaroslav@9
   691
                    CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
jaroslav@18
   692
                    final String in = fi.getClassName().getInternalName();
jaroslav@18
   693
                    out.append("stack.push(").append(in.replace('/', '_'));
jaroslav@9
   694
                    out.append('_').append(fi.getFieldName()).append(");");
jaroslav@9
   695
                    i += 2;
jaroslav@18
   696
                    addReference(in);
jaroslav@9
   697
                    break;
jaroslav@9
   698
                }
jaroslav@9
   699
                case bc_putstatic: {
jaroslav@9
   700
                    int indx = readIntArg(byteCodes, i);
jaroslav@9
   701
                    CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
jaroslav@18
   702
                    final String in = fi.getClassName().getInternalName();
jaroslav@18
   703
                    out.append(in.replace('/', '_'));
jaroslav@9
   704
                    out.append('_').append(fi.getFieldName()).append(" = stack.pop();");
jaroslav@9
   705
                    i += 2;
jaroslav@18
   706
                    addReference(in);
jaroslav@9
   707
                    break;
jaroslav@9
   708
                }
jaroslav@10
   709
                case bc_putfield: {
jaroslav@10
   710
                    int indx = readIntArg(byteCodes, i);
jaroslav@10
   711
                    CPFieldInfo fi = (CPFieldInfo) jc.getConstantPool().get(indx);
jaroslav@10
   712
                    out.append("{ var v = stack.pop(); stack.pop().")
jaroslav@10
   713
                       .append(fi.getFieldName()).append(" = v; }");
jaroslav@10
   714
                    i += 2;
jaroslav@10
   715
                    break;
jaroslav@10
   716
                }
jaroslav@30
   717
                case bc_checkcast: {
jaroslav@30
   718
                    int indx = readIntArg(byteCodes, i);
jaroslav@30
   719
                    CPClassInfo ci = jc.getConstantPool().getClass(indx);
jaroslav@42
   720
                    final String type = ci.getClassName().getType();
jaroslav@42
   721
                    if (!type.startsWith("[")) {
jaroslav@42
   722
                        // no way to check arrays right now
jaroslav@42
   723
                        out.append("if(stack[stack.length - 1].$instOf_")
jaroslav@42
   724
                           .append(type.replace('/', '_'))
jaroslav@42
   725
                           .append(" != 1) throw {};"); // XXX proper exception
jaroslav@42
   726
                    }
jaroslav@30
   727
                    i += 2;
jaroslav@30
   728
                    break;
jaroslav@30
   729
                }
jaroslav@17
   730
                case bc_instanceof: {
jaroslav@17
   731
                    int indx = readIntArg(byteCodes, i);
jaroslav@17
   732
                    CPClassInfo ci = jc.getConstantPool().getClass(indx);
jaroslav@17
   733
                    out.append("stack.push(stack.pop().$instOf_")
jaroslav@18
   734
                       .append(ci.getClassName().getInternalName().replace('/', '_'))
jaroslav@17
   735
                       .append(" ? 1 : 0);");
jaroslav@17
   736
                    i += 2;
jaroslav@30
   737
                    break;
jaroslav@17
   738
                }
jaroslav@104
   739
                case bc_athrow: {
jaroslav@104
   740
                    out.append("{ var t = stack.pop(); stack = new Array(1); stack[0] = t; throw t; }");
jaroslav@104
   741
                    break;
jaroslav@104
   742
                }
jaroslav@104
   743
                default: {
jaroslav@104
   744
                    out.append("throw 'unknown bytecode " + c + "';");
jaroslav@104
   745
                }
jaroslav@8
   746
                    
jaroslav@0
   747
            }
jaroslav@39
   748
            out.append(" //");
jaroslav@0
   749
            for (int j = prev; j <= i; j++) {
jaroslav@0
   750
                out.append(" ");
jaroslav@0
   751
                final int cc = (byteCodes[j] + 256) % 256;
jaroslav@0
   752
                out.append(Integer.toString(cc));
jaroslav@0
   753
            }
jaroslav@39
   754
            out.append("\n");
jaroslav@0
   755
        }
jaroslav@10
   756
        out.append("  }\n");
jaroslav@4
   757
    }
jaroslav@4
   758
jaroslav@4
   759
    private int generateIf(byte[] byteCodes, int i, final String test) throws IOException {
jaroslav@4
   760
        int indx = i + readIntArg(byteCodes, i);
jaroslav@4
   761
        out.append("if (stack.pop() ").append(test).append(" stack.pop()) { gt = " + indx);
jaroslav@4
   762
        out.append("; continue; }");
jaroslav@4
   763
        return i + 2;
jaroslav@4
   764
    }
jaroslav@4
   765
jaroslav@4
   766
    private int readIntArg(byte[] byteCodes, int offsetInstruction) {
jaroslav@5
   767
        final int indxHi = byteCodes[offsetInstruction + 1] << 8;
jaroslav@5
   768
        final int indxLo = byteCodes[offsetInstruction + 2];
jaroslav@5
   769
        return (indxHi & 0xffffff00) | (indxLo & 0xff);
jaroslav@4
   770
    }
jaroslav@115
   771
    private int readInt4(byte[] byteCodes, int offsetInstruction) {
jaroslav@115
   772
        final int d = byteCodes[offsetInstruction + 0] << 24;
jaroslav@115
   773
        final int c = byteCodes[offsetInstruction + 1] << 16;
jaroslav@115
   774
        final int b = byteCodes[offsetInstruction + 2] << 8;
jaroslav@115
   775
        final int a = byteCodes[offsetInstruction + 3];
jaroslav@115
   776
        return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
jaroslav@115
   777
    }
jaroslav@4
   778
    
jaroslav@4
   779
    private static int countArgs(String descriptor, boolean[] hasReturnType, StringBuilder sig) {
jaroslav@4
   780
        int cnt = 0;
jaroslav@4
   781
        int i = 0;
jaroslav@4
   782
        Boolean count = null;
jaroslav@32
   783
        boolean array = false;
jaroslav@10
   784
        int firstPos = sig.length();
jaroslav@4
   785
        while (i < descriptor.length()) {
jaroslav@4
   786
            char ch = descriptor.charAt(i++);
jaroslav@4
   787
            switch (ch) {
jaroslav@4
   788
                case '(':
jaroslav@4
   789
                    count = true;
jaroslav@4
   790
                    continue;
jaroslav@4
   791
                case ')':
jaroslav@4
   792
                    count = false;
jaroslav@4
   793
                    continue;
jaroslav@32
   794
                case 'A':
jaroslav@32
   795
                    array = true;
jaroslav@32
   796
                    break;
jaroslav@4
   797
                case 'B': 
jaroslav@4
   798
                case 'C': 
jaroslav@4
   799
                case 'D': 
jaroslav@4
   800
                case 'F': 
jaroslav@4
   801
                case 'I': 
jaroslav@4
   802
                case 'J': 
jaroslav@4
   803
                case 'S': 
jaroslav@4
   804
                case 'Z': 
jaroslav@4
   805
                    if (count) {
jaroslav@4
   806
                        cnt++;
jaroslav@32
   807
                        if (array) {
jaroslav@32
   808
                            sig.append('A');
jaroslav@32
   809
                        }
jaroslav@4
   810
                        sig.append(ch);
jaroslav@4
   811
                    } else {
jaroslav@4
   812
                        hasReturnType[0] = true;
jaroslav@10
   813
                        sig.insert(firstPos, ch);
jaroslav@32
   814
                        if (array) {
jaroslav@32
   815
                            sig.insert(firstPos, 'A');
jaroslav@32
   816
                        }
jaroslav@4
   817
                    }
jaroslav@93
   818
                    array = false;
jaroslav@4
   819
                    continue;
jaroslav@4
   820
                case 'V': 
jaroslav@4
   821
                    assert !count;
jaroslav@4
   822
                    hasReturnType[0] = false;
jaroslav@10
   823
                    sig.insert(firstPos, 'V');
jaroslav@4
   824
                    continue;
jaroslav@4
   825
                case 'L':
jaroslav@16
   826
                    int next = descriptor.indexOf(';', i);
jaroslav@4
   827
                    if (count) {
jaroslav@4
   828
                        cnt++;
jaroslav@32
   829
                        if (array) {
jaroslav@32
   830
                            sig.append('A');
jaroslav@32
   831
                        }
jaroslav@16
   832
                        sig.append(ch);
jaroslav@16
   833
                        sig.append(descriptor.substring(i, next).replace('/', '_'));
jaroslav@4
   834
                    } else {
jaroslav@16
   835
                        sig.insert(firstPos, descriptor.substring(i, next).replace('/', '_'));
jaroslav@16
   836
                        sig.insert(firstPos, ch);
jaroslav@32
   837
                        if (array) {
jaroslav@33
   838
                            sig.insert(firstPos, 'A');
jaroslav@32
   839
                        }
jaroslav@4
   840
                        hasReturnType[0] = true;
jaroslav@4
   841
                    }
jaroslav@16
   842
                    i = next + 1;
jaroslav@4
   843
                    continue;
jaroslav@4
   844
                case '[':
jaroslav@4
   845
                    //arrays++;
jaroslav@4
   846
                    continue;
jaroslav@4
   847
                default:
jaroslav@4
   848
                    break; // invalid character
jaroslav@4
   849
            }
jaroslav@4
   850
        }
jaroslav@4
   851
        return cnt;
jaroslav@0
   852
    }
jaroslav@9
   853
jaroslav@9
   854
    private void generateStaticField(Variable v) throws IOException {
jaroslav@9
   855
        out.append("\nvar ")
jaroslav@18
   856
           .append(jc.getName().getInternalName().replace('/', '_'))
jaroslav@9
   857
           .append('_').append(v.getName()).append(" = 0;");
jaroslav@9
   858
    }
jaroslav@10
   859
jaroslav@10
   860
    private String findMethodName(Method m) {
jaroslav@42
   861
        StringBuilder name = new StringBuilder();
jaroslav@42
   862
        String descr = m.getDescriptor();
jaroslav@10
   863
        if ("<init>".equals(m.getName())) { // NOI18N
jaroslav@42
   864
            name.append("cons"); // NOI18N
jaroslav@19
   865
        } else if ("<clinit>".equals(m.getName())) { // NOI18N
jaroslav@42
   866
            name.append("class"); // NOI18N
jaroslav@10
   867
        } else {
jaroslav@42
   868
            name.append(m.getName());
jaroslav@10
   869
        } 
jaroslav@42
   870
        
jaroslav@42
   871
        boolean hasReturn[] = { false };
jaroslav@42
   872
        countArgs(findDescriptor(m.getDescriptor()), hasReturn, name);
jaroslav@42
   873
        return name.toString();
jaroslav@10
   874
    }
jaroslav@10
   875
jaroslav@10
   876
    private String findMethodName(CPMethodInfo mi, int[] cnt, boolean[] hasReturn) {
jaroslav@10
   877
        StringBuilder name = new StringBuilder();
jaroslav@42
   878
        String descr = mi.getDescriptor();
jaroslav@10
   879
        if ("<init>".equals(mi.getName())) { // NOI18N
jaroslav@10
   880
            name.append("cons"); // NOI18N
jaroslav@10
   881
        } else {
jaroslav@10
   882
            name.append(mi.getName());
jaroslav@10
   883
        }
jaroslav@32
   884
        cnt[0] = countArgs(findDescriptor(mi.getDescriptor()), hasReturn, name);
jaroslav@10
   885
        return name.toString();
jaroslav@10
   886
    }
jaroslav@10
   887
jaroslav@10
   888
    private int invokeStaticMethod(byte[] byteCodes, int i, boolean isStatic)
jaroslav@10
   889
    throws IOException {
jaroslav@10
   890
        int methodIndex = readIntArg(byteCodes, i);
jaroslav@10
   891
        CPMethodInfo mi = (CPMethodInfo) jc.getConstantPool().get(methodIndex);
jaroslav@10
   892
        boolean[] hasReturn = { false };
jaroslav@10
   893
        int[] cnt = { 0 };
jaroslav@10
   894
        String mn = findMethodName(mi, cnt, hasReturn);
jaroslav@11
   895
        out.append("{ ");
jaroslav@11
   896
        for (int j = cnt[0] - 1; j >= 0; j--) {
jaroslav@11
   897
            out.append("var v" + j).append(" = stack.pop(); ");
jaroslav@11
   898
        }
jaroslav@11
   899
        
jaroslav@10
   900
        if (hasReturn[0]) {
jaroslav@10
   901
            out.append("stack.push(");
jaroslav@10
   902
        }
jaroslav@18
   903
        final String in = mi.getClassName().getInternalName();
jaroslav@18
   904
        out.append(in.replace('/', '_'));
jaroslav@102
   905
        if (isStatic) {
jaroslav@102
   906
            out.append(".prototype.");
jaroslav@102
   907
        } else {
jaroslav@102
   908
            out.append('_');
jaroslav@102
   909
        }
jaroslav@10
   910
        out.append(mn);
jaroslav@10
   911
        out.append('(');
jaroslav@10
   912
        String sep = "";
jaroslav@10
   913
        if (!isStatic) {
jaroslav@10
   914
            out.append("stack.pop()");
jaroslav@10
   915
            sep = ", ";
jaroslav@10
   916
        }
jaroslav@10
   917
        for (int j = 0; j < cnt[0]; j++) {
jaroslav@10
   918
            out.append(sep);
jaroslav@11
   919
            out.append("v" + j);
jaroslav@10
   920
            sep = ", ";
jaroslav@10
   921
        }
jaroslav@10
   922
        out.append(")");
jaroslav@10
   923
        if (hasReturn[0]) {
jaroslav@10
   924
            out.append(")");
jaroslav@10
   925
        }
jaroslav@11
   926
        out.append("; }");
jaroslav@10
   927
        i += 2;
jaroslav@18
   928
        addReference(in);
jaroslav@10
   929
        return i;
jaroslav@10
   930
    }
jaroslav@12
   931
    private int invokeVirtualMethod(byte[] byteCodes, int i)
jaroslav@12
   932
    throws IOException {
jaroslav@12
   933
        int methodIndex = readIntArg(byteCodes, i);
jaroslav@12
   934
        CPMethodInfo mi = (CPMethodInfo) jc.getConstantPool().get(methodIndex);
jaroslav@12
   935
        boolean[] hasReturn = { false };
jaroslav@12
   936
        int[] cnt = { 0 };
jaroslav@12
   937
        String mn = findMethodName(mi, cnt, hasReturn);
jaroslav@12
   938
        out.append("{ ");
jaroslav@12
   939
        for (int j = cnt[0] - 1; j >= 0; j--) {
jaroslav@12
   940
            out.append("var v" + j).append(" = stack.pop(); ");
jaroslav@12
   941
        }
jaroslav@12
   942
        out.append("var self = stack.pop(); ");
jaroslav@12
   943
        if (hasReturn[0]) {
jaroslav@12
   944
            out.append("stack.push(");
jaroslav@12
   945
        }
jaroslav@12
   946
        out.append("self.");
jaroslav@12
   947
        out.append(mn);
jaroslav@12
   948
        out.append('(');
jaroslav@12
   949
        out.append("self");
jaroslav@12
   950
        for (int j = 0; j < cnt[0]; j++) {
jaroslav@12
   951
            out.append(", ");
jaroslav@12
   952
            out.append("v" + j);
jaroslav@12
   953
        }
jaroslav@12
   954
        out.append(")");
jaroslav@12
   955
        if (hasReturn[0]) {
jaroslav@12
   956
            out.append(")");
jaroslav@12
   957
        }
jaroslav@12
   958
        out.append("; }");
jaroslav@12
   959
        i += 2;
jaroslav@12
   960
        return i;
jaroslav@12
   961
    }
jaroslav@18
   962
    
jaroslav@103
   963
    private void addReference(String cn) throws IOException {
jaroslav@103
   964
        out.append(" /* needs ").append(cn).append(" */");
jaroslav@18
   965
        if (references != null) {
jaroslav@18
   966
            references.add(cn);
jaroslav@18
   967
        }
jaroslav@18
   968
    }
jaroslav@16
   969
jaroslav@33
   970
    private void outType(String d, StringBuilder out) {
jaroslav@33
   971
        int arr = 0;
jaroslav@33
   972
        while (d.charAt(0) == '[') {
jaroslav@33
   973
            out.append('A');
jaroslav@33
   974
            d = d.substring(1);
jaroslav@33
   975
        }
jaroslav@16
   976
        if (d.charAt(0) == 'L') {
jaroslav@16
   977
            assert d.charAt(d.length() - 1) == ';';
jaroslav@16
   978
            out.append(d.replace('/', '_').substring(0, d.length() - 1));
jaroslav@16
   979
        } else {
jaroslav@16
   980
            out.append(d);
jaroslav@16
   981
        }
jaroslav@16
   982
    }
jaroslav@21
   983
jaroslav@21
   984
    private String encodeConstant(CPEntry entry) {
jaroslav@21
   985
        final String v;
jaroslav@93
   986
        if (entry instanceof CPClassInfo) {
jaroslav@93
   987
            v = "new java_lang_Class";
jaroslav@93
   988
        } else if (entry instanceof CPStringInfo) {
jaroslav@21
   989
            v = "\"" + entry.getValue().toString().replace("\"", "\\\"") + "\"";
jaroslav@21
   990
        } else {
jaroslav@21
   991
            v = entry.getValue().toString();
jaroslav@21
   992
        }
jaroslav@21
   993
        return v;
jaroslav@21
   994
    }
jaroslav@32
   995
jaroslav@32
   996
    private String findDescriptor(String d) {
jaroslav@32
   997
        return d.replace('[', 'A');
jaroslav@32
   998
    }
jaroslav@94
   999
jaroslav@94
  1000
    private boolean javaScriptBody(Method m, boolean isStatic) throws IOException {
jaroslav@94
  1001
        final ClassName extraAnn = ClassName.getClassName(JavaScriptBody.class.getName().replace('.', '/'));
jaroslav@94
  1002
        Annotation a = m.getAnnotation(extraAnn);
jaroslav@94
  1003
        if (a != null) {
jaroslav@94
  1004
            final ElementValue annVal = a.getComponent("body").getValue();
jaroslav@94
  1005
            String body = ((PrimitiveElementValue) annVal).getValue().getValue().toString();
jaroslav@94
  1006
            
jaroslav@94
  1007
            final ArrayElementValue arrVal = (ArrayElementValue) a.getComponent("args").getValue();
jaroslav@94
  1008
            final int len = arrVal.getValues().length;
jaroslav@94
  1009
            String[] names = new String[len];
jaroslav@94
  1010
            for (int i = 0; i < len; i++) {
jaroslav@94
  1011
                names[i] = ((PrimitiveElementValue) arrVal.getValues()[i]).getValue().getValue().toString();
jaroslav@94
  1012
            }
jaroslav@94
  1013
            out.append("\nfunction ").append(
jaroslav@94
  1014
                jc.getName().getInternalName().replace('/', '_')).append('_').append(findMethodName(m));
jaroslav@94
  1015
            out.append("(");
jaroslav@94
  1016
            String space;
jaroslav@94
  1017
            int index;
jaroslav@94
  1018
            if (!isStatic) {                
jaroslav@94
  1019
                out.append(names[0]);
jaroslav@94
  1020
                space = ",";
jaroslav@94
  1021
                index = 1;
jaroslav@94
  1022
            } else {
jaroslav@94
  1023
                space = "";
jaroslav@94
  1024
                index = 0;
jaroslav@94
  1025
            }
jaroslav@94
  1026
            List<Parameter> args = m.getParameters();
jaroslav@94
  1027
            for (int i = 0; i < args.size(); i++) {
jaroslav@94
  1028
                out.append(space);
jaroslav@94
  1029
                out.append(names[index]);
jaroslav@94
  1030
                final String desc = findDescriptor(args.get(i).getDescriptor());
jaroslav@94
  1031
                index++;
jaroslav@99
  1032
                space = ",";
jaroslav@94
  1033
            }
jaroslav@94
  1034
            out.append(") {").append("\n");
jaroslav@94
  1035
            out.append(body);
jaroslav@94
  1036
            out.append("\n}\n");
jaroslav@94
  1037
            return true;
jaroslav@94
  1038
        }
jaroslav@94
  1039
        return false;
jaroslav@94
  1040
    }
jaroslav@0
  1041
}