1 // Copyright 2013 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // This file implements various field and method lookup functions.
11 "cmd/compile/internal/syntax"
15 // Internal use of LookupFieldOrMethod: If the obj result is a method
16 // associated with a concrete (non-interface) type, the method's signature
17 // may not be fully set up. Call Checker.objDecl(obj, nil) before accessing
20 // LookupFieldOrMethod looks up a field or method with given package and name
21 // in T and returns the corresponding *Var or *Func, an index sequence, and a
22 // bool indicating if there were any pointer indirections on the path to the
23 // field or method. If addressable is set, T is the type of an addressable
24 // variable (only matters for method lookups). T must not be nil.
26 // The last index entry is the field or method index in the (possibly embedded)
27 // type where the entry was found, either:
29 // 1. the list of declared methods of a named type; or
30 // 2. the list of all methods (method set) of an interface type; or
31 // 3. the list of fields of a struct type.
33 // The earlier index entries are the indices of the embedded struct fields
34 // traversed to get to the found entry, starting at depth 0.
36 // If no entry is found, a nil object is returned. In this case, the returned
37 // index and indirect values have the following meaning:
39 // - If index != nil, the index sequence points to an ambiguous entry
40 // (the same name appeared more than once at the same embedding level).
42 // - If indirect is set, a method with a pointer receiver type was found
43 // but there was no pointer on the path from the actual receiver type to
44 // the method's formal receiver base type, nor was the receiver addressable.
45 func LookupFieldOrMethod(T Type, addressable bool, pkg *Package, name string) (obj Object, index []int, indirect bool) {
47 panic("LookupFieldOrMethod on nil type")
50 // Methods cannot be associated to a named pointer type.
51 // (spec: "The type denoted by T is called the receiver base type;
52 // it must not be a pointer or interface type and it must be declared
53 // in the same package as the method.").
54 // Thus, if we have a named pointer type, proceed with the underlying
55 // pointer type but discard the result if it is a method since we would
56 // not have found it for T (see also go.dev/issue/8590).
57 if t := asNamed(T); t != nil {
58 if p, _ := t.Underlying().(*Pointer); p != nil {
59 obj, index, indirect = lookupFieldOrMethodImpl(p, false, pkg, name, false)
60 if _, ok := obj.(*Func); ok {
61 return nil, nil, false
67 obj, index, indirect = lookupFieldOrMethodImpl(T, addressable, pkg, name, false)
69 // If we didn't find anything and if we have a type parameter with a core type,
70 // see if there is a matching field (but not a method, those need to be declared
71 // explicitly in the constraint). If the constraint is a named pointer type (see
72 // above), we are ok here because only fields are accepted as results.
73 const enableTParamFieldLookup = false // see go.dev/issue/51576
74 if enableTParamFieldLookup && obj == nil && isTypeParam(T) {
75 if t := coreType(T); t != nil {
76 obj, index, indirect = lookupFieldOrMethodImpl(t, addressable, pkg, name, false)
77 if _, ok := obj.(*Var); !ok {
78 obj, index, indirect = nil, nil, false // accept fields (variables) only
85 // lookupFieldOrMethodImpl is the implementation of LookupFieldOrMethod.
86 // Notably, in contrast to LookupFieldOrMethod, it won't find struct fields
87 // in base types of defined (*Named) pointer types T. For instance, given
90 // type T *struct{f int}
92 // lookupFieldOrMethodImpl won't find the field f in the defined (*Named) type T
93 // (methods on T are not permitted in the first place).
95 // Thus, lookupFieldOrMethodImpl should only be called by LookupFieldOrMethod
96 // and missingMethod (the latter doesn't care about struct fields).
98 // If foldCase is true, method names are considered equal if they are equal
101 // The resulting object may not be fully type-checked.
102 func lookupFieldOrMethodImpl(T Type, addressable bool, pkg *Package, name string, foldCase bool) (obj Object, index []int, indirect bool) {
103 // WARNING: The code in this function is extremely subtle - do not modify casually!
106 return // blank fields/methods are never found
109 // Importantly, we must not call under before the call to deref below (nor
110 // does deref call under), as doing so could incorrectly result in finding
111 // methods of the pointer base type when T is a (*Named) pointer type.
112 typ, isPtr := deref(T)
114 // *typ where typ is an interface (incl. a type parameter) has no methods.
116 if _, ok := under(typ).(*Interface); ok {
121 // Start with typ as single entry at shallowest depth.
122 current := []embeddedType{{typ, nil, isPtr, false}}
124 // seen tracks named types that we have seen already, allocated lazily.
125 // Used to avoid endless searches in case of recursive types.
127 // We must use a lookup on identity rather than a simple map[*Named]bool as
128 // instantiated types may be identical but not equal.
129 var seen instanceLookup
131 // search current depth
132 for len(current) > 0 {
133 var next []embeddedType // embedded types found at current depth
135 // look for (pkg, name) in all types at current depth
136 for _, e := range current {
139 // If we have a named type, we may have associated methods.
140 // Look for those first.
141 if named := asNamed(typ); named != nil {
142 if alt := seen.lookup(named); alt != nil {
143 // We have seen this type before, at a more shallow depth
144 // (note that multiples of this type at the current depth
145 // were consolidated before). The type at that depth shadows
146 // this same type at the current depth, so we can ignore
152 // look for a matching attached method
153 if i, m := named.lookupMethod(pkg, name, foldCase); m != nil {
155 // caution: method may not have a proper signature yet
156 index = concat(e.index, i)
157 if obj != nil || e.multiples {
158 return nil, index, false // collision
161 indirect = e.indirect
162 continue // we can't have a matching field or interface method
166 switch t := under(typ).(type) {
168 // look for a matching field and collect embedded types
169 for i, f := range t.fields {
170 if f.sameId(pkg, name) {
172 index = concat(e.index, i)
173 if obj != nil || e.multiples {
174 return nil, index, false // collision
177 indirect = e.indirect
178 continue // we can't have a matching interface method
180 // Collect embedded struct fields for searching the next
181 // lower depth, but only if we have not seen a match yet
182 // (if we have a match it is either the desired field or
183 // we have a name collision on the same depth; in either
184 // case we don't need to look further).
185 // Embedded fields are always of the form T or *T where
186 // T is a type name. If e.typ appeared multiple times at
187 // this depth, f.typ appears multiple times at the next
189 if obj == nil && f.embedded {
190 typ, isPtr := deref(f.typ)
191 // TODO(gri) optimization: ignore types that can't
192 // have fields or methods (only Named, Struct, and
193 // Interface types need to be considered).
194 next = append(next, embeddedType{typ, concat(e.index, i), e.indirect || isPtr, e.multiples})
199 // look for a matching method (interface may be a type parameter)
200 if i, m := t.typeSet().LookupMethod(pkg, name, foldCase); m != nil {
202 index = concat(e.index, i)
203 if obj != nil || e.multiples {
204 return nil, index, false // collision
207 indirect = e.indirect
213 // found a potential match
214 // spec: "A method call x.m() is valid if the method set of (the type of) x
215 // contains m and the argument list can be assigned to the parameter
216 // list of m. If x is addressable and &x's method set contains m, x.m()
217 // is shorthand for (&x).m()".
218 if f, _ := obj.(*Func); f != nil {
219 // determine if method has a pointer receiver
220 if f.hasPtrRecv() && !indirect && !addressable {
221 return nil, nil, true // pointer/addressable receiver required
227 current = consolidateMultiples(next)
230 return nil, nil, false // not found
233 // embeddedType represents an embedded type
234 type embeddedType struct {
236 index []int // embedded field indices, starting with index at depth 0
237 indirect bool // if set, there was a pointer indirection on the path to this field
238 multiples bool // if set, typ appears multiple times at this depth
241 // consolidateMultiples collects multiple list entries with the same type
242 // into a single entry marked as containing multiples. The result is the
243 // consolidated list.
244 func consolidateMultiples(list []embeddedType) []embeddedType {
246 return list // at most one entry - nothing to do
249 n := 0 // number of entries w/ unique type
250 prev := make(map[Type]int) // index at which type was previously seen
251 for _, e := range list {
252 if i, found := lookupType(prev, e.typ); found {
253 list[i].multiples = true
264 func lookupType(m map[Type]int, typ Type) (int, bool) {
265 // fast path: maybe the types are equal
266 if i, found := m[typ]; found {
270 for t, i := range m {
271 if Identical(t, typ) {
279 type instanceLookup struct {
280 // buf is used to avoid allocating the map m in the common case of a small
281 // number of instances.
283 m map[*Named][]*Named
286 func (l *instanceLookup) lookup(inst *Named) *Named {
287 for _, t := range l.buf {
288 if t != nil && Identical(inst, t) {
292 for _, t := range l.m[inst.Origin()] {
293 if Identical(inst, t) {
300 func (l *instanceLookup) add(inst *Named) {
301 for i, t := range l.buf {
308 l.m = make(map[*Named][]*Named)
310 insts := l.m[inst.Origin()]
311 l.m[inst.Origin()] = append(insts, inst)
314 // MissingMethod returns (nil, false) if V implements T, otherwise it
315 // returns a missing method required by T and whether it is missing or
316 // just has the wrong type: either a pointer receiver or wrong signature.
318 // For non-interface types V, or if static is set, V implements T if all
319 // methods of T are present in V. Otherwise (V is an interface and static
320 // is not set), MissingMethod only checks that methods of T which are also
321 // present in V have matching types (e.g., for a type assertion x.(T) where
322 // x is of interface type V).
323 func MissingMethod(V Type, T *Interface, static bool) (method *Func, wrongType bool) {
324 return (*Checker)(nil).missingMethod(V, T, static, Identical, nil)
327 // missingMethod is like MissingMethod but accepts a *Checker as receiver,
328 // a comparator equivalent for type comparison, and a *string for error causes.
329 // The receiver may be nil if missingMethod is invoked through an exported
330 // API call (such as MissingMethod), i.e., when all methods have been type-
332 // The underlying type of T must be an interface; T (rather than its under-
333 // lying type) is used for better error messages (reported through *cause).
334 // The comparator is used to compare signatures.
335 // If a method is missing and cause is not nil, *cause describes the error.
336 func (check *Checker) missingMethod(V, T Type, static bool, equivalent func(x, y Type) bool, cause *string) (method *Func, wrongType bool) {
337 methods := under(T).(*Interface).typeSet().methods // T must be an interface
338 if len(methods) == 0 {
353 var m *Func // method on T we're trying to implement
354 var f *Func // method on V, if found (state is one of ok, wrongName, wrongSig)
356 if u, _ := under(V).(*Interface); u != nil {
358 for _, m = range methods {
359 _, f = tset.LookupMethod(m.pkg, m.name, false)
369 if !equivalent(f.typ, m.typ) {
375 for _, m = range methods {
376 obj, index, indirect := lookupFieldOrMethodImpl(V, false, m.pkg, m.name, false)
378 // check if m is ambiguous, on *V, or on V with case-folding
387 obj, _, _ = lookupFieldOrMethodImpl(V, false, m.pkg, m.name, true /* fold case */)
396 // we must have a method (not a struct field)
403 // methods may not have a fully set up signature yet
405 check.objDecl(f, nil)
408 if !equivalent(f.typ, m.typ) {
421 // This method may be formatted in funcString below, so must have a fully
424 check.objDecl(f, nil)
430 case isInterfacePtr(V):
431 *cause = "(" + check.interfacePtrError(V) + ")"
432 case isInterfacePtr(T):
433 *cause = "(" + check.interfacePtrError(T) + ")"
435 *cause = check.sprintf("(missing method %s)", m.Name())
438 fs, ms := check.funcString(f, false), check.funcString(m, false)
439 *cause = check.sprintf("(missing method %s)\n\t\thave %s\n\t\twant %s",
442 fs, ms := check.funcString(f, false), check.funcString(m, false)
444 // Don't report "want Foo, have Foo".
445 // Add package information to disambiguate (go.dev/issue/54258).
446 fs, ms = check.funcString(f, true), check.funcString(m, true)
448 *cause = check.sprintf("(wrong type for method %s)\n\t\thave %s\n\t\twant %s",
451 *cause = check.sprintf("(ambiguous selector %s.%s)", V, m.Name())
453 *cause = check.sprintf("(method %s has pointer receiver)", m.Name())
455 *cause = check.sprintf("(%s.%s is a field, not a method)", V, m.Name())
461 return m, state == wrongSig || state == ptrRecv
464 func isInterfacePtr(T Type) bool {
465 p, _ := under(T).(*Pointer)
466 return p != nil && IsInterface(p.base)
470 func (check *Checker) interfacePtrError(T Type) string {
471 assert(isInterfacePtr(T))
472 if p, _ := under(T).(*Pointer); isTypeParam(p.base) {
473 return check.sprintf("type %s is pointer to type parameter, not type parameter", T)
475 return check.sprintf("type %s is pointer to interface, not interface", T)
478 // funcString returns a string of the form name + signature for f.
480 func (check *Checker) funcString(f *Func, pkgInfo bool) string {
481 buf := bytes.NewBufferString(f.name)
483 if check != nil && !pkgInfo {
486 w := newTypeWriter(buf, qf)
489 w.signature(f.typ.(*Signature))
493 // assertableTo reports whether a value of type V can be asserted to have type T.
494 // The receiver may be nil if assertableTo is invoked through an exported API call
495 // (such as AssertableTo), i.e., when all methods have been type-checked.
496 // The underlying type of V must be an interface.
497 // If the result is false and cause is not nil, *cause describes the error.
498 // TODO(gri) replace calls to this function with calls to newAssertableTo.
499 func (check *Checker) assertableTo(V, T Type, cause *string) bool {
500 // no static check is required if T is an interface
501 // spec: "If T is an interface type, x.(T) asserts that the
502 // dynamic type of x implements the interface T."
506 // TODO(gri) fix this for generalized interfaces
507 m, _ := check.missingMethod(T, V, false, Identical, cause)
511 // newAssertableTo reports whether a value of type V can be asserted to have type T.
512 // It also implements behavior for interfaces that currently are only permitted
513 // in constraint position (we have not yet defined that behavior in the spec).
514 // The underlying type of V must be an interface.
515 // If the result is false and cause is not nil, *cause is set to the error cause.
516 func (check *Checker) newAssertableTo(pos syntax.Pos, V, T Type, cause *string) bool {
517 // no static check is required if T is an interface
518 // spec: "If T is an interface type, x.(T) asserts that the
519 // dynamic type of x implements the interface T."
523 return check.implements(pos, T, V, false, cause)
526 // deref dereferences typ if it is a *Pointer (but not a *Named type
527 // with an underlying pointer type!) and returns its base and true.
528 // Otherwise it returns (typ, false).
529 func deref(typ Type) (Type, bool) {
530 if p, _ := _Unalias(typ).(*Pointer); p != nil {
531 // p.base should never be nil, but be conservative
534 panic("pointer with nil base type (possibly due to an invalid cyclic declaration)")
536 return Typ[Invalid], true
543 // derefStructPtr dereferences typ if it is a (named or unnamed) pointer to a
544 // (named or unnamed) struct and returns its base. Otherwise it returns typ.
545 func derefStructPtr(typ Type) Type {
546 if p, _ := under(typ).(*Pointer); p != nil {
547 if _, ok := under(p.base).(*Struct); ok {
554 // concat returns the result of concatenating list and i.
555 // The result does not share its underlying array with list.
556 func concat(list []int, i int) []int {
558 t = append(t, list...)
562 // fieldIndex returns the index for the field with matching package and name, or a value < 0.
563 func fieldIndex(fields []*Var, pkg *Package, name string) int {
565 for i, f := range fields {
566 if f.sameId(pkg, name) {
574 // lookupMethod returns the index of and method with matching package and name, or (-1, nil).
575 // If foldCase is true, method names are considered equal if they are equal with case folding.
576 func lookupMethod(methods []*Func, pkg *Package, name string, foldCase bool) (int, *Func) {
578 for i, m := range methods {
579 if (m.name == name || foldCase && strings.EqualFold(m.name, name)) && m.sameId(pkg, m.name) {