MemberName.java 40.7 KB
Newer Older
1
/*
2
 * Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved.
3 4 5 6
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * 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 12 13 14 15 16 17 18 19 20
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
21 22 23
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
24 25
 */

26
package java.lang.invoke;
27

28
import sun.invoke.util.BytecodeDescriptor;
29 30
import sun.invoke.util.VerifyAccess;

31 32 33 34 35 36
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Member;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
37
import java.util.Arrays;
38 39 40
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
41 42
import static java.lang.invoke.MethodHandleNatives.Constants.*;
import static java.lang.invoke.MethodHandleStatics.*;
43
import java.util.Objects;
44 45

/**
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
 * A {@code MemberName} is a compact symbolic datum which fully characterizes
 * a method or field reference.
 * A member name refers to a field, method, constructor, or member type.
 * Every member name has a simple name (a string) and a type (either a Class or MethodType).
 * A member name may also have a non-null declaring class, or it may be simply
 * a naked name/type pair.
 * A member name may also have non-zero modifier flags.
 * Finally, a member name may be either resolved or unresolved.
 * If it is resolved, the existence of the named
 * <p>
 * Whether resolved or not, a member name provides no access rights or
 * invocation capability to its possessor.  It is merely a compact
 * representation of all symbolic information necessary to link to
 * and properly use the named member.
 * <p>
 * When resolved, a member name's internal implementation may include references to JVM metadata.
62 63 64
 * This representation is stateless and only decriptive.
 * It provides no private information and no capability to use the member.
 * <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 68
 * allows invocation.  A MemberName is much lighter than a Method,
 * since it contains about 7 fields to the 16 of Method (plus its sub-arrays),
69 70 71
 * and those seven fields omit much of the information in Method.
 * @author jrose
 */
72
/*non-public*/ final class MemberName implements Member, Cloneable {
73 74 75 76
    private Class<?>   clazz;       // class in which the method is defined
    private String     name;        // may be null if not yet materialized
    private Object     type;        // may be null if not yet materialized
    private int        flags;       // modifier bits; see reflect.Modifier
77 78 79
    //@Injected JVM_Method* vmtarget;
    //@Injected int         vmindex;
    private Object     resolution;  // if null, this guy is resolved
80

81 82 83
    /** Return the declaring class of this member.
     *  In the case of a bare name and type, the declaring class will be null.
     */
84 85 86 87
    public Class<?> getDeclaringClass() {
        return clazz;
    }

88
    /** Utility method producing the class loader of the declaring class. */
89 90 91 92
    public ClassLoader getClassLoader() {
        return clazz.getClassLoader();
    }

93 94 95 96 97
    /** Return the simple name of this member.
     *  For a type, it is the same as {@link Class#getSimpleName}.
     *  For a method or field, it is the simple name of the member.
     *  For a constructor, it is always {@code "&lt;init&gt;"}.
     */
98 99 100 101 102 103 104 105
    public String getName() {
        if (name == null) {
            expandFromVM();
            if (name == null)  return null;
        }
        return name;
    }

106 107 108 109 110 111 112 113 114 115
    public MethodType getMethodOrFieldType() {
        if (isInvocable())
            return getMethodType();
        if (isGetter())
            return MethodType.methodType(getFieldType());
        if (isSetter())
            return MethodType.methodType(void.class, getFieldType());
        throw new InternalError("not a method or field: "+this);
    }

116 117 118
    /** Return the declared type of this member, which
     *  must be a method or constructor.
     */
119 120 121 122 123 124 125 126 127 128 129 130
    public MethodType getMethodType() {
        if (type == null) {
            expandFromVM();
            if (type == null)  return null;
        }
        if (!isInvocable())
            throw newIllegalArgumentException("not invocable, no method type");
        if (type instanceof MethodType) {
            return (MethodType) type;
        }
        if (type instanceof String) {
            String sig = (String) type;
131
            MethodType res = MethodType.fromMethodDescriptorString(sig, getClassLoader());
132 133 134 135 136 137 138
            this.type = res;
            return res;
        }
        if (type instanceof Object[]) {
            Object[] typeInfo = (Object[]) type;
            Class<?>[] ptypes = (Class<?>[]) typeInfo[1];
            Class<?> rtype = (Class<?>) typeInfo[0];
139
            MethodType res = MethodType.methodType(rtype, ptypes);
140 141 142 143 144 145
            this.type = res;
            return res;
        }
        throw new InternalError("bad method type "+type);
    }

146 147 148 149
    /** Return the actual type under which this method or constructor must be invoked.
     *  For non-static methods or constructors, this is the type with a leading parameter,
     *  a reference to declaring class.  For static methods, it is the same as the declared type.
     */
150
    public MethodType getInvocationType() {
151 152 153
        MethodType itype = getMethodOrFieldType();
        if (isConstructor() && getReferenceKind() == REF_newInvokeSpecial)
            return itype.changeReturnType(clazz);
154
        if (!isStatic())
155
            return itype.insertParameterTypes(0, clazz);
156 157 158
        return itype;
    }

159
    /** Utility method producing the parameter types of the method type. */
160 161 162 163
    public Class<?>[] getParameterTypes() {
        return getMethodType().parameterArray();
    }

164
    /** Utility method producing the return type of the method type. */
165 166 167 168
    public Class<?> getReturnType() {
        return getMethodType().returnType();
    }

169 170 171 172
    /** Return the declared type of this member, which
     *  must be a field or type.
     *  If it is a type member, that type itself is returned.
     */
173 174 175 176 177 178 179 180 181 182 183 184
    public Class<?> getFieldType() {
        if (type == null) {
            expandFromVM();
            if (type == null)  return null;
        }
        if (isInvocable())
            throw newIllegalArgumentException("not a field or nested class, no simple type");
        if (type instanceof Class<?>) {
            return (Class<?>) type;
        }
        if (type instanceof String) {
            String sig = (String) type;
185
            MethodType mtype = MethodType.fromMethodDescriptorString("()"+sig, getClassLoader());
186 187 188 189 190 191 192
            Class<?> res = mtype.returnType();
            this.type = res;
            return res;
        }
        throw new InternalError("bad field type "+type);
    }

193
    /** Utility method to produce either the method type or field type of this member. */
194 195 196 197
    public Object getType() {
        return (isInvocable() ? getMethodType() : getFieldType());
    }

198 199 200
    /** Utility method to produce the signature of this member,
     *  used within the class file format to describe its type.
     */
201 202 203 204 205 206 207 208
    public String getSignature() {
        if (type == null) {
            expandFromVM();
            if (type == null)  return null;
        }
        if (type instanceof String)
            return (String) type;
        if (isInvocable())
209
            return BytecodeDescriptor.unparse(getMethodType());
210
        else
211
            return BytecodeDescriptor.unparse(getFieldType());
212 213
    }

214 215 216
    /** Return the modifier flags of this member.
     *  @see java.lang.reflect.Modifier
     */
217 218 219 220
    public int getModifiers() {
        return (flags & RECOGNIZED_MODIFIERS);
    }

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
    /** Return the reference kind of this member, or zero if none.
     */
    public byte getReferenceKind() {
        return (byte) ((flags >>> MN_REFERENCE_KIND_SHIFT) & MN_REFERENCE_KIND_MASK);
    }
    private boolean referenceKindIsConsistent() {
        byte refKind = getReferenceKind();
        if (refKind == REF_NONE)  return isType();
        if (isField()) {
            assert(staticIsConsistent());
            assert(MethodHandleNatives.refKindIsField(refKind));
        } else if (isConstructor()) {
            assert(refKind == REF_newInvokeSpecial || refKind == REF_invokeSpecial);
        } else if (isMethod()) {
            assert(staticIsConsistent());
            assert(MethodHandleNatives.refKindIsMethod(refKind));
            if (clazz.isInterface())
                assert(refKind == REF_invokeInterface ||
                       refKind == REF_invokeVirtual && isObjectPublicMethod());
        } else {
            assert(false);
        }
        return true;
    }
    private boolean isObjectPublicMethod() {
        if (clazz == Object.class)  return true;
        MethodType mtype = getMethodType();
        if (name.equals("toString") && mtype.returnType() == String.class && mtype.parameterCount() == 0)
            return true;
        if (name.equals("hashCode") && mtype.returnType() == int.class && mtype.parameterCount() == 0)
            return true;
        if (name.equals("equals") && mtype.returnType() == boolean.class && mtype.parameterCount() == 1 && mtype.parameterType(0) == Object.class)
            return true;
        return false;
    }
    /*non-public*/ boolean referenceKindIsConsistentWith(int originalRefKind) {
        int refKind = getReferenceKind();
        if (refKind == originalRefKind)  return true;
        switch (originalRefKind) {
        case REF_invokeInterface:
            // Looking up an interface method, can get (e.g.) Object.hashCode
            assert(refKind == REF_invokeVirtual ||
                   refKind == REF_invokeSpecial) : this;
            return true;
        case REF_invokeVirtual:
        case REF_newInvokeSpecial:
            // Looked up a virtual, can get (e.g.) final String.hashCode.
            assert(refKind == REF_invokeSpecial) : this;
            return true;
        }
        assert(false) : this;
        return true;
    }
    private boolean staticIsConsistent() {
        byte refKind = getReferenceKind();
        return MethodHandleNatives.refKindIsStatic(refKind) == isStatic() || getModifiers() == 0;
    }
    private boolean vminfoIsConsistent() {
        byte refKind = getReferenceKind();
        assert(isResolved());  // else don't call
        Object vminfo = MethodHandleNatives.getMemberVMInfo(this);
        assert(vminfo instanceof Object[]);
        long vmindex = (Long) ((Object[])vminfo)[0];
        Object vmtarget = ((Object[])vminfo)[1];
        if (MethodHandleNatives.refKindIsField(refKind)) {
            assert(vmindex >= 0) : vmindex + ":" + this;
            assert(vmtarget instanceof Class);
        } else {
            if (MethodHandleNatives.refKindDoesDispatch(refKind))
                assert(vmindex >= 0) : vmindex + ":" + this;
            else
                assert(vmindex < 0) : vmindex;
            assert(vmtarget instanceof MemberName) : vmtarget + " in " + this;
        }
        return true;
    }

    private MemberName changeReferenceKind(byte refKind, byte oldKind) {
        assert(getReferenceKind() == oldKind);
        assert(MethodHandleNatives.refKindIsValid(refKind));
        flags += (((int)refKind - oldKind) << MN_REFERENCE_KIND_SHIFT);
//        if (isConstructor() && refKind != REF_newInvokeSpecial)
//            flags += (IS_METHOD - IS_CONSTRUCTOR);
//        else if (refKind == REF_newInvokeSpecial && isMethod())
//            flags += (IS_CONSTRUCTOR - IS_METHOD);
        return this;
    }

309 310 311 312 313 314 315 316 317 318
    private boolean testFlags(int mask, int value) {
        return (flags & mask) == value;
    }
    private boolean testAllFlags(int mask) {
        return testFlags(mask, mask);
    }
    private boolean testAnyFlags(int mask) {
        return !testFlags(mask, 0);
    }

319 320 321 322 323 324 325 326 327 328 329
    /** Utility method to query if this member is a method handle invocation (invoke or invokeExact). */
    public boolean isMethodHandleInvoke() {
        final int bits = Modifier.NATIVE | Modifier.FINAL;
        final int negs = Modifier.STATIC;
        if (testFlags(bits | negs, bits) &&
            clazz == MethodHandle.class) {
            return name.equals("invoke") || name.equals("invokeExact");
        }
        return false;
    }

330
    /** Utility method to query the modifier flags of this member. */
331 332 333
    public boolean isStatic() {
        return Modifier.isStatic(flags);
    }
334
    /** Utility method to query the modifier flags of this member. */
335 336 337
    public boolean isPublic() {
        return Modifier.isPublic(flags);
    }
338
    /** Utility method to query the modifier flags of this member. */
339 340 341
    public boolean isPrivate() {
        return Modifier.isPrivate(flags);
    }
342
    /** Utility method to query the modifier flags of this member. */
343 344 345
    public boolean isProtected() {
        return Modifier.isProtected(flags);
    }
346
    /** Utility method to query the modifier flags of this member. */
347 348 349
    public boolean isFinal() {
        return Modifier.isFinal(flags);
    }
350 351 352 353 354 355 356 357
    /** Utility method to query whether this member or its defining class is final. */
    public boolean canBeStaticallyBound() {
        return Modifier.isFinal(flags | clazz.getModifiers());
    }
    /** Utility method to query the modifier flags of this member. */
    public boolean isVolatile() {
        return Modifier.isVolatile(flags);
    }
358
    /** Utility method to query the modifier flags of this member. */
359 360 361
    public boolean isAbstract() {
        return Modifier.isAbstract(flags);
    }
362 363 364 365
    /** Utility method to query the modifier flags of this member. */
    public boolean isNative() {
        return Modifier.isNative(flags);
    }
366 367 368 369 370 371 372 373
    // let the rest (native, volatile, transient, etc.) be tested via Modifier.isFoo

    // unofficial modifier flags, used by HotSpot:
    static final int BRIDGE    = 0x00000040;
    static final int VARARGS   = 0x00000080;
    static final int SYNTHETIC = 0x00001000;
    static final int ANNOTATION= 0x00002000;
    static final int ENUM      = 0x00004000;
374
    /** Utility method to query the modifier flags of this member; returns false if the member is not a method. */
375 376 377
    public boolean isBridge() {
        return testAllFlags(IS_METHOD | BRIDGE);
    }
378
    /** Utility method to query the modifier flags of this member; returns false if the member is not a method. */
379 380 381
    public boolean isVarargs() {
        return testAllFlags(VARARGS) && isInvocable();
    }
382
    /** Utility method to query the modifier flags of this member; returns false if the member is not a method. */
383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
    public boolean isSynthetic() {
        return testAllFlags(SYNTHETIC);
    }

    static final String CONSTRUCTOR_NAME = "<init>";  // the ever-popular

    // modifiers exported by the JVM:
    static final int RECOGNIZED_MODIFIERS = 0xFFFF;

    // private flags, not part of RECOGNIZED_MODIFIERS:
    static final int
            IS_METHOD      = MN_IS_METHOD,      // method (not constructor)
            IS_CONSTRUCTOR = MN_IS_CONSTRUCTOR, // constructor
            IS_FIELD       = MN_IS_FIELD,       // field
            IS_TYPE        = MN_IS_TYPE;        // nested type

    static final int ALL_ACCESS = Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED;
    static final int ALL_KINDS = IS_METHOD | IS_CONSTRUCTOR | IS_FIELD | IS_TYPE;
    static final int IS_INVOCABLE = IS_METHOD | IS_CONSTRUCTOR;
    static final int IS_FIELD_OR_METHOD = IS_METHOD | IS_FIELD;
403
    static final int SEARCH_ALL_SUPERS = MN_SEARCH_SUPERCLASSES | MN_SEARCH_INTERFACES;
404

405
    /** Utility method to query whether this member is a method or constructor. */
406 407 408
    public boolean isInvocable() {
        return testAnyFlags(IS_INVOCABLE);
    }
409
    /** Utility method to query whether this member is a method, constructor, or field. */
410 411 412
    public boolean isFieldOrMethod() {
        return testAnyFlags(IS_FIELD_OR_METHOD);
    }
413
    /** Query whether this member is a method. */
414 415 416
    public boolean isMethod() {
        return testAllFlags(IS_METHOD);
    }
417
    /** Query whether this member is a constructor. */
418 419 420
    public boolean isConstructor() {
        return testAllFlags(IS_CONSTRUCTOR);
    }
421
    /** Query whether this member is a field. */
422 423 424
    public boolean isField() {
        return testAllFlags(IS_FIELD);
    }
425
    /** Query whether this member is a type. */
426 427 428
    public boolean isType() {
        return testAllFlags(IS_TYPE);
    }
429
    /** Utility method to query whether this member is neither public, private, nor protected. */
430 431 432 433
    public boolean isPackage() {
        return !testAnyFlags(ALL_ACCESS);
    }

434 435 436 437 438 439
    /** Utility method to query whether this member is accessible from a given lookup class. */
    public boolean isAccessibleFrom(Class<?> lookupClass) {
        return VerifyAccess.isMemberAccessible(this.getDeclaringClass(), this.getDeclaringClass(), flags,
                                               lookupClass, ALL_ACCESS|MethodHandles.Lookup.PACKAGE);
    }

440 441 442
    /** Initialize a query.   It is not resolved. */
    private void init(Class<?> defClass, String name, Object type, int flags) {
        // defining class is allowed to be null (for a naked name/type pair)
443 444
        //name.toString();  // null check
        //type.equals(type);  // null check
445 446 447 448
        // fill in fields:
        this.clazz = defClass;
        this.name = name;
        this.type = type;
J
jrose 已提交
449 450
        this.flags = flags;
        assert(testAnyFlags(ALL_KINDS));
451
        assert(this.resolution == null);  // nobody should have touched this yet
J
jrose 已提交
452
        //assert(referenceKindIsConsistent());  // do this after resolution
453 454 455 456 457 458 459 460 461 462
    }

    private void expandFromVM() {
        if (!isResolved())  return;
        if (type instanceof Object[])
            type = null;  // don't saddle JVM w/ typeInfo
        MethodHandleNatives.expand(this);
    }

    // Capturing information from the Core Reflection API:
463
    private static int flagsMods(int flags, int mods, byte refKind) {
464 465
        assert((flags & RECOGNIZED_MODIFIERS) == 0);
        assert((mods & ~RECOGNIZED_MODIFIERS) == 0);
466 467
        assert((refKind & ~MN_REFERENCE_KIND_MASK) == 0);
        return flags | mods | (refKind << MN_REFERENCE_KIND_SHIFT);
468
    }
469
    /** Create a name for the given reflected method.  The resulting name will be in a resolved state. */
470
    public MemberName(Method m) {
471 472 473 474
        this(m, false);
    }
    @SuppressWarnings("LeakingThisInConstructor")
    public MemberName(Method m, boolean wantSpecial) {
475
        m.getClass();  // NPE check
476 477
        // fill in vmtarget, vmindex while we have m in hand:
        MethodHandleNatives.init(this, m);
478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
        assert(isResolved() && this.clazz != null);
        this.name = m.getName();
        if (this.type == null)
            this.type = new Object[] { m.getReturnType(), m.getParameterTypes() };
        if (wantSpecial) {
            if (getReferenceKind() == REF_invokeVirtual)
                changeReferenceKind(REF_invokeSpecial, REF_invokeVirtual);
        }
    }
    public MemberName asSpecial() {
        switch (getReferenceKind()) {
        case REF_invokeSpecial:     return this;
        case REF_invokeVirtual:     return clone().changeReferenceKind(REF_invokeSpecial, REF_invokeVirtual);
        case REF_newInvokeSpecial:  return clone().changeReferenceKind(REF_invokeSpecial, REF_newInvokeSpecial);
        }
        throw new IllegalArgumentException(this.toString());
    }
    public MemberName asConstructor() {
        switch (getReferenceKind()) {
        case REF_invokeSpecial:     return clone().changeReferenceKind(REF_newInvokeSpecial, REF_invokeSpecial);
        case REF_newInvokeSpecial:  return this;
        }
        throw new IllegalArgumentException(this.toString());
501
    }
502
    /** Create a name for the given reflected constructor.  The resulting name will be in a resolved state. */
503
    @SuppressWarnings("LeakingThisInConstructor")
504
    public MemberName(Constructor<?> ctor) {
505
        ctor.getClass();  // NPE check
506 507
        // fill in vmtarget, vmindex while we have ctor in hand:
        MethodHandleNatives.init(this, ctor);
508 509 510 511
        assert(isResolved() && this.clazz != null);
        this.name = CONSTRUCTOR_NAME;
        if (this.type == null)
            this.type = new Object[] { void.class, ctor.getParameterTypes() };
512
    }
513 514
    /** Create a name for the given reflected field.  The resulting name will be in a resolved state.
     */
515
    public MemberName(Field fld) {
516 517 518 519
        this(fld, false);
    }
    @SuppressWarnings("LeakingThisInConstructor")
    public MemberName(Field fld, boolean makeSetter) {
520
        fld.getClass();  // NPE check
521 522
        // fill in vmtarget, vmindex while we have fld in hand:
        MethodHandleNatives.init(this, fld);
523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
        assert(isResolved() && this.clazz != null);
        this.name = fld.getName();
        this.type = fld.getType();
        assert((REF_putStatic - REF_getStatic) == (REF_putField - REF_getField));
        byte refKind = this.getReferenceKind();
        assert(refKind == (isStatic() ? REF_getStatic : REF_getField));
        if (makeSetter) {
            changeReferenceKind((byte)(refKind + (REF_putStatic - REF_getStatic)), refKind);
        }
    }
    public boolean isGetter() {
        return MethodHandleNatives.refKindIsGetter(getReferenceKind());
    }
    public boolean isSetter() {
        return MethodHandleNatives.refKindIsSetter(getReferenceKind());
    }
    public MemberName asSetter() {
        byte refKind = getReferenceKind();
        assert(MethodHandleNatives.refKindIsGetter(refKind));
        assert((REF_putStatic - REF_getStatic) == (REF_putField - REF_getField));
        byte setterRefKind = (byte)(refKind + (REF_putField - REF_getField));
        return clone().changeReferenceKind(setterRefKind, refKind);
545
    }
546
    /** Create a name for the given class.  The resulting name will be in a resolved state. */
547
    public MemberName(Class<?> type) {
548 549 550
        init(type.getDeclaringClass(), type.getSimpleName(), type,
                flagsMods(IS_TYPE, type.getModifiers(), REF_NONE));
        initResolved(true);
551 552 553 554 555 556 557 558 559 560
    }

    // bare-bones constructor; the JVM will fill it in
    MemberName() { }

    // locally useful cloner
    @Override protected MemberName clone() {
        try {
            return (MemberName) super.clone();
        } catch (CloneNotSupportedException ex) {
561
            throw new InternalError(ex);
562 563 564
        }
     }

565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602
    /** Get the definition of this member name.
     *  This may be in a super-class of the declaring class of this member.
     */
    public MemberName getDefinition() {
        if (!isResolved())  throw new IllegalStateException("must be resolved: "+this);
        if (isType())  return this;
        MemberName res = this.clone();
        res.clazz = null;
        res.type = null;
        res.name = null;
        res.resolution = res;
        res.expandFromVM();
        assert(res.getName().equals(this.getName()));
        return res;
    }

    @Override
    public int hashCode() {
        return Objects.hash(clazz, flags, name, getType());
    }
    @Override
    public boolean equals(Object that) {
        return (that instanceof MemberName && this.equals((MemberName)that));
    }

    /** Decide if two member names have exactly the same symbolic content.
     *  Does not take into account any actual class members, so even if
     *  two member names resolve to the same actual member, they may
     *  be distinct references.
     */
    public boolean equals(MemberName that) {
        if (this == that)  return true;
        if (that == null)  return false;
        return this.clazz == that.clazz
                && this.flags == that.flags
                && Objects.equals(this.name, that.name)
                && Objects.equals(this.getType(), that.getType());
    }
603 604

    // Construction from symbolic parts, for queries:
605
    /** Create a field or type name from the given components:  Declaring class, name, type, reference kind.
606 607 608
     *  The declaring class may be supplied as null if this is to be a bare name and type.
     *  The resulting name will in an unresolved state.
     */
609 610 611
    public MemberName(Class<?> defClass, String name, Class<?> type, byte refKind) {
        init(defClass, name, type, flagsMods(IS_FIELD, 0, refKind));
        initResolved(false);
612
    }
613 614 615 616 617
    /** Create a field or type name from the given components:  Declaring class, name, type.
     *  The declaring class may be supplied as null if this is to be a bare name and type.
     *  The modifier flags default to zero.
     *  The resulting name will in an unresolved state.
     */
618 619 620
    public MemberName(Class<?> defClass, String name, Class<?> type, Void unused) {
        this(defClass, name, type, REF_NONE);
        initResolved(false);
621
    }
622 623 624
    /** Create a method or constructor name from the given components:  Declaring class, name, type, modifiers.
     *  It will be a constructor if and only if the name is {@code "&lt;init&gt;"}.
     *  The declaring class may be supplied as null if this is to be a bare name and type.
625
     *  The last argument is optional, a boolean which requests REF_invokeSpecial.
626 627
     *  The resulting name will in an unresolved state.
     */
628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644
    public MemberName(Class<?> defClass, String name, MethodType type, byte refKind) {
        @SuppressWarnings("LocalVariableHidesMemberVariable")
        int flags = (name != null && name.equals(CONSTRUCTOR_NAME) ? IS_CONSTRUCTOR : IS_METHOD);
        init(defClass, name, type, flagsMods(flags, 0, refKind));
        initResolved(false);
    }
//    /** Create a method or constructor name from the given components:  Declaring class, name, type, modifiers.
//     *  It will be a constructor if and only if the name is {@code "&lt;init&gt;"}.
//     *  The declaring class may be supplied as null if this is to be a bare name and type.
//     *  The modifier flags default to zero.
//     *  The resulting name will in an unresolved state.
//     */
//    public MemberName(Class<?> defClass, String name, MethodType type, Void unused) {
//        this(defClass, name, type, REF_NONE);
//    }

    /** Query whether this member name is resolved to a non-static, non-final method.
645
     */
646 647
    public boolean hasReceiverTypeDispatch() {
        return MethodHandleNatives.refKindDoesDispatch(getReferenceKind());
648 649
    }

650 651 652 653 654 655
    /** Query whether this member name is resolved.
     *  A resolved member name is one for which the JVM has found
     *  a method, constructor, field, or type binding corresponding exactly to the name.
     *  (Document?)
     */
    public boolean isResolved() {
656
        return resolution == null;
657 658
    }

659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684
    private void initResolved(boolean isResolved) {
        assert(this.resolution == null);  // not initialized yet!
        if (!isResolved)
            this.resolution = this;
        assert(isResolved() == isResolved);
    }

    void checkForTypeAlias() {
        if (isInvocable()) {
            MethodType type;
            if (this.type instanceof MethodType)
                type = (MethodType) this.type;
            else
                this.type = type = getMethodType();
            if (type.erase() == type)  return;
            if (VerifyAccess.isTypeVisible(type, clazz))  return;
            throw new LinkageError("bad method type alias: "+type+" not visible from "+clazz);
        } else {
            Class<?> type;
            if (this.type instanceof Class<?>)
                type = (Class<?>) this.type;
            else
                this.type = type = getFieldType();
            if (VerifyAccess.isTypeVisible(type, clazz))  return;
            throw new LinkageError("bad field type alias: "+type+" not visible from "+clazz);
        }
685 686
    }

687

688 689 690 691 692 693 694
    /** Produce a string form of this member name.
     *  For types, it is simply the type's own string (as reported by {@code toString}).
     *  For fields, it is {@code "DeclaringClass.name/type"}.
     *  For methods and constructors, it is {@code "DeclaringClass.name(ptype...)rtype"}.
     *  If the declaring class is null, the prefix {@code "DeclaringClass."} is omitted.
     *  If the member is unresolved, a prefix {@code "*."} is prepended.
     */
695
    @SuppressWarnings("LocalVariableHidesMemberVariable")
696 697 698 699 700 701 702 703 704 705
    @Override
    public String toString() {
        if (isType())
            return type.toString();  // class java.lang.String
        // else it is a field, method, or constructor
        StringBuilder buf = new StringBuilder();
        if (getDeclaringClass() != null) {
            buf.append(getName(clazz));
            buf.append('.');
        }
706 707 708 709 710 711 712 713 714
        String name = getName();
        buf.append(name == null ? "*" : name);
        Object type = getType();
        if (!isInvocable()) {
            buf.append('/');
            buf.append(type == null ? "*" : getName(type));
        } else {
            buf.append(type == null ? "(*)*" : getName(type));
        }
715 716 717 718
        byte refKind = getReferenceKind();
        if (refKind != REF_NONE) {
            buf.append('/');
            buf.append(MethodHandleNatives.refKindName(refKind));
719
        }
720
        //buf.append("#").append(System.identityHashCode(this));
721 722 723 724 725
        return buf.toString();
    }
    private static String getName(Object obj) {
        if (obj instanceof Class<?>)
            return ((Class<?>)obj).getName();
726
        return String.valueOf(obj);
727 728
    }

729 730
    public IllegalAccessException makeAccessException(String message, Object from) {
        message = message + ": "+ toString();
731 732 733
        if (from != null)  message += ", from " + from;
        return new IllegalAccessException(message);
    }
734 735 736 737 738 739 740 741 742 743 744 745
    private String message() {
        if (isResolved())
            return "no access";
        else if (isConstructor())
            return "no such constructor";
        else if (isMethod())
            return "no such method";
        else
            return "no such field";
    }
    public ReflectiveOperationException makeAccessException() {
        String message = message() + ": "+ toString();
746 747 748 749
        ReflectiveOperationException ex;
        if (isResolved() || !(resolution instanceof NoSuchMethodError ||
                              resolution instanceof NoSuchFieldError))
            ex = new IllegalAccessException(message);
750
        else if (isConstructor())
751
            ex = new NoSuchMethodException(message);
752
        else if (isMethod())
753
            ex = new NoSuchMethodException(message);
754
        else
755 756 757 758
            ex = new NoSuchFieldException(message);
        if (resolution instanceof Throwable)
            ex.initCause((Throwable) resolution);
        return ex;
759
    }
760 761

    /** Actually making a query requires an access check. */
762
    /*non-public*/ static Factory getFactory() {
763 764
        return Factory.INSTANCE;
    }
765 766 767
    /** A factory type for resolving member names with the help of the VM.
     *  TBD: Define access-safe public constructors for this factory.
     */
768
    /*non-public*/ static class Factory {
769 770 771
        private Factory() { } // singleton pattern
        static Factory INSTANCE = new Factory();

772
        private static int ALLOWED_FLAGS = ALL_KINDS;
773 774 775 776 777 778 779 780

        /// Queries
        List<MemberName> getMembers(Class<?> defc,
                String matchName, Object matchType,
                int matchFlags, Class<?> lookupClass) {
            matchFlags &= ALLOWED_FLAGS;
            String matchSig = null;
            if (matchType != null) {
781
                matchSig = BytecodeDescriptor.unparse(matchType);
782 783 784 785 786 787 788 789 790 791
                if (matchSig.startsWith("("))
                    matchFlags &= ~(ALL_KINDS & ~IS_INVOCABLE);
                else
                    matchFlags &= ~(ALL_KINDS & ~IS_FIELD);
            }
            final int BUF_MAX = 0x2000;
            int len1 = matchName == null ? 10 : matchType == null ? 4 : 1;
            MemberName[] buf = newMemberBuffer(len1);
            int totalCount = 0;
            ArrayList<MemberName[]> bufs = null;
792
            int bufCount = 0;
793
            for (;;) {
794
                bufCount = MethodHandleNatives.getMembers(defc,
795
                        matchName, matchSig, matchFlags,
796
                        lookupClass,
797 798
                        totalCount, buf);
                if (bufCount <= buf.length) {
799 800
                    if (bufCount < 0)  bufCount = 0;
                    totalCount += bufCount;
801 802
                    break;
                }
803
                // JVM returned to us with an intentional overflow!
804 805
                totalCount += buf.length;
                int excess = bufCount - buf.length;
806
                if (bufs == null)  bufs = new ArrayList<>(1);
807 808 809 810 811 812
                bufs.add(buf);
                int len2 = buf.length;
                len2 = Math.max(len2, excess);
                len2 = Math.max(len2, totalCount / 4);
                buf = newMemberBuffer(Math.min(BUF_MAX, len2));
            }
813
            ArrayList<MemberName> result = new ArrayList<>(totalCount);
814 815 816 817 818
            if (bufs != null) {
                for (MemberName[] buf0 : bufs) {
                    Collections.addAll(result, buf0);
                }
            }
819
            result.addAll(Arrays.asList(buf).subList(0, bufCount));
820 821 822 823 824 825 826 827 828 829 830 831
            // Signature matching is not the same as type matching, since
            // one signature might correspond to several types.
            // So if matchType is a Class or MethodType, refilter the results.
            if (matchType != null && matchType != matchSig) {
                for (Iterator<MemberName> it = result.iterator(); it.hasNext();) {
                    MemberName m = it.next();
                    if (!matchType.equals(m.getType()))
                        it.remove();
                }
            }
            return result;
        }
832 833 834 835 836 837
        /** Produce a resolved version of the given member.
         *  Super types are searched (for inherited members) if {@code searchSupers} is true.
         *  Access checking is performed on behalf of the given {@code lookupClass}.
         *  If lookup fails or access is not permitted, null is returned.
         *  Otherwise a fresh copy of the given member is returned, with modifier bits filled in.
         */
838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854
        private MemberName resolve(byte refKind, MemberName ref, Class<?> lookupClass) {
            MemberName m = ref.clone();  // JVM will side-effect the ref
            assert(refKind == m.getReferenceKind());
            try {
                m = MethodHandleNatives.resolve(m, lookupClass);
                m.checkForTypeAlias();
                m.resolution = null;
            } catch (LinkageError ex) {
                // JVM reports that the "bytecode behavior" would get an error
                assert(!m.isResolved());
                m.resolution = ex;
                return m;
            }
            assert(m.referenceKindIsConsistent());
            m.initResolved(true);
            assert(m.vminfoIsConsistent());
            return m;
855
        }
856 857 858
        /** Produce a resolved version of the given member.
         *  Super types are searched (for inherited members) if {@code searchSupers} is true.
         *  Access checking is performed on behalf of the given {@code lookupClass}.
859
         *  If lookup fails or access is not permitted, a {@linkplain ReflectiveOperationException} is thrown.
860 861
         *  Otherwise a fresh copy of the given member is returned, with modifier bits filled in.
         */
862 863
        public
        <NoSuchMemberException extends ReflectiveOperationException>
864
        MemberName resolveOrFail(byte refKind, MemberName m, Class<?> lookupClass,
865 866
                                 Class<NoSuchMemberException> nsmClass)
                throws IllegalAccessException, NoSuchMemberException {
867 868
            MemberName result = resolve(refKind, m, lookupClass);
            if (result.isResolved())
869
                return result;
870
            ReflectiveOperationException ex = result.makeAccessException();
871 872
            if (ex instanceof IllegalAccessException)  throw (IllegalAccessException) ex;
            throw nsmClass.cast(ex);
873
        }
874 875 876 877 878 879 880 881 882 883 884 885 886
        /** Produce a resolved version of the given member.
         *  Super types are searched (for inherited members) if {@code searchSupers} is true.
         *  Access checking is performed on behalf of the given {@code lookupClass}.
         *  If lookup fails or access is not permitted, return null.
         *  Otherwise a fresh copy of the given member is returned, with modifier bits filled in.
         */
        public
        MemberName resolveOrNull(byte refKind, MemberName m, Class<?> lookupClass) {
            MemberName result = resolve(refKind, m, lookupClass);
            if (result.isResolved())
                return result;
            return null;
        }
887 888 889 890 891
        /** Return a list of all methods defined by the given class.
         *  Super types are searched (for inherited members) if {@code searchSupers} is true.
         *  Access checking is performed on behalf of the given {@code lookupClass}.
         *  Inaccessible members are not added to the last.
         */
892 893 894 895
        public List<MemberName> getMethods(Class<?> defc, boolean searchSupers,
                Class<?> lookupClass) {
            return getMethods(defc, searchSupers, null, null, lookupClass);
        }
896 897 898 899 900 901
        /** Return a list of matching methods defined by the given class.
         *  Super types are searched (for inherited members) if {@code searchSupers} is true.
         *  Returned methods will match the name (if not null) and the type (if not null).
         *  Access checking is performed on behalf of the given {@code lookupClass}.
         *  Inaccessible members are not added to the last.
         */
902 903 904 905 906
        public List<MemberName> getMethods(Class<?> defc, boolean searchSupers,
                String name, MethodType type, Class<?> lookupClass) {
            int matchFlags = IS_METHOD | (searchSupers ? SEARCH_ALL_SUPERS : 0);
            return getMembers(defc, name, type, matchFlags, lookupClass);
        }
907 908 909 910
        /** Return a list of all constructors defined by the given class.
         *  Access checking is performed on behalf of the given {@code lookupClass}.
         *  Inaccessible members are not added to the last.
         */
911 912 913
        public List<MemberName> getConstructors(Class<?> defc, Class<?> lookupClass) {
            return getMembers(defc, null, null, IS_CONSTRUCTOR, lookupClass);
        }
914 915 916 917 918
        /** Return a list of all fields defined by the given class.
         *  Super types are searched (for inherited members) if {@code searchSupers} is true.
         *  Access checking is performed on behalf of the given {@code lookupClass}.
         *  Inaccessible members are not added to the last.
         */
919 920 921 922
        public List<MemberName> getFields(Class<?> defc, boolean searchSupers,
                Class<?> lookupClass) {
            return getFields(defc, searchSupers, null, null, lookupClass);
        }
923 924 925 926 927 928
        /** Return a list of all fields defined by the given class.
         *  Super types are searched (for inherited members) if {@code searchSupers} is true.
         *  Returned fields will match the name (if not null) and the type (if not null).
         *  Access checking is performed on behalf of the given {@code lookupClass}.
         *  Inaccessible members are not added to the last.
         */
929 930 931 932 933
        public List<MemberName> getFields(Class<?> defc, boolean searchSupers,
                String name, Class<?> type, Class<?> lookupClass) {
            int matchFlags = IS_FIELD | (searchSupers ? SEARCH_ALL_SUPERS : 0);
            return getMembers(defc, name, type, matchFlags, lookupClass);
        }
934 935 936 937 938
        /** Return a list of all nested types defined by the given class.
         *  Super types are searched (for inherited members) if {@code searchSupers} is true.
         *  Access checking is performed on behalf of the given {@code lookupClass}.
         *  Inaccessible members are not added to the last.
         */
939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957
        public List<MemberName> getNestedTypes(Class<?> defc, boolean searchSupers,
                Class<?> lookupClass) {
            int matchFlags = IS_TYPE | (searchSupers ? SEARCH_ALL_SUPERS : 0);
            return getMembers(defc, null, null, matchFlags, lookupClass);
        }
        private static MemberName[] newMemberBuffer(int length) {
            MemberName[] buf = new MemberName[length];
            // fill the buffer with dummy structs for the JVM to fill in
            for (int i = 0; i < length; i++)
                buf[i] = new MemberName();
            return buf;
        }
    }

//    static {
//        System.out.println("Hello world!  My methods are:");
//        System.out.println(Factory.INSTANCE.getMethods(MemberName.class, true, null));
//    }
}