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