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 // LookupFieldOrMethod looks up a field or method with given package and name
12 // in T and returns the corresponding *Var or *Func, an index sequence, and a
13 // bool indicating if there were any pointer indirections on the path to the
14 // field or method. If addressable is set, T is the type of an addressable
15 // variable (only matters for method lookups).
17 // The last index entry is the field or method index in the (possibly embedded)
18 // type where the entry was found, either:
20 // 1) the list of declared methods of a named type; or
21 // 2) the list of all methods (method set) of an interface type; or
22 // 3) the list of fields of a struct type.
24 // The earlier index entries are the indices of the embedded struct fields
25 // traversed to get to the found entry, starting at depth 0.
27 // If no entry is found, a nil object is returned. In this case, the returned
28 // index and indirect values have the following meaning:
30 // - If index != nil, the index sequence points to an ambiguous entry
31 // (the same name appeared more than once at the same embedding level).
33 // - If indirect is set, a method with a pointer receiver type was found
34 // but there was no pointer on the path from the actual receiver type to
35 // the method's formal receiver base type, nor was the receiver addressable.
37 func LookupFieldOrMethod(T Type, addressable bool, pkg *Package, name string) (obj Object, index []int, indirect bool) {
38 return (*Checker)(nil).lookupFieldOrMethod(T, addressable, pkg, name)
41 // Internal use of Checker.lookupFieldOrMethod: If the obj result is a method
42 // associated with a concrete (non-interface) type, the method's signature
43 // may not be fully set up. Call Checker.objDecl(obj, nil) before accessing
45 // TODO(gri) Now that we provide the *Checker, we can probably remove this
46 // caveat by calling Checker.objDecl from lookupFieldOrMethod. Investigate.
48 // lookupFieldOrMethod is like the external version but completes interfaces
50 func (check *Checker) lookupFieldOrMethod(T Type, addressable bool, pkg *Package, name string) (obj Object, index []int, indirect bool) {
51 // Methods cannot be associated to a named pointer type
52 // (spec: "The type denoted by T is called the receiver base type;
53 // it must not be a pointer or interface type and it must be declared
54 // in the same package as the method.").
55 // Thus, if we have a named pointer type, proceed with the underlying
56 // pointer type but discard the result if it is a method since we would
57 // not have found it for T (see also issue 8590).
58 if t := asNamed(T); t != nil {
59 if p, _ := t.Underlying().(*Pointer); p != nil {
60 obj, index, indirect = check.rawLookupFieldOrMethod(p, false, pkg, name)
61 if _, ok := obj.(*Func); ok {
62 return nil, nil, false
68 return check.rawLookupFieldOrMethod(T, addressable, pkg, name)
71 // TODO(gri) The named type consolidation and seen maps below must be
72 // indexed by unique keys for a given type. Verify that named
73 // types always have only one representation (even when imported
74 // indirectly via different packages.)
76 // rawLookupFieldOrMethod should only be called by lookupFieldOrMethod and missingMethod.
77 func (check *Checker) rawLookupFieldOrMethod(T Type, addressable bool, pkg *Package, name string) (obj Object, index []int, indirect bool) {
78 // WARNING: The code in this function is extremely subtle - do not modify casually!
79 // This function and NewMethodSet should be kept in sync.
82 return // blank fields/methods are never found
85 typ, isPtr := deref(T)
87 // *typ where typ is an interface has no methods.
88 // Be cautious: typ may be nil (issue 39634, crash #3).
89 if typ == nil || isPtr && IsInterface(typ) {
93 // Start with typ as single entry at shallowest depth.
94 current := []embeddedType{{typ, nil, isPtr, false}}
96 // Named types that we have seen already, allocated lazily.
97 // Used to avoid endless searches in case of recursive types.
98 // Since only Named types can be used for recursive types, we
99 // only need to track those.
100 // (If we ever allow type aliases to construct recursive types,
101 // we must use type identity rather than pointer equality for
102 // the map key comparison, as we do in consolidateMultiples.)
103 var seen map[*Named]bool
105 // search current depth
106 for len(current) > 0 {
107 var next []embeddedType // embedded types found at current depth
109 // look for (pkg, name) in all types at current depth
110 var tpar *_TypeParam // set if obj receiver is a type parameter
111 for _, e := range current {
114 // If we have a named type, we may have associated methods.
115 // Look for those first.
116 if named := asNamed(typ); named != nil {
118 // We have seen this type before, at a more shallow depth
119 // (note that multiples of this type at the current depth
120 // were consolidated before). The type at that depth shadows
121 // this same type at the current depth, so we can ignore
126 seen = make(map[*Named]bool)
130 // look for a matching attached method
132 if i, m := lookupMethod(named.methods, pkg, name); m != nil {
134 // caution: method may not have a proper signature yet
135 index = concat(e.index, i)
136 if obj != nil || e.multiples {
137 return nil, index, false // collision
140 indirect = e.indirect
141 continue // we can't have a matching field or interface method
144 // continue with underlying type, but only if it's not a type parameter
145 // TODO(gri) is this what we want to do for type parameters? (spec question)
146 // TODO(#45639) the error message produced as a result of skipping an
147 // underlying type parameter should be improved.
149 if asTypeParam(typ) != nil {
155 switch t := typ.(type) {
157 // look for a matching field and collect embedded types
158 for i, f := range t.fields {
159 if f.sameId(pkg, name) {
161 index = concat(e.index, i)
162 if obj != nil || e.multiples {
163 return nil, index, false // collision
166 indirect = e.indirect
167 continue // we can't have a matching interface method
169 // Collect embedded struct fields for searching the next
170 // lower depth, but only if we have not seen a match yet
171 // (if we have a match it is either the desired field or
172 // we have a name collision on the same depth; in either
173 // case we don't need to look further).
174 // Embedded fields are always of the form T or *T where
175 // T is a type name. If e.typ appeared multiple times at
176 // this depth, f.typ appears multiple times at the next
178 if obj == nil && f.embedded {
179 typ, isPtr := deref(f.typ)
180 // TODO(gri) optimization: ignore types that can't
181 // have fields or methods (only Named, Struct, and
182 // Interface types need to be considered).
183 next = append(next, embeddedType{typ, concat(e.index, i), e.indirect || isPtr, e.multiples})
188 // look for a matching method
189 // TODO(gri) t.allMethods is sorted - use binary search
190 check.completeInterface(token.NoPos, t)
191 if i, m := lookupMethod(t.allMethods, pkg, name); m != nil {
193 index = concat(e.index, i)
194 if obj != nil || e.multiples {
195 return nil, index, false // collision
198 indirect = e.indirect
202 // only consider explicit methods in the type parameter bound, not
203 // methods that may be common to all types in the type list.
204 if i, m := lookupMethod(t.Bound().allMethods, pkg, name); m != nil {
206 index = concat(e.index, i)
207 if obj != nil || e.multiples {
208 return nil, index, false // collision
212 indirect = e.indirect
218 // found a potential match
219 // spec: "A method call x.m() is valid if the method set of (the type of) x
220 // contains m and the argument list can be assigned to the parameter
221 // list of m. If x is addressable and &x's method set contains m, x.m()
222 // is shorthand for (&x).m()".
223 if f, _ := obj.(*Func); f != nil {
224 // determine if method has a pointer receiver
225 hasPtrRecv := tpar == nil && ptrRecv(f)
226 if hasPtrRecv && !indirect && !addressable {
227 return nil, nil, true // pointer/addressable receiver required
233 current = check.consolidateMultiples(next)
236 return nil, nil, false // not found
239 // embeddedType represents an embedded type
240 type embeddedType struct {
242 index []int // embedded field indices, starting with index at depth 0
243 indirect bool // if set, there was a pointer indirection on the path to this field
244 multiples bool // if set, typ appears multiple times at this depth
247 // consolidateMultiples collects multiple list entries with the same type
248 // into a single entry marked as containing multiples. The result is the
249 // consolidated list.
250 func (check *Checker) consolidateMultiples(list []embeddedType) []embeddedType {
252 return list // at most one entry - nothing to do
255 n := 0 // number of entries w/ unique type
256 prev := make(map[Type]int) // index at which type was previously seen
257 for _, e := range list {
258 if i, found := check.lookupType(prev, e.typ); found {
259 list[i].multiples = true
270 func (check *Checker) lookupType(m map[Type]int, typ Type) (int, bool) {
271 // fast path: maybe the types are equal
272 if i, found := m[typ]; found {
276 for t, i := range m {
277 if check.identical(t, typ) {
285 // MissingMethod returns (nil, false) if V implements T, otherwise it
286 // returns a missing method required by T and whether it is missing or
287 // just has the wrong type.
289 // For non-interface types V, or if static is set, V implements T if all
290 // methods of T are present in V. Otherwise (V is an interface and static
291 // is not set), MissingMethod only checks that methods of T which are also
292 // present in V have matching types (e.g., for a type assertion x.(T) where
293 // x is of interface type V).
295 func MissingMethod(V Type, T *Interface, static bool) (method *Func, wrongType bool) {
296 m, typ := (*Checker)(nil).missingMethod(V, T, static)
300 // missingMethod is like MissingMethod but accepts a *Checker as
301 // receiver and an addressable flag.
302 // The receiver may be nil if missingMethod is invoked through
303 // an exported API call (such as MissingMethod), i.e., when all
304 // methods have been type-checked.
305 // If the type has the correctly named method, but with the wrong
306 // signature, the existing method is returned as well.
307 // To improve error messages, also report the wrong signature
308 // when the method exists on *V instead of V.
309 func (check *Checker) missingMethod(V Type, T *Interface, static bool) (method, wrongType *Func) {
310 check.completeInterface(token.NoPos, T)
312 // fast path for common case
317 if ityp := asInterface(V); ityp != nil {
318 check.completeInterface(token.NoPos, ityp)
319 // TODO(gri) allMethods is sorted - can do this more efficiently
320 for _, m := range T.allMethods {
321 _, f := lookupMethod(ityp.allMethods, m.pkg, m.name)
324 // if m is the magic method == we're ok (interfaces are comparable)
325 if m.name == "==" || !static {
331 // both methods must have the same number of type parameters
332 ftyp := f.typ.(*Signature)
333 mtyp := m.typ.(*Signature)
334 if len(ftyp.tparams) != len(mtyp.tparams) {
337 if len(ftyp.tparams) > 0 {
338 panic("internal error: method with type parameters")
341 // If the methods have type parameters we don't care whether they
342 // are the same or not, as long as they match up. Use unification
343 // to see if they can be made to match.
344 // TODO(gri) is this always correct? what about type bounds?
345 // (Alternative is to rename/subst type parameters and compare.)
346 u := newUnifier(check, true)
347 u.x.init(ftyp.tparams)
348 if !u.unify(ftyp, mtyp) {
356 // A concrete type implements T if it implements all methods of T.
359 for _, m := range T.allMethods {
360 // TODO(gri) should this be calling lookupFieldOrMethod instead (and why not)?
361 obj, _, _ := check.rawLookupFieldOrMethod(V, false, m.pkg, m.name)
363 // Check if *V implements this method of T.
366 obj, _, _ = check.rawLookupFieldOrMethod(ptr, false, m.pkg, m.name)
368 return m, obj.(*Func)
372 // we must have a method (not a field of matching function type)
375 // if m is the magic method == and V is comparable, we're ok
376 if m.name == "==" && Comparable(V) {
382 // methods may not have a fully set up signature yet
384 check.objDecl(f, nil)
387 // both methods must have the same number of type parameters
388 ftyp := f.typ.(*Signature)
389 mtyp := m.typ.(*Signature)
390 if len(ftyp.tparams) != len(mtyp.tparams) {
393 if len(ftyp.tparams) > 0 {
394 panic("internal error: method with type parameters")
397 // If V is a (instantiated) generic type, its methods are still
398 // parameterized using the original (declaration) receiver type
399 // parameters (subst simply copies the existing method list, it
400 // does not instantiate the methods).
401 // In order to compare the signatures, substitute the receiver
402 // type parameters of ftyp with V's instantiation type arguments.
403 // This lazily instantiates the signature of method f.
404 if Vn != nil && len(Vn.TParams()) > 0 {
405 // Be careful: The number of type arguments may not match
406 // the number of receiver parameters. If so, an error was
407 // reported earlier but the length discrepancy is still
408 // here. Exit early in this case to prevent an assertion
409 // failure in makeSubstMap.
410 // TODO(gri) Can we avoid this check by fixing the lengths?
411 if len(ftyp.rparams) != len(Vn.targs) {
414 ftyp = check.subst(token.NoPos, ftyp, makeSubstMap(ftyp.rparams, Vn.targs)).(*Signature)
417 // If the methods have type parameters we don't care whether they
418 // are the same or not, as long as they match up. Use unification
419 // to see if they can be made to match.
420 // TODO(gri) is this always correct? what about type bounds?
421 // (Alternative is to rename/subst type parameters and compare.)
422 u := newUnifier(check, true)
423 u.x.init(ftyp.rparams)
424 if !u.unify(ftyp, mtyp) {
432 // assertableTo reports whether a value of type V can be asserted to have type T.
433 // It returns (nil, false) as affirmative answer. Otherwise it returns a missing
434 // method required by V and whether it is missing or just has the wrong type.
435 // The receiver may be nil if assertableTo is invoked through an exported API call
436 // (such as AssertableTo), i.e., when all methods have been type-checked.
437 // If the global constant forceStrict is set, assertions that are known to fail
438 // are not permitted.
439 func (check *Checker) assertableTo(V *Interface, T Type) (method, wrongType *Func) {
440 // no static check is required if T is an interface
441 // spec: "If T is an interface type, x.(T) asserts that the
442 // dynamic type of x implements the interface T."
443 if asInterface(T) != nil && !forceStrict {
446 return check.missingMethod(T, V, false)
449 // deref dereferences typ if it is a *Pointer and returns its base and true.
450 // Otherwise it returns (typ, false).
451 func deref(typ Type) (Type, bool) {
452 if p, _ := typ.(*Pointer); p != nil {
458 // derefStructPtr dereferences typ if it is a (named or unnamed) pointer to a
459 // (named or unnamed) struct and returns its base. Otherwise it returns typ.
460 func derefStructPtr(typ Type) Type {
461 if p := asPointer(typ); p != nil {
462 if asStruct(p.base) != nil {
469 // concat returns the result of concatenating list and i.
470 // The result does not share its underlying array with list.
471 func concat(list []int, i int) []int {
473 t = append(t, list...)
477 // fieldIndex returns the index for the field with matching package and name, or a value < 0.
478 func fieldIndex(fields []*Var, pkg *Package, name string) int {
480 for i, f := range fields {
481 if f.sameId(pkg, name) {
489 // lookupMethod returns the index of and method with matching package and name, or (-1, nil).
490 func lookupMethod(methods []*Func, pkg *Package, name string) (int, *Func) {
492 for i, m := range methods {
493 if m.sameId(pkg, name) {