MemberName.java revision 13025:7e2dc25eef6b
1/*
2 * Copyright (c) 2008, 2015, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.  Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 */
25
26package java.lang.invoke;
27
28import sun.invoke.util.BytecodeDescriptor;
29import sun.invoke.util.VerifyAccess;
30
31import java.lang.reflect.Constructor;
32import java.lang.reflect.Field;
33import java.lang.reflect.Method;
34import java.lang.reflect.Member;
35import java.lang.reflect.Modifier;
36import java.util.ArrayList;
37import java.util.Arrays;
38import java.util.Collections;
39import java.util.Iterator;
40import java.util.List;
41import static java.lang.invoke.MethodHandleNatives.Constants.*;
42import static java.lang.invoke.MethodHandleStatics.*;
43import java.util.Objects;
44
45/**
46 * A {@code MemberName} is a compact symbolic datum which fully characterizes
47 * a method or field reference.
48 * A member name refers to a field, method, constructor, or member type.
49 * Every member name has a simple name (a string) and a type (either a Class or MethodType).
50 * A member name may also have a non-null declaring class, or it may be simply
51 * a naked name/type pair.
52 * A member name may also have non-zero modifier flags.
53 * Finally, a member name may be either resolved or unresolved.
54 * If it is resolved, the existence of the named
55 * <p>
56 * Whether resolved or not, a member name provides no access rights or
57 * invocation capability to its possessor.  It is merely a compact
58 * representation of all symbolic information necessary to link to
59 * and properly use the named member.
60 * <p>
61 * When resolved, a member name's internal implementation may include references to JVM metadata.
62 * This representation is stateless and only descriptive.
63 * It provides no private information and no capability to use the member.
64 * <p>
65 * By contrast, a {@linkplain java.lang.reflect.Method} contains fuller information
66 * about the internals of a method (except its bytecodes) and also
67 * allows invocation.  A MemberName is much lighter than a Method,
68 * since it contains about 7 fields to the 16 of Method (plus its sub-arrays),
69 * and those seven fields omit much of the information in Method.
70 * @author jrose
71 */
72/*non-public*/ final class MemberName implements Member, Cloneable {
73    private Class<?> clazz;       // class in which the method is defined
74    private String   name;        // may be null if not yet materialized
75    private Object   type;        // may be null if not yet materialized
76    private int      flags;       // modifier bits; see reflect.Modifier
77    //@Injected JVM_Method* vmtarget;
78    //@Injected int         vmindex;
79    private Object   resolution;  // if null, this guy is resolved
80
81    /** Return the declaring class of this member.
82     *  In the case of a bare name and type, the declaring class will be null.
83     */
84    public Class<?> getDeclaringClass() {
85        return clazz;
86    }
87
88    /** Utility method producing the class loader of the declaring class. */
89    public ClassLoader getClassLoader() {
90        return clazz.getClassLoader();
91    }
92
93    /** Return the simple name of this member.
94     *  For a type, it is the same as {@link Class#getSimpleName}.
95     *  For a method or field, it is the simple name of the member.
96     *  For a constructor, it is always {@code "<init>"}.
97     */
98    public String getName() {
99        if (name == null) {
100            expandFromVM();
101            if (name == null) {
102                return null;
103            }
104        }
105        return name;
106    }
107
108    public MethodType getMethodOrFieldType() {
109        if (isInvocable())
110            return getMethodType();
111        if (isGetter())
112            return MethodType.methodType(getFieldType());
113        if (isSetter())
114            return MethodType.methodType(void.class, getFieldType());
115        throw new InternalError("not a method or field: "+this);
116    }
117
118    /** Return the declared type of this member, which
119     *  must be a method or constructor.
120     */
121    public MethodType getMethodType() {
122        if (type == null) {
123            expandFromVM();
124            if (type == null) {
125                return null;
126            }
127        }
128        if (!isInvocable()) {
129            throw newIllegalArgumentException("not invocable, no method type");
130        }
131
132        {
133            // Get a snapshot of type which doesn't get changed by racing threads.
134            final Object type = this.type;
135            if (type instanceof MethodType) {
136                return (MethodType) type;
137            }
138        }
139
140        // type is not a MethodType yet.  Convert it thread-safely.
141        synchronized (this) {
142            if (type instanceof String) {
143                String sig = (String) type;
144                MethodType res = MethodType.fromDescriptor(sig, getClassLoader());
145                type = res;
146            } else if (type instanceof Object[]) {
147                Object[] typeInfo = (Object[]) type;
148                Class<?>[] ptypes = (Class<?>[]) typeInfo[1];
149                Class<?> rtype = (Class<?>) typeInfo[0];
150                MethodType res = MethodType.methodType(rtype, ptypes);
151                type = res;
152            }
153            // Make sure type is a MethodType for racing threads.
154            assert type instanceof MethodType : "bad method type " + type;
155        }
156        return (MethodType) type;
157    }
158
159    /** Return the actual type under which this method or constructor must be invoked.
160     *  For non-static methods or constructors, this is the type with a leading parameter,
161     *  a reference to declaring class.  For static methods, it is the same as the declared type.
162     */
163    public MethodType getInvocationType() {
164        MethodType itype = getMethodOrFieldType();
165        if (isConstructor() && getReferenceKind() == REF_newInvokeSpecial)
166            return itype.changeReturnType(clazz);
167        if (!isStatic())
168            return itype.insertParameterTypes(0, clazz);
169        return itype;
170    }
171
172    /** Utility method producing the parameter types of the method type. */
173    public Class<?>[] getParameterTypes() {
174        return getMethodType().parameterArray();
175    }
176
177    /** Utility method producing the return type of the method type. */
178    public Class<?> getReturnType() {
179        return getMethodType().returnType();
180    }
181
182    /** Return the declared type of this member, which
183     *  must be a field or type.
184     *  If it is a type member, that type itself is returned.
185     */
186    public Class<?> getFieldType() {
187        if (type == null) {
188            expandFromVM();
189            if (type == null) {
190                return null;
191            }
192        }
193        if (isInvocable()) {
194            throw newIllegalArgumentException("not a field or nested class, no simple type");
195        }
196
197        {
198            // Get a snapshot of type which doesn't get changed by racing threads.
199            final Object type = this.type;
200            if (type instanceof Class<?>) {
201                return (Class<?>) type;
202            }
203        }
204
205        // type is not a Class yet.  Convert it thread-safely.
206        synchronized (this) {
207            if (type instanceof String) {
208                String sig = (String) type;
209                MethodType mtype = MethodType.fromDescriptor("()"+sig, getClassLoader());
210                Class<?> res = mtype.returnType();
211                type = res;
212            }
213            // Make sure type is a Class for racing threads.
214            assert type instanceof Class<?> : "bad field type " + type;
215        }
216        return (Class<?>) type;
217    }
218
219    /** Utility method to produce either the method type or field type of this member. */
220    public Object getType() {
221        return (isInvocable() ? getMethodType() : getFieldType());
222    }
223
224    /** Utility method to produce the signature of this member,
225     *  used within the class file format to describe its type.
226     */
227    public String getSignature() {
228        if (type == null) {
229            expandFromVM();
230            if (type == null) {
231                return null;
232            }
233        }
234        if (isInvocable())
235            return BytecodeDescriptor.unparse(getMethodType());
236        else
237            return BytecodeDescriptor.unparse(getFieldType());
238    }
239
240    /** Return the modifier flags of this member.
241     *  @see java.lang.reflect.Modifier
242     */
243    public int getModifiers() {
244        return (flags & RECOGNIZED_MODIFIERS);
245    }
246
247    /** Return the reference kind of this member, or zero if none.
248     */
249    public byte getReferenceKind() {
250        return (byte) ((flags >>> MN_REFERENCE_KIND_SHIFT) & MN_REFERENCE_KIND_MASK);
251    }
252    private boolean referenceKindIsConsistent() {
253        byte refKind = getReferenceKind();
254        if (refKind == REF_NONE)  return isType();
255        if (isField()) {
256            assert(staticIsConsistent());
257            assert(MethodHandleNatives.refKindIsField(refKind));
258        } else if (isConstructor()) {
259            assert(refKind == REF_newInvokeSpecial || refKind == REF_invokeSpecial);
260        } else if (isMethod()) {
261            assert(staticIsConsistent());
262            assert(MethodHandleNatives.refKindIsMethod(refKind));
263            if (clazz.isInterface())
264                assert(refKind == REF_invokeInterface ||
265                       refKind == REF_invokeStatic    ||
266                       refKind == REF_invokeSpecial   ||
267                       refKind == REF_invokeVirtual && isObjectPublicMethod());
268        } else {
269            assert(false);
270        }
271        return true;
272    }
273    private boolean isObjectPublicMethod() {
274        if (clazz == Object.class)  return true;
275        MethodType mtype = getMethodType();
276        if (name.equals("toString") && mtype.returnType() == String.class && mtype.parameterCount() == 0)
277            return true;
278        if (name.equals("hashCode") && mtype.returnType() == int.class && mtype.parameterCount() == 0)
279            return true;
280        if (name.equals("equals") && mtype.returnType() == boolean.class && mtype.parameterCount() == 1 && mtype.parameterType(0) == Object.class)
281            return true;
282        return false;
283    }
284    /*non-public*/ boolean referenceKindIsConsistentWith(int originalRefKind) {
285        int refKind = getReferenceKind();
286        if (refKind == originalRefKind)  return true;
287        switch (originalRefKind) {
288        case REF_invokeInterface:
289            // Looking up an interface method, can get (e.g.) Object.hashCode
290            assert(refKind == REF_invokeVirtual ||
291                   refKind == REF_invokeSpecial) : this;
292            return true;
293        case REF_invokeVirtual:
294        case REF_newInvokeSpecial:
295            // Looked up a virtual, can get (e.g.) final String.hashCode.
296            assert(refKind == REF_invokeSpecial) : this;
297            return true;
298        }
299        assert(false) : this+" != "+MethodHandleNatives.refKindName((byte)originalRefKind);
300        return true;
301    }
302    private boolean staticIsConsistent() {
303        byte refKind = getReferenceKind();
304        return MethodHandleNatives.refKindIsStatic(refKind) == isStatic() || getModifiers() == 0;
305    }
306    private boolean vminfoIsConsistent() {
307        byte refKind = getReferenceKind();
308        assert(isResolved());  // else don't call
309        Object vminfo = MethodHandleNatives.getMemberVMInfo(this);
310        assert(vminfo instanceof Object[]);
311        long vmindex = (Long) ((Object[])vminfo)[0];
312        Object vmtarget = ((Object[])vminfo)[1];
313        if (MethodHandleNatives.refKindIsField(refKind)) {
314            assert(vmindex >= 0) : vmindex + ":" + this;
315            assert(vmtarget instanceof Class);
316        } else {
317            if (MethodHandleNatives.refKindDoesDispatch(refKind))
318                assert(vmindex >= 0) : vmindex + ":" + this;
319            else
320                assert(vmindex < 0) : vmindex;
321            assert(vmtarget instanceof MemberName) : vmtarget + " in " + this;
322        }
323        return true;
324    }
325
326    private MemberName changeReferenceKind(byte refKind, byte oldKind) {
327        assert(getReferenceKind() == oldKind);
328        assert(MethodHandleNatives.refKindIsValid(refKind));
329        flags += (((int)refKind - oldKind) << MN_REFERENCE_KIND_SHIFT);
330        return this;
331    }
332
333    private boolean testFlags(int mask, int value) {
334        return (flags & mask) == value;
335    }
336    private boolean testAllFlags(int mask) {
337        return testFlags(mask, mask);
338    }
339    private boolean testAnyFlags(int mask) {
340        return !testFlags(mask, 0);
341    }
342
343    /** Utility method to query if this member is a method handle invocation (invoke or invokeExact).
344     *  Also returns true for the non-public MH.invokeBasic.
345     */
346    public boolean isMethodHandleInvoke() {
347        final int bits = MH_INVOKE_MODS &~ Modifier.PUBLIC;
348        final int negs = Modifier.STATIC;
349        if (testFlags(bits | negs, bits) &&
350            clazz == MethodHandle.class) {
351            return isMethodHandleInvokeName(name);
352        }
353        return false;
354    }
355    public static boolean isMethodHandleInvokeName(String name) {
356        switch (name) {
357        case "invoke":
358        case "invokeExact":
359        case "invokeBasic":  // internal sig-poly method
360            return true;
361        default:
362            return false;
363        }
364    }
365    private static final int MH_INVOKE_MODS = Modifier.NATIVE | Modifier.FINAL | Modifier.PUBLIC;
366
367    /** Utility method to query the modifier flags of this member. */
368    public boolean isStatic() {
369        return Modifier.isStatic(flags);
370    }
371    /** Utility method to query the modifier flags of this member. */
372    public boolean isPublic() {
373        return Modifier.isPublic(flags);
374    }
375    /** Utility method to query the modifier flags of this member. */
376    public boolean isPrivate() {
377        return Modifier.isPrivate(flags);
378    }
379    /** Utility method to query the modifier flags of this member. */
380    public boolean isProtected() {
381        return Modifier.isProtected(flags);
382    }
383    /** Utility method to query the modifier flags of this member. */
384    public boolean isFinal() {
385        return Modifier.isFinal(flags);
386    }
387    /** Utility method to query whether this member or its defining class is final. */
388    public boolean canBeStaticallyBound() {
389        return Modifier.isFinal(flags | clazz.getModifiers());
390    }
391    /** Utility method to query the modifier flags of this member. */
392    public boolean isVolatile() {
393        return Modifier.isVolatile(flags);
394    }
395    /** Utility method to query the modifier flags of this member. */
396    public boolean isAbstract() {
397        return Modifier.isAbstract(flags);
398    }
399    /** Utility method to query the modifier flags of this member. */
400    public boolean isNative() {
401        return Modifier.isNative(flags);
402    }
403    // let the rest (native, volatile, transient, etc.) be tested via Modifier.isFoo
404
405    // unofficial modifier flags, used by HotSpot:
406    static final int BRIDGE    = 0x00000040;
407    static final int VARARGS   = 0x00000080;
408    static final int SYNTHETIC = 0x00001000;
409    static final int ANNOTATION= 0x00002000;
410    static final int ENUM      = 0x00004000;
411    /** Utility method to query the modifier flags of this member; returns false if the member is not a method. */
412    public boolean isBridge() {
413        return testAllFlags(IS_METHOD | BRIDGE);
414    }
415    /** Utility method to query the modifier flags of this member; returns false if the member is not a method. */
416    public boolean isVarargs() {
417        return testAllFlags(VARARGS) && isInvocable();
418    }
419    /** Utility method to query the modifier flags of this member; returns false if the member is not a method. */
420    public boolean isSynthetic() {
421        return testAllFlags(SYNTHETIC);
422    }
423
424    static final String CONSTRUCTOR_NAME = "<init>";  // the ever-popular
425
426    // modifiers exported by the JVM:
427    static final int RECOGNIZED_MODIFIERS = 0xFFFF;
428
429    // private flags, not part of RECOGNIZED_MODIFIERS:
430    static final int
431            IS_METHOD        = MN_IS_METHOD,        // method (not constructor)
432            IS_CONSTRUCTOR   = MN_IS_CONSTRUCTOR,   // constructor
433            IS_FIELD         = MN_IS_FIELD,         // field
434            IS_TYPE          = MN_IS_TYPE,          // nested type
435            CALLER_SENSITIVE = MN_CALLER_SENSITIVE; // @CallerSensitive annotation detected
436
437    static final int ALL_ACCESS = Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED;
438    static final int ALL_KINDS = IS_METHOD | IS_CONSTRUCTOR | IS_FIELD | IS_TYPE;
439    static final int IS_INVOCABLE = IS_METHOD | IS_CONSTRUCTOR;
440    static final int IS_FIELD_OR_METHOD = IS_METHOD | IS_FIELD;
441    static final int SEARCH_ALL_SUPERS = MN_SEARCH_SUPERCLASSES | MN_SEARCH_INTERFACES;
442
443    /** Utility method to query whether this member is a method or constructor. */
444    public boolean isInvocable() {
445        return testAnyFlags(IS_INVOCABLE);
446    }
447    /** Utility method to query whether this member is a method, constructor, or field. */
448    public boolean isFieldOrMethod() {
449        return testAnyFlags(IS_FIELD_OR_METHOD);
450    }
451    /** Query whether this member is a method. */
452    public boolean isMethod() {
453        return testAllFlags(IS_METHOD);
454    }
455    /** Query whether this member is a constructor. */
456    public boolean isConstructor() {
457        return testAllFlags(IS_CONSTRUCTOR);
458    }
459    /** Query whether this member is a field. */
460    public boolean isField() {
461        return testAllFlags(IS_FIELD);
462    }
463    /** Query whether this member is a type. */
464    public boolean isType() {
465        return testAllFlags(IS_TYPE);
466    }
467    /** Utility method to query whether this member is neither public, private, nor protected. */
468    public boolean isPackage() {
469        return !testAnyFlags(ALL_ACCESS);
470    }
471    /** Query whether this member has a CallerSensitive annotation. */
472    public boolean isCallerSensitive() {
473        return testAllFlags(CALLER_SENSITIVE);
474    }
475
476    /** Utility method to query whether this member is accessible from a given lookup class. */
477    public boolean isAccessibleFrom(Class<?> lookupClass) {
478        return VerifyAccess.isMemberAccessible(this.getDeclaringClass(), this.getDeclaringClass(), flags,
479                                               lookupClass, ALL_ACCESS|MethodHandles.Lookup.PACKAGE);
480    }
481
482    /** Initialize a query.   It is not resolved. */
483    private void init(Class<?> defClass, String name, Object type, int flags) {
484        // defining class is allowed to be null (for a naked name/type pair)
485        //name.toString();  // null check
486        //type.equals(type);  // null check
487        // fill in fields:
488        this.clazz = defClass;
489        this.name = name;
490        this.type = type;
491        this.flags = flags;
492        assert(testAnyFlags(ALL_KINDS));
493        assert(this.resolution == null);  // nobody should have touched this yet
494        //assert(referenceKindIsConsistent());  // do this after resolution
495    }
496
497    /**
498     * Calls down to the VM to fill in the fields.  This method is
499     * synchronized to avoid racing calls.
500     */
501    private void expandFromVM() {
502        if (type != null) {
503            return;
504        }
505        if (!isResolved()) {
506            return;
507        }
508        MethodHandleNatives.expand(this);
509    }
510
511    // Capturing information from the Core Reflection API:
512    private static int flagsMods(int flags, int mods, byte refKind) {
513        assert((flags & RECOGNIZED_MODIFIERS) == 0);
514        assert((mods & ~RECOGNIZED_MODIFIERS) == 0);
515        assert((refKind & ~MN_REFERENCE_KIND_MASK) == 0);
516        return flags | mods | (refKind << MN_REFERENCE_KIND_SHIFT);
517    }
518    /** Create a name for the given reflected method.  The resulting name will be in a resolved state. */
519    public MemberName(Method m) {
520        this(m, false);
521    }
522    @SuppressWarnings("LeakingThisInConstructor")
523    public MemberName(Method m, boolean wantSpecial) {
524        Objects.requireNonNull(m);
525        // fill in vmtarget, vmindex while we have m in hand:
526        MethodHandleNatives.init(this, m);
527        if (clazz == null) {  // MHN.init failed
528            if (m.getDeclaringClass() == MethodHandle.class &&
529                isMethodHandleInvokeName(m.getName())) {
530                // The JVM did not reify this signature-polymorphic instance.
531                // Need a special case here.
532                // See comments on MethodHandleNatives.linkMethod.
533                MethodType type = MethodType.methodType(m.getReturnType(), m.getParameterTypes());
534                int flags = flagsMods(IS_METHOD, m.getModifiers(), REF_invokeVirtual);
535                init(MethodHandle.class, m.getName(), type, flags);
536                if (isMethodHandleInvoke())
537                    return;
538            }
539            throw new LinkageError(m.toString());
540        }
541        assert(isResolved() && this.clazz != null);
542        this.name = m.getName();
543        if (this.type == null)
544            this.type = new Object[] { m.getReturnType(), m.getParameterTypes() };
545        if (wantSpecial) {
546            if (isAbstract())
547                throw new AbstractMethodError(this.toString());
548            if (getReferenceKind() == REF_invokeVirtual)
549                changeReferenceKind(REF_invokeSpecial, REF_invokeVirtual);
550            else if (getReferenceKind() == REF_invokeInterface)
551                // invokeSpecial on a default method
552                changeReferenceKind(REF_invokeSpecial, REF_invokeInterface);
553        }
554    }
555    public MemberName asSpecial() {
556        switch (getReferenceKind()) {
557        case REF_invokeSpecial:     return this;
558        case REF_invokeVirtual:     return clone().changeReferenceKind(REF_invokeSpecial, REF_invokeVirtual);
559        case REF_invokeInterface:   return clone().changeReferenceKind(REF_invokeSpecial, REF_invokeInterface);
560        case REF_newInvokeSpecial:  return clone().changeReferenceKind(REF_invokeSpecial, REF_newInvokeSpecial);
561        }
562        throw new IllegalArgumentException(this.toString());
563    }
564    /** If this MN is not REF_newInvokeSpecial, return a clone with that ref. kind.
565     *  In that case it must already be REF_invokeSpecial.
566     */
567    public MemberName asConstructor() {
568        switch (getReferenceKind()) {
569        case REF_invokeSpecial:     return clone().changeReferenceKind(REF_newInvokeSpecial, REF_invokeSpecial);
570        case REF_newInvokeSpecial:  return this;
571        }
572        throw new IllegalArgumentException(this.toString());
573    }
574    /** If this MN is a REF_invokeSpecial, return a clone with the "normal" kind
575     *  REF_invokeVirtual; also switch either to REF_invokeInterface if clazz.isInterface.
576     *  The end result is to get a fully virtualized version of the MN.
577     *  (Note that resolving in the JVM will sometimes devirtualize, changing
578     *  REF_invokeVirtual of a final to REF_invokeSpecial, and REF_invokeInterface
579     *  in some corner cases to either of the previous two; this transform
580     *  undoes that change under the assumption that it occurred.)
581     */
582    public MemberName asNormalOriginal() {
583        byte normalVirtual = clazz.isInterface() ? REF_invokeInterface : REF_invokeVirtual;
584        byte refKind = getReferenceKind();
585        byte newRefKind = refKind;
586        MemberName result = this;
587        switch (refKind) {
588        case REF_invokeInterface:
589        case REF_invokeVirtual:
590        case REF_invokeSpecial:
591            newRefKind = normalVirtual;
592            break;
593        }
594        if (newRefKind == refKind)
595            return this;
596        result = clone().changeReferenceKind(newRefKind, refKind);
597        assert(this.referenceKindIsConsistentWith(result.getReferenceKind()));
598        return result;
599    }
600    /** Create a name for the given reflected constructor.  The resulting name will be in a resolved state. */
601    @SuppressWarnings("LeakingThisInConstructor")
602    public MemberName(Constructor<?> ctor) {
603        Objects.requireNonNull(ctor);
604        // fill in vmtarget, vmindex while we have ctor in hand:
605        MethodHandleNatives.init(this, ctor);
606        assert(isResolved() && this.clazz != null);
607        this.name = CONSTRUCTOR_NAME;
608        if (this.type == null)
609            this.type = new Object[] { void.class, ctor.getParameterTypes() };
610    }
611    /** Create a name for the given reflected field.  The resulting name will be in a resolved state.
612     */
613    public MemberName(Field fld) {
614        this(fld, false);
615    }
616    @SuppressWarnings("LeakingThisInConstructor")
617    public MemberName(Field fld, boolean makeSetter) {
618        Objects.requireNonNull(fld);
619        // fill in vmtarget, vmindex while we have fld in hand:
620        MethodHandleNatives.init(this, fld);
621        assert(isResolved() && this.clazz != null);
622        this.name = fld.getName();
623        this.type = fld.getType();
624        assert((REF_putStatic - REF_getStatic) == (REF_putField - REF_getField));
625        byte refKind = this.getReferenceKind();
626        assert(refKind == (isStatic() ? REF_getStatic : REF_getField));
627        if (makeSetter) {
628            changeReferenceKind((byte)(refKind + (REF_putStatic - REF_getStatic)), refKind);
629        }
630    }
631    public boolean isGetter() {
632        return MethodHandleNatives.refKindIsGetter(getReferenceKind());
633    }
634    public boolean isSetter() {
635        return MethodHandleNatives.refKindIsSetter(getReferenceKind());
636    }
637    public MemberName asSetter() {
638        byte refKind = getReferenceKind();
639        assert(MethodHandleNatives.refKindIsGetter(refKind));
640        assert((REF_putStatic - REF_getStatic) == (REF_putField - REF_getField));
641        byte setterRefKind = (byte)(refKind + (REF_putField - REF_getField));
642        return clone().changeReferenceKind(setterRefKind, refKind);
643    }
644    /** Create a name for the given class.  The resulting name will be in a resolved state. */
645    public MemberName(Class<?> type) {
646        init(type.getDeclaringClass(), type.getSimpleName(), type,
647                flagsMods(IS_TYPE, type.getModifiers(), REF_NONE));
648        initResolved(true);
649    }
650
651    /**
652     * Create a name for a signature-polymorphic invoker.
653     * This is a placeholder for a signature-polymorphic instance
654     * (of MH.invokeExact, etc.) that the JVM does not reify.
655     * See comments on {@link MethodHandleNatives#linkMethod}.
656     */
657    static MemberName makeMethodHandleInvoke(String name, MethodType type) {
658        return makeMethodHandleInvoke(name, type, MH_INVOKE_MODS | SYNTHETIC);
659    }
660    static MemberName makeMethodHandleInvoke(String name, MethodType type, int mods) {
661        MemberName mem = new MemberName(MethodHandle.class, name, type, REF_invokeVirtual);
662        mem.flags |= mods;  // it's not resolved, but add these modifiers anyway
663        assert(mem.isMethodHandleInvoke()) : mem;
664        return mem;
665    }
666
667    // bare-bones constructor; the JVM will fill it in
668    MemberName() { }
669
670    // locally useful cloner
671    @Override protected MemberName clone() {
672        try {
673            return (MemberName) super.clone();
674        } catch (CloneNotSupportedException ex) {
675            throw newInternalError(ex);
676        }
677     }
678
679    /** Get the definition of this member name.
680     *  This may be in a super-class of the declaring class of this member.
681     */
682    public MemberName getDefinition() {
683        if (!isResolved())  throw new IllegalStateException("must be resolved: "+this);
684        if (isType())  return this;
685        MemberName res = this.clone();
686        res.clazz = null;
687        res.type = null;
688        res.name = null;
689        res.resolution = res;
690        res.expandFromVM();
691        assert(res.getName().equals(this.getName()));
692        return res;
693    }
694
695    @Override
696    public int hashCode() {
697        // Avoid autoboxing getReferenceKind(), since this is used early and will force
698        // early initialization of Byte$ByteCache
699        return Objects.hash(clazz, new Byte(getReferenceKind()), name, getType());
700    }
701
702    @Override
703    public boolean equals(Object that) {
704        return (that instanceof MemberName && this.equals((MemberName)that));
705    }
706
707    /** Decide if two member names have exactly the same symbolic content.
708     *  Does not take into account any actual class members, so even if
709     *  two member names resolve to the same actual member, they may
710     *  be distinct references.
711     */
712    public boolean equals(MemberName that) {
713        if (this == that)  return true;
714        if (that == null)  return false;
715        return this.clazz == that.clazz
716                && this.getReferenceKind() == that.getReferenceKind()
717                && Objects.equals(this.name, that.name)
718                && Objects.equals(this.getType(), that.getType());
719    }
720
721    // Construction from symbolic parts, for queries:
722    /** Create a field or type name from the given components:
723     *  Declaring class, name, type, reference kind.
724     *  The declaring class may be supplied as null if this is to be a bare name and type.
725     *  The resulting name will in an unresolved state.
726     */
727    public MemberName(Class<?> defClass, String name, Class<?> type, byte refKind) {
728        init(defClass, name, type, flagsMods(IS_FIELD, 0, refKind));
729        initResolved(false);
730    }
731    /** Create a method or constructor name from the given components:
732     *  Declaring class, name, type, reference kind.
733     *  It will be a constructor if and only if the name is {@code "<init>"}.
734     *  The declaring class may be supplied as null if this is to be a bare name and type.
735     *  The last argument is optional, a boolean which requests REF_invokeSpecial.
736     *  The resulting name will in an unresolved state.
737     */
738    public MemberName(Class<?> defClass, String name, MethodType type, byte refKind) {
739        int initFlags = (name != null && name.equals(CONSTRUCTOR_NAME) ? IS_CONSTRUCTOR : IS_METHOD);
740        init(defClass, name, type, flagsMods(initFlags, 0, refKind));
741        initResolved(false);
742    }
743    /** Create a method, constructor, or field name from the given components:
744     *  Reference kind, declaring class, name, type.
745     */
746    public MemberName(byte refKind, Class<?> defClass, String name, Object type) {
747        int kindFlags;
748        if (MethodHandleNatives.refKindIsField(refKind)) {
749            kindFlags = IS_FIELD;
750            if (!(type instanceof Class))
751                throw newIllegalArgumentException("not a field type");
752        } else if (MethodHandleNatives.refKindIsMethod(refKind)) {
753            kindFlags = IS_METHOD;
754            if (!(type instanceof MethodType))
755                throw newIllegalArgumentException("not a method type");
756        } else if (refKind == REF_newInvokeSpecial) {
757            kindFlags = IS_CONSTRUCTOR;
758            if (!(type instanceof MethodType) ||
759                !CONSTRUCTOR_NAME.equals(name))
760                throw newIllegalArgumentException("not a constructor type or name");
761        } else {
762            throw newIllegalArgumentException("bad reference kind "+refKind);
763        }
764        init(defClass, name, type, flagsMods(kindFlags, 0, refKind));
765        initResolved(false);
766    }
767    /** Query whether this member name is resolved to a non-static, non-final method.
768     */
769    public boolean hasReceiverTypeDispatch() {
770        return MethodHandleNatives.refKindDoesDispatch(getReferenceKind());
771    }
772
773    /** Query whether this member name is resolved.
774     *  A resolved member name is one for which the JVM has found
775     *  a method, constructor, field, or type binding corresponding exactly to the name.
776     *  (Document?)
777     */
778    public boolean isResolved() {
779        return resolution == null;
780    }
781
782    private void initResolved(boolean isResolved) {
783        assert(this.resolution == null);  // not initialized yet!
784        if (!isResolved)
785            this.resolution = this;
786        assert(isResolved() == isResolved);
787    }
788
789    void checkForTypeAlias() {
790        if (isInvocable()) {
791            MethodType type;
792            if (this.type instanceof MethodType)
793                type = (MethodType) this.type;
794            else
795                this.type = type = getMethodType();
796            if (type.erase() == type)  return;
797            if (VerifyAccess.isTypeVisible(type, clazz))  return;
798            throw new LinkageError("bad method type alias: "+type+" not visible from "+clazz);
799        } else {
800            Class<?> type;
801            if (this.type instanceof Class<?>)
802                type = (Class<?>) this.type;
803            else
804                this.type = type = getFieldType();
805            if (VerifyAccess.isTypeVisible(type, clazz))  return;
806            throw new LinkageError("bad field type alias: "+type+" not visible from "+clazz);
807        }
808    }
809
810
811    /** Produce a string form of this member name.
812     *  For types, it is simply the type's own string (as reported by {@code toString}).
813     *  For fields, it is {@code "DeclaringClass.name/type"}.
814     *  For methods and constructors, it is {@code "DeclaringClass.name(ptype...)rtype"}.
815     *  If the declaring class is null, the prefix {@code "DeclaringClass."} is omitted.
816     *  If the member is unresolved, a prefix {@code "*."} is prepended.
817     */
818    @SuppressWarnings("LocalVariableHidesMemberVariable")
819    @Override
820    public String toString() {
821        if (isType())
822            return type.toString();  // class java.lang.String
823        // else it is a field, method, or constructor
824        StringBuilder buf = new StringBuilder();
825        if (getDeclaringClass() != null) {
826            buf.append(getName(clazz));
827            buf.append('.');
828        }
829        String name = getName();
830        buf.append(name == null ? "*" : name);
831        Object type = getType();
832        if (!isInvocable()) {
833            buf.append('/');
834            buf.append(type == null ? "*" : getName(type));
835        } else {
836            buf.append(type == null ? "(*)*" : getName(type));
837        }
838        byte refKind = getReferenceKind();
839        if (refKind != REF_NONE) {
840            buf.append('/');
841            buf.append(MethodHandleNatives.refKindName(refKind));
842        }
843        //buf.append("#").append(System.identityHashCode(this));
844        return buf.toString();
845    }
846    private static String getName(Object obj) {
847        if (obj instanceof Class<?>)
848            return ((Class<?>)obj).getName();
849        return String.valueOf(obj);
850    }
851
852    public IllegalAccessException makeAccessException(String message, Object from) {
853        message = message + ": "+ toString();
854        if (from != null)  message += ", from " + from;
855        return new IllegalAccessException(message);
856    }
857    private String message() {
858        if (isResolved())
859            return "no access";
860        else if (isConstructor())
861            return "no such constructor";
862        else if (isMethod())
863            return "no such method";
864        else
865            return "no such field";
866    }
867    public ReflectiveOperationException makeAccessException() {
868        String message = message() + ": "+ toString();
869        ReflectiveOperationException ex;
870        if (isResolved() || !(resolution instanceof NoSuchMethodError ||
871                              resolution instanceof NoSuchFieldError))
872            ex = new IllegalAccessException(message);
873        else if (isConstructor())
874            ex = new NoSuchMethodException(message);
875        else if (isMethod())
876            ex = new NoSuchMethodException(message);
877        else
878            ex = new NoSuchFieldException(message);
879        if (resolution instanceof Throwable)
880            ex.initCause((Throwable) resolution);
881        return ex;
882    }
883
884    /** Actually making a query requires an access check. */
885    /*non-public*/ static Factory getFactory() {
886        return Factory.INSTANCE;
887    }
888    /** A factory type for resolving member names with the help of the VM.
889     *  TBD: Define access-safe public constructors for this factory.
890     */
891    /*non-public*/ static class Factory {
892        private Factory() { } // singleton pattern
893        static Factory INSTANCE = new Factory();
894
895        private static int ALLOWED_FLAGS = ALL_KINDS;
896
897        /// Queries
898        List<MemberName> getMembers(Class<?> defc,
899                String matchName, Object matchType,
900                int matchFlags, Class<?> lookupClass) {
901            matchFlags &= ALLOWED_FLAGS;
902            String matchSig = null;
903            if (matchType != null) {
904                matchSig = BytecodeDescriptor.unparse(matchType);
905                if (matchSig.startsWith("("))
906                    matchFlags &= ~(ALL_KINDS & ~IS_INVOCABLE);
907                else
908                    matchFlags &= ~(ALL_KINDS & ~IS_FIELD);
909            }
910            final int BUF_MAX = 0x2000;
911            int len1 = matchName == null ? 10 : matchType == null ? 4 : 1;
912            MemberName[] buf = newMemberBuffer(len1);
913            int totalCount = 0;
914            ArrayList<MemberName[]> bufs = null;
915            int bufCount = 0;
916            for (;;) {
917                bufCount = MethodHandleNatives.getMembers(defc,
918                        matchName, matchSig, matchFlags,
919                        lookupClass,
920                        totalCount, buf);
921                if (bufCount <= buf.length) {
922                    if (bufCount < 0)  bufCount = 0;
923                    totalCount += bufCount;
924                    break;
925                }
926                // JVM returned to us with an intentional overflow!
927                totalCount += buf.length;
928                int excess = bufCount - buf.length;
929                if (bufs == null)  bufs = new ArrayList<>(1);
930                bufs.add(buf);
931                int len2 = buf.length;
932                len2 = Math.max(len2, excess);
933                len2 = Math.max(len2, totalCount / 4);
934                buf = newMemberBuffer(Math.min(BUF_MAX, len2));
935            }
936            ArrayList<MemberName> result = new ArrayList<>(totalCount);
937            if (bufs != null) {
938                for (MemberName[] buf0 : bufs) {
939                    Collections.addAll(result, buf0);
940                }
941            }
942            result.addAll(Arrays.asList(buf).subList(0, bufCount));
943            // Signature matching is not the same as type matching, since
944            // one signature might correspond to several types.
945            // So if matchType is a Class or MethodType, refilter the results.
946            if (matchType != null && matchType != matchSig) {
947                for (Iterator<MemberName> it = result.iterator(); it.hasNext();) {
948                    MemberName m = it.next();
949                    if (!matchType.equals(m.getType()))
950                        it.remove();
951                }
952            }
953            return result;
954        }
955        /** Produce a resolved version of the given member.
956         *  Super types are searched (for inherited members) if {@code searchSupers} is true.
957         *  Access checking is performed on behalf of the given {@code lookupClass}.
958         *  If lookup fails or access is not permitted, null is returned.
959         *  Otherwise a fresh copy of the given member is returned, with modifier bits filled in.
960         */
961        private MemberName resolve(byte refKind, MemberName ref, Class<?> lookupClass) {
962            MemberName m = ref.clone();  // JVM will side-effect the ref
963            assert(refKind == m.getReferenceKind());
964            try {
965                m = MethodHandleNatives.resolve(m, lookupClass);
966                m.checkForTypeAlias();
967                m.resolution = null;
968            } catch (LinkageError ex) {
969                // JVM reports that the "bytecode behavior" would get an error
970                assert(!m.isResolved());
971                m.resolution = ex;
972                return m;
973            }
974            assert(m.referenceKindIsConsistent());
975            m.initResolved(true);
976            assert(m.vminfoIsConsistent());
977            return m;
978        }
979        /** Produce a resolved version of the given member.
980         *  Super types are searched (for inherited members) if {@code searchSupers} is true.
981         *  Access checking is performed on behalf of the given {@code lookupClass}.
982         *  If lookup fails or access is not permitted, a {@linkplain ReflectiveOperationException} is thrown.
983         *  Otherwise a fresh copy of the given member is returned, with modifier bits filled in.
984         */
985        public
986        <NoSuchMemberException extends ReflectiveOperationException>
987        MemberName resolveOrFail(byte refKind, MemberName m, Class<?> lookupClass,
988                                 Class<NoSuchMemberException> nsmClass)
989                throws IllegalAccessException, NoSuchMemberException {
990            MemberName result = resolve(refKind, m, lookupClass);
991            if (result.isResolved())
992                return result;
993            ReflectiveOperationException ex = result.makeAccessException();
994            if (ex instanceof IllegalAccessException)  throw (IllegalAccessException) ex;
995            throw nsmClass.cast(ex);
996        }
997        /** Produce a resolved version of the given member.
998         *  Super types are searched (for inherited members) if {@code searchSupers} is true.
999         *  Access checking is performed on behalf of the given {@code lookupClass}.
1000         *  If lookup fails or access is not permitted, return null.
1001         *  Otherwise a fresh copy of the given member is returned, with modifier bits filled in.
1002         */
1003        public
1004        MemberName resolveOrNull(byte refKind, MemberName m, Class<?> lookupClass) {
1005            MemberName result = resolve(refKind, m, lookupClass);
1006            if (result.isResolved())
1007                return result;
1008            return null;
1009        }
1010        /** Return a list of all methods defined by the given class.
1011         *  Super types are searched (for inherited members) if {@code searchSupers} is true.
1012         *  Access checking is performed on behalf of the given {@code lookupClass}.
1013         *  Inaccessible members are not added to the last.
1014         */
1015        public List<MemberName> getMethods(Class<?> defc, boolean searchSupers,
1016                Class<?> lookupClass) {
1017            return getMethods(defc, searchSupers, null, null, lookupClass);
1018        }
1019        /** Return a list of matching methods defined by the given class.
1020         *  Super types are searched (for inherited members) if {@code searchSupers} is true.
1021         *  Returned methods will match the name (if not null) and the type (if not null).
1022         *  Access checking is performed on behalf of the given {@code lookupClass}.
1023         *  Inaccessible members are not added to the last.
1024         */
1025        public List<MemberName> getMethods(Class<?> defc, boolean searchSupers,
1026                String name, MethodType type, Class<?> lookupClass) {
1027            int matchFlags = IS_METHOD | (searchSupers ? SEARCH_ALL_SUPERS : 0);
1028            return getMembers(defc, name, type, matchFlags, lookupClass);
1029        }
1030        /** Return a list of all constructors defined by the given class.
1031         *  Access checking is performed on behalf of the given {@code lookupClass}.
1032         *  Inaccessible members are not added to the last.
1033         */
1034        public List<MemberName> getConstructors(Class<?> defc, Class<?> lookupClass) {
1035            return getMembers(defc, null, null, IS_CONSTRUCTOR, lookupClass);
1036        }
1037        /** Return a list of all fields defined by the given class.
1038         *  Super types are searched (for inherited members) if {@code searchSupers} is true.
1039         *  Access checking is performed on behalf of the given {@code lookupClass}.
1040         *  Inaccessible members are not added to the last.
1041         */
1042        public List<MemberName> getFields(Class<?> defc, boolean searchSupers,
1043                Class<?> lookupClass) {
1044            return getFields(defc, searchSupers, null, null, lookupClass);
1045        }
1046        /** Return a list of all fields defined by the given class.
1047         *  Super types are searched (for inherited members) if {@code searchSupers} is true.
1048         *  Returned fields will match the name (if not null) and the type (if not null).
1049         *  Access checking is performed on behalf of the given {@code lookupClass}.
1050         *  Inaccessible members are not added to the last.
1051         */
1052        public List<MemberName> getFields(Class<?> defc, boolean searchSupers,
1053                String name, Class<?> type, Class<?> lookupClass) {
1054            int matchFlags = IS_FIELD | (searchSupers ? SEARCH_ALL_SUPERS : 0);
1055            return getMembers(defc, name, type, matchFlags, lookupClass);
1056        }
1057        /** Return a list of all nested types defined by the given class.
1058         *  Super types are searched (for inherited members) if {@code searchSupers} is true.
1059         *  Access checking is performed on behalf of the given {@code lookupClass}.
1060         *  Inaccessible members are not added to the last.
1061         */
1062        public List<MemberName> getNestedTypes(Class<?> defc, boolean searchSupers,
1063                Class<?> lookupClass) {
1064            int matchFlags = IS_TYPE | (searchSupers ? SEARCH_ALL_SUPERS : 0);
1065            return getMembers(defc, null, null, matchFlags, lookupClass);
1066        }
1067        private static MemberName[] newMemberBuffer(int length) {
1068            MemberName[] buf = new MemberName[length];
1069            // fill the buffer with dummy structs for the JVM to fill in
1070            for (int i = 0; i < length; i++)
1071                buf[i] = new MemberName();
1072            return buf;
1073        }
1074    }
1075
1076//    static {
1077//        System.out.println("Hello world!  My methods are:");
1078//        System.out.println(Factory.INSTANCE.getMethods(MemberName.class, true, null));
1079//    }
1080}
1081