summaryrefslogtreecommitdiffstats
path: root/src/main/javassist/compiler/MemberResolver.java
blob: 6e9c33c1434d21cdc0adfe98d4f0ba73b1bbd62a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
/*
 * Javassist, a Java-bytecode translator toolkit.
 * Copyright (C) 1999-2003 Shigeru Chiba. All Rights Reserved.
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License.  Alternatively, the contents of this file may be used under
 * the terms of the GNU Lesser General Public License Version 2.1 or later.
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 */

package javassist.compiler;

import java.util.List;
import javassist.*;
import javassist.bytecode.*;
import javassist.compiler.ast.*;

/* Code generator methods depending on javassist.* classes.
 */
public class MemberResolver implements TokenId {
    private ClassPool classPool;

    public MemberResolver(ClassPool cp) {
        classPool = cp;
    }

    public ClassPool getClassPool() { return classPool; }

    private static void fatal() throws CompileError {
        throw new CompileError("fatal");
    }

    public static class Method {
        public CtClass declaring;
        public MethodInfo info;

        public Method(CtClass c, MethodInfo i) {
            declaring = c;
            info = i;
        }

        /**
         * Returns true if the invoked method is static.
         */
        public boolean isStatic() {
            int acc = info.getAccessFlags();
            return (acc & AccessFlag.STATIC) != 0;
        }
    }

    public Method lookupMethod(CtClass clazz, MethodInfo current,
                               String methodName,
                               int[] argTypes, int[] argDims,
                               String[] argClassNames, boolean onlyExact)
        throws CompileError
    {
        Method maybe = null;

        // to enable the creation of a recursively called method
        if (current != null)
            if (current.getName().equals(methodName)) {
                int res = compareSignature(current.getDescriptor(),
                                           argTypes, argDims, argClassNames);
                Method r = new Method(clazz, current);
                if (res == YES)
                    return r;
                else if (res == MAYBE && maybe == null)
                    maybe = r;
            }

        List list = clazz.getClassFile2().getMethods();
        int n = list.size();
        for (int i = 0; i < n; ++i) {
            MethodInfo minfo = (MethodInfo)list.get(i);
            if (minfo.getName().equals(methodName)) {
                int res = compareSignature(minfo.getDescriptor(),
                                           argTypes, argDims, argClassNames);
                Method r = new Method(clazz, minfo);
                if (res == YES)
                    return r;
                else if (res == MAYBE && maybe == null)
                    maybe = r;
            }
        }

        try {
            CtClass pclazz = clazz.getSuperclass();
            if (pclazz != null) {
                Method r = lookupMethod(pclazz, null, methodName, argTypes,
                                        argDims, argClassNames,
                                        (onlyExact || maybe != null));
                if (r != null)
                    return r;
            }
        }
        catch (NotFoundException e) {}

        int mod = clazz.getModifiers();
        if (Modifier.isAbstract(mod) || Modifier.isInterface(mod))
            try {
                CtClass[] ifs = clazz.getInterfaces();
                int size = ifs.length;
                for (int i = 0; i < size; ++i) {
                    Method r = lookupMethod(ifs[i], null, methodName,
                                            argTypes, argDims, argClassNames,
                                            (onlyExact || maybe != null));
                    if (r != null)
                        return r;
                }
            }
            catch (NotFoundException e) {}

        if (onlyExact)
            return null;
        else
            return maybe;
    }

    private static final int YES = 2;
    private static final int MAYBE = 1;
    private static final int NO = 0;

    /*
     * Returns YES if actual parameter types matches the given signature.
     *
     * argTypes, argDims, and argClassNames represent actual parameters.
     *
     * This method does not correctly implement the Java method dispatch
     * algorithm.
     */
    private int compareSignature(String desc, int[] argTypes,
                                 int[] argDims, String[] argClassNames)
        throws CompileError
    {
        int result = YES;
        int i = 1;
        int nArgs = argTypes.length;
        if (nArgs != Descriptor.numOfParameters(desc))
            return NO;

        int len = desc.length();
        for (int n = 0; i < len; ++n) {
            char c = desc.charAt(i++);
            if (c == ')')
                return (n == nArgs ? result : NO);
            else if (n >= nArgs)
                return NO;

            int dim = 0;
            while (c == '[') {
                ++dim;
                c = desc.charAt(i++);
            }

            if (argTypes[n] == NULL) {
                if (dim == 0 && c != 'L')
                    return NO;
            }
            else if (argDims[n] != dim) {
                if (!(dim == 0 && c == 'L'
                      && desc.startsWith("java/lang/Object;", i)))
                    return NO;

                // if the thread reaches here, c must be 'L'.
                i = desc.indexOf(';', i) + 1;
                result = MAYBE;
                if (i <= 0)
                    return NO;  // invalid descriptor?
            }
            else if (c == 'L') {        // not compare
                int j = desc.indexOf(';', i);
                if (j < 0 || argTypes[n] != CLASS)
                    return NO;

                String cname = desc.substring(i, j);
                if (!cname.equals(argClassNames[n])) {
                    CtClass clazz = lookupClassByJvmName(argClassNames[n]);
                    try {
                        if (clazz.subtypeOf(lookupClassByJvmName(cname)))
                            result = MAYBE;
                        else
                            return NO;
                    }
                    catch (NotFoundException e) {
                        result = MAYBE; // should be NO?
                    }
                }

                i = j + 1;
            }
            else {
                int t = descToType(c);
                int at = argTypes[n];
                if (t != at)
                    if (t == INT
                        && (at == SHORT || at == BYTE || at == CHAR))
                        result = MAYBE;
                    else
                        return NO;
            }
        }

        return NO;
    }

    /**
     * Only used by fieldAccess() in MemberCodeGen.
     *
     * @param jvmClassName  a JVM class name.  e.g. java/lang/String
     */
    public CtField lookupFieldByJvmName2(String jvmClassName, Symbol fieldSym,
                                         ASTree expr) throws NoFieldException
    {
        String field = fieldSym.get();
        CtClass cc = null;
        try {
            cc = lookupClass(jvmToJavaName(jvmClassName), true);
        }
        catch (CompileError e) {
            // EXPR might be part of a qualified class name.
            throw new NoFieldException(jvmClassName + "/" + field, expr);
        }

        try {
            return cc.getField(field);
        }
        catch (NotFoundException e) {
            // maybe an inner class.
            jvmClassName = javaToJvmName(cc.getName());
            throw new NoFieldException(jvmClassName + "$" + field, expr);
        }
    }

    /**
     * @param jvmClassName  a JVM class name.  e.g. java/lang/String
     */
    public CtField lookupFieldByJvmName(String jvmClassName, Symbol fieldName)
        throws CompileError
    {
        return lookupField(jvmToJavaName(jvmClassName), fieldName);
    }

    /**
     * @param name      a qualified class name. e.g. java.lang.String
     */
    public CtField lookupField(String className, Symbol fieldName)
        throws CompileError
    {
        CtClass cc = lookupClass(className, false);
        try {
            return cc.getField(fieldName.get());
        }
        catch (NotFoundException e) {}
        throw new CompileError("no such field: " + fieldName.get());
    }

    public CtClass lookupClassByName(ASTList name) throws CompileError {
        return lookupClass(Declarator.astToClassName(name, '.'), false);
    }

    public CtClass lookupClassByJvmName(String jvmName) throws CompileError {
        return lookupClass(jvmToJavaName(jvmName), false);
    }

    public CtClass lookupClass(Declarator decl) throws CompileError {
        return lookupClass(decl.getType(), decl.getArrayDim(),
                           decl.getClassName());
    }

    /**
     * @parma classname         jvm class name.
     */
    public CtClass lookupClass(int type, int dim, String classname)
        throws CompileError
    {
        String cname = "";
        CtClass clazz;
        switch (type) {
        case CLASS :
            clazz = lookupClassByJvmName(classname);
            if (dim > 0)
                cname = clazz.getName();
            else
                return clazz;

            break;
        case BOOLEAN :
            cname = "boolean";
            break;
        case CHAR :
            cname = "char";
            break;
        case BYTE :
            cname = "byte";
            break;
        case SHORT :
            cname = "short";
            break;
        case INT :
            cname = "int";
            break;
        case LONG :
            cname = "long";
            break;
        case FLOAT :
            cname = "float";
            break;
        case DOUBLE :
            cname = "double";
            break;
        case VOID :
            cname = "void";
            break;
        default :
            fatal();
        }

        while (dim-- > 0)
            cname += "[]";

        return lookupClass(cname, false);
    }

    /**
     * @param name      a qualified class name. e.g. java.lang.String
     */
    public CtClass lookupClass(String name, boolean notCheckInner)
        throws CompileError
    {
        try {
            return lookupClass0(name, notCheckInner);
        }
        catch (NotFoundException e) {}

        try {
            if (name.indexOf('.') < 0)
                return classPool.get("java.lang." + name);
        }
        catch (NotFoundException e) {}

        throw new CompileError("no such class: " + name);
    }

    private CtClass lookupClass0(String classname, boolean notCheckInner)
        throws NotFoundException
    {
        CtClass cc = null;
        do {
            try {
                cc = classPool.get(classname);
            }
            catch (NotFoundException e) {
                int i = classname.lastIndexOf('.');
                if (notCheckInner || i < 0)
                    throw e;
                else {
                    StringBuffer sbuf = new StringBuffer(classname);
                    sbuf.setCharAt(i, '$');
                    classname = sbuf.toString();
                }
            }
        } while (cc == null);
        return cc;
    }

    /* Converts a class name into a JVM-internal representation.
     *
     * It may also expand a simple class name to java.lang.*.
     * For example, this converts Object into java/lang/Object.
     */
    public String resolveClassName(ASTList name) throws CompileError {
        if (name == null)
            return null;
        else
            return javaToJvmName(lookupClassByName(name).getName());
    }

    /* Expands a simple class name to java.lang.*.
     * For example, this converts Object into java/lang/Object.
     */
    public String resolveJvmClassName(String jvmName) throws CompileError {
        if (jvmName == null)
            return null;
        else
            return javaToJvmName(lookupClassByJvmName(jvmName).getName());
    }

    public static CtClass getSuperclass(CtClass c) throws CompileError {
        try {
            return c.getSuperclass();
        }
        catch (NotFoundException e) {
            throw new CompileError("cannot find the super class of "
                                   + c.getName());
        }
    }

    public static String javaToJvmName(String classname) {
        return classname.replace('.', '/');
    }

    public static String jvmToJavaName(String classname) {
        return classname.replace('/', '.');
    }

    public static int jvmTypeNameToExprType(char type) {
        switch(type) {
        case 'Z' :
            return BOOLEAN;
        case 'B' :
            return BYTE;
        case 'C' :
            return CHAR;
        case 'S' :
            return SHORT;
        case 'I' :
            return INT;
        case 'J' :
            return LONG;
        case 'F' :
            return FLOAT;
        case 'D' :
            return DOUBLE;
        case 'V' :
            return VOID;
        default :
            return CLASS;
        }
    }

    public static int descToType(char c) throws CompileError {
        switch (c) {
        case 'Z' :
            return BOOLEAN;
        case 'C' :
            return CHAR;
        case 'B' :
            return  BYTE;
        case 'S' :
            return SHORT;
        case 'I' :
            return INT;
        case 'J' :
            return LONG;
        case 'F' :
            return FLOAT;
        case 'D' :
            return DOUBLE;
        case 'V' :
            return VOID;
        case 'L' :
        case '[' :
            return CLASS;
        default :
            fatal();
            return VOID;
        }
    }

    public static int getModifiers(ASTList mods) {
        int m = 0;
        while (mods != null) {
            Keyword k = (Keyword)mods.head();
            mods = mods.tail();
            switch (k.get()) {
            case STATIC :
                m |= Modifier.STATIC;
                break;
            case FINAL :
                m |= Modifier.FINAL;
                break;
            case SYNCHRONIZED :
                m |= Modifier.SYNCHRONIZED;
                break;
            case ABSTRACT :
                m |= Modifier.ABSTRACT;
                break;
            case PUBLIC :
                m |= Modifier.PUBLIC;
                break;
            case PROTECTED :
                m |= Modifier.PROTECTED;
                break;
            case PRIVATE :
                m |= Modifier.PRIVATE;
                break;
            case VOLATILE :
                m |= Modifier.VOLATILE;
                break;
            case TRANSIENT :
                m |= Modifier.TRANSIENT;
                break;
            case STRICT :
                m |= Modifier.STRICT;
                break;
            }
        }

        return m;
    }
}