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.
14 // Internal use of LookupFieldOrMethod: If the obj result is a method
15 // associated with a concrete (non-interface) type, the method's signature
16 // may not be fully set up. Call Checker.objDecl(obj, nil) before accessing
19 // LookupFieldOrMethod looks up a field or method with given package and name
20 // in T and returns the corresponding *Var or *Func, an index sequence, and a
21 // bool indicating if there were any pointer indirections on the path to the
22 // field or method. If addressable is set, T is the type of an addressable
23 // variable (only matters for method lookups).
25 // The last index entry is the field or method index in the (possibly embedded)
26 // type where the entry was found, either:
28 // 1) the list of declared methods of a named type; or
29 // 2) the list of all methods (method set) of an interface type; or
30 // 3) the list of fields of a struct type.
32 // The earlier index entries are the indices of the embedded struct fields
33 // traversed to get to the found entry, starting at depth 0.
35 // If no entry is found, a nil object is returned. In this case, the returned
36 // index and indirect values have the following meaning:
38 // - If index != nil, the index sequence points to an ambiguous entry
39 // (the same name appeared more than once at the same embedding level).
41 // - If indirect is set, a method with a pointer receiver type was found
42 // but there was no pointer on the path from the actual receiver type to
43 // 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) {
46 // Methods cannot be associated to a named pointer type
47 // (spec: "The type denoted by T is called the receiver base type;
48 // it must not be a pointer or interface type and it must be declared
49 // in the same package as the method.").
50 // Thus, if we have a named pointer type, proceed with the underlying
51 // pointer type but discard the result if it is a method since we would
52 // not have found it for T (see also issue 8590).
53 if t, _ := T.(*Named); t != nil {
54 if p, _ := t.Underlying().(*Pointer); p != nil {
55 obj, index, indirect = lookupFieldOrMethod(p, false, false, pkg, name)
56 if _, ok := obj.(*Func); ok {
57 return nil, nil, false
63 return lookupFieldOrMethod(T, addressable, false, pkg, name)
66 // TODO(gri) The named type consolidation and seen maps below must be
67 // indexed by unique keys for a given type. Verify that named
68 // types always have only one representation (even when imported
69 // indirectly via different packages.)
71 // lookupFieldOrMethod should only be called by LookupFieldOrMethod and missingMethod.
72 // If checkFold is true, the lookup for methods will include looking for any method
73 // which case-folds to the same as 'name' (used for giving helpful error messages).
74 func lookupFieldOrMethod(T Type, addressable, checkFold bool, pkg *Package, name string) (obj Object, index []int, indirect bool) {
75 // WARNING: The code in this function is extremely subtle - do not modify casually!
78 return // blank fields/methods are never found
81 typ, isPtr := deref(T)
83 // *typ where typ is an interface has no methods.
85 if _, ok := under(typ).(*Interface); ok {
90 // Start with typ as single entry at shallowest depth.
91 current := []embeddedType{{typ, nil, isPtr, false}}
93 // Named types that we have seen already, allocated lazily.
94 // Used to avoid endless searches in case of recursive types.
95 // Since only Named types can be used for recursive types, we
96 // only need to track those.
97 // (If we ever allow type aliases to construct recursive types,
98 // we must use type identity rather than pointer equality for
99 // the map key comparison, as we do in consolidateMultiples.)
100 var seen map[*Named]bool
102 // search current depth
103 for len(current) > 0 {
104 var next []embeddedType // embedded types found at current depth
106 // look for (pkg, name) in all types at current depth
107 var tpar *TypeParam // set if obj receiver is a type parameter
108 for _, e := range current {
111 // If we have a named type, we may have associated methods.
112 // Look for those first.
113 if named, _ := typ.(*Named); named != nil {
115 // We have seen this type before, at a more shallow depth
116 // (note that multiples of this type at the current depth
117 // were consolidated before). The type at that depth shadows
118 // this same type at the current depth, so we can ignore
123 seen = make(map[*Named]bool)
127 // look for a matching attached method
129 if i, m := lookupMethodFold(named.methods, pkg, name, checkFold); m != nil {
131 // caution: method may not have a proper signature yet
132 index = concat(e.index, i)
133 if obj != nil || e.multiples {
134 return nil, index, false // collision
137 indirect = e.indirect
138 continue // we can't have a matching field or interface method
141 // continue with underlying type
146 switch t := typ.(type) {
148 // look for a matching field and collect embedded types
149 for i, f := range t.fields {
150 if f.sameId(pkg, name) {
152 index = concat(e.index, i)
153 if obj != nil || e.multiples {
154 return nil, index, false // collision
157 indirect = e.indirect
158 continue // we can't have a matching interface method
160 // Collect embedded struct fields for searching the next
161 // lower depth, but only if we have not seen a match yet
162 // (if we have a match it is either the desired field or
163 // we have a name collision on the same depth; in either
164 // case we don't need to look further).
165 // Embedded fields are always of the form T or *T where
166 // T is a type name. If e.typ appeared multiple times at
167 // this depth, f.typ appears multiple times at the next
169 if obj == nil && f.embedded {
170 typ, isPtr := deref(f.typ)
171 // TODO(gri) optimization: ignore types that can't
172 // have fields or methods (only Named, Struct, and
173 // Interface types need to be considered).
174 next = append(next, embeddedType{typ, concat(e.index, i), e.indirect || isPtr, e.multiples})
179 // look for a matching method
180 if i, m := lookupMethodFold(t.typeSet().methods, pkg, name, checkFold); m != nil {
182 index = concat(e.index, i)
183 if obj != nil || e.multiples {
184 return nil, index, false // collision
187 indirect = e.indirect
191 if i, m := lookupMethodFold(t.iface().typeSet().methods, pkg, name, checkFold); m != nil {
193 index = concat(e.index, i)
194 if obj != nil || e.multiples {
195 return nil, index, false // collision
199 indirect = e.indirect
202 // At this point we're not (yet) looking into methods
203 // that any underlying type of the types in the type list
205 // TODO(gri) Do we want to specify the language that way?
211 // found a potential match
212 // spec: "A method call x.m() is valid if the method set of (the type of) x
213 // contains m and the argument list can be assigned to the parameter
214 // list of m. If x is addressable and &x's method set contains m, x.m()
215 // is shorthand for (&x).m()".
216 if f, _ := obj.(*Func); f != nil {
217 // determine if method has a pointer receiver
218 hasPtrRecv := tpar == nil && f.hasPtrRecv()
219 if hasPtrRecv && !indirect && !addressable {
220 return nil, nil, true // pointer/addressable receiver required
226 current = consolidateMultiples(next)
229 return nil, nil, false // not found
232 // embeddedType represents an embedded type
233 type embeddedType struct {
235 index []int // embedded field indices, starting with index at depth 0
236 indirect bool // if set, there was a pointer indirection on the path to this field
237 multiples bool // if set, typ appears multiple times at this depth
240 // consolidateMultiples collects multiple list entries with the same type
241 // into a single entry marked as containing multiples. The result is the
242 // consolidated list.
243 func consolidateMultiples(list []embeddedType) []embeddedType {
245 return list // at most one entry - nothing to do
248 n := 0 // number of entries w/ unique type
249 prev := make(map[Type]int) // index at which type was previously seen
250 for _, e := range list {
251 if i, found := lookupType(prev, e.typ); found {
252 list[i].multiples = true
263 func lookupType(m map[Type]int, typ Type) (int, bool) {
264 // fast path: maybe the types are equal
265 if i, found := m[typ]; found {
269 for t, i := range m {
270 if Identical(t, typ) {
278 // MissingMethod returns (nil, false) if V implements T, otherwise it
279 // returns a missing method required by T and whether it is missing or
280 // just has the wrong type.
282 // For non-interface types V, or if static is set, V implements T if all
283 // methods of T are present in V. Otherwise (V is an interface and static
284 // is not set), MissingMethod only checks that methods of T which are also
285 // present in V have matching types (e.g., for a type assertion x.(T) where
286 // x is of interface type V).
288 func MissingMethod(V Type, T *Interface, static bool) (method *Func, wrongType bool) {
289 m, typ := (*Checker)(nil).missingMethod(V, T, static)
293 // missingMethod is like MissingMethod but accepts a *Checker as
294 // receiver and an addressable flag.
295 // The receiver may be nil if missingMethod is invoked through
296 // an exported API call (such as MissingMethod), i.e., when all
297 // methods have been type-checked.
298 // If the type has the correctly named method, but with the wrong
299 // signature, the existing method is returned as well.
300 // To improve error messages, also report the wrong signature
301 // when the method exists on *V instead of V.
302 func (check *Checker) missingMethod(V Type, T *Interface, static bool) (method, wrongType *Func) {
303 // fast path for common case
308 if ityp, _ := under(V).(*Interface); ityp != nil {
309 // TODO(gri) the methods are sorted - could do this more efficiently
310 for _, m := range T.typeSet().methods {
311 _, f := ityp.typeSet().LookupMethod(m.pkg, m.name)
317 // We don't do any case-fold check if V is an interface.
321 // both methods must have the same number of type parameters
322 ftyp := f.typ.(*Signature)
323 mtyp := m.typ.(*Signature)
324 if ftyp.TypeParams().Len() != mtyp.TypeParams().Len() {
327 if !acceptMethodTypeParams && ftyp.TypeParams().Len() > 0 {
328 panic("method with type parameters")
331 // If the methods have type parameters we don't care whether they
332 // are the same or not, as long as they match up. Use unification
333 // to see if they can be made to match.
334 // TODO(gri) is this always correct? what about type bounds?
335 // (Alternative is to rename/subst type parameters and compare.)
336 u := newUnifier(true)
337 u.x.init(ftyp.TypeParams().list())
338 if !u.unify(ftyp, mtyp) {
346 // A concrete type implements T if it implements all methods of T.
347 for _, m := range T.typeSet().methods {
348 // TODO(gri) should this be calling LookupFieldOrMethod instead (and why not)?
349 obj, _, _ := lookupFieldOrMethod(V, false, false, m.pkg, m.name)
351 // Check if *V implements this method of T.
354 obj, _, _ = lookupFieldOrMethod(ptr, false, false, m.pkg, m.name)
356 return m, obj.(*Func)
358 // If we didn't find the exact method (even with pointer
359 // receiver), look to see if there is a method that
360 // matches m.name with case-folding.
361 obj, _, _ := lookupFieldOrMethod(V, false, true, m.pkg, m.name)
363 return m, obj.(*Func)
367 // we must have a method (not a field of matching function type)
373 // methods may not have a fully set up signature yet
375 check.objDecl(f, nil)
378 // both methods must have the same number of type parameters
379 ftyp := f.typ.(*Signature)
380 mtyp := m.typ.(*Signature)
381 if ftyp.TypeParams().Len() != mtyp.TypeParams().Len() {
384 if !acceptMethodTypeParams && ftyp.TypeParams().Len() > 0 {
385 panic("method with type parameters")
388 // If the methods have type parameters we don't care whether they
389 // are the same or not, as long as they match up. Use unification
390 // to see if they can be made to match.
391 // TODO(gri) is this always correct? what about type bounds?
392 // (Alternative is to rename/subst type parameters and compare.)
393 u := newUnifier(true)
394 if ftyp.TypeParams().Len() > 0 {
395 // We reach here only if we accept method type parameters.
396 // In this case, unification must consider any receiver
397 // and method type parameters as "free" type parameters.
398 assert(acceptMethodTypeParams)
399 // We don't have a test case for this at the moment since
400 // we can't parse method type parameters. Keeping the
401 // unimplemented call so that we test this code if we
402 // enable method type parameters.
404 u.x.init(append(ftyp.RecvTypeParams().list(), ftyp.TypeParams().list()...))
406 u.x.init(ftyp.RecvTypeParams().list())
408 if !u.unify(ftyp, mtyp) {
416 // missingMethodReason returns a string giving the detailed reason for a missing method m,
417 // where m is missing from V, but required by T. It puts the reason in parentheses,
418 // and may include more have/want info after that. If non-nil, wrongType is a relevant
419 // method that matches in some way. It may have the correct name, but wrong type, or
420 // it may have a pointer receiver, or it may have the correct name except wrong case.
421 func (check *Checker) missingMethodReason(V, T Type, m, wrongType *Func) string {
424 if check.conf.CompilerErrorMessages {
425 mname = m.Name() + " method"
427 mname = "method " + m.Name()
429 if wrongType != nil {
430 if Identical(m.typ, wrongType.typ) {
431 if m.Name() == wrongType.Name() {
432 r = fmt.Sprintf("(%s has pointer receiver)", mname)
434 r = fmt.Sprintf("(missing %s)\n\t\thave %s^^%s\n\t\twant %s^^%s",
435 mname, wrongType.Name(), wrongType.typ, m.Name(), m.typ)
438 if check.conf.CompilerErrorMessages {
439 r = fmt.Sprintf("(wrong type for %s)\n\t\thave %s^^%s\n\t\twant %s^^%s",
440 mname, wrongType.Name(), wrongType.typ, m.Name(), m.typ)
442 r = fmt.Sprintf("(wrong type for %s: have %s, want %s)",
443 mname, wrongType.typ, m.typ)
446 // This is a hack to print the function type without the leading
447 // 'func' keyword in the have/want printouts. We could change to have
448 // an extra formatting option for types2.Type that doesn't print out
450 r = strings.Replace(r, "^^func", "", -1)
451 } else if IsInterface(T) && !isTypeParam(T) {
452 if isInterfacePtr(V) {
453 r = fmt.Sprintf("(%s is pointer to interface, not interface)", V)
455 } else if isInterfacePtr(T) && !isTypeParam(T) {
456 r = fmt.Sprintf("(%s is pointer to interface, not interface)", T)
459 r = fmt.Sprintf("(missing %s)", mname)
464 func isInterfacePtr(T Type) bool {
465 p, _ := under(T).(*Pointer)
466 return p != nil && IsInterface(p.base) && !isTypeParam(p.base)
469 // assertableTo reports whether a value of type V can be asserted to have type T.
470 // It returns (nil, false) as affirmative answer. Otherwise it returns a missing
471 // method required by V and whether it is missing or just has the wrong type.
472 // The receiver may be nil if assertableTo is invoked through an exported API call
473 // (such as AssertableTo), i.e., when all methods have been type-checked.
474 // If the global constant forceStrict is set, assertions that are known to fail
475 // are not permitted.
476 func (check *Checker) assertableTo(V *Interface, T Type) (method, wrongType *Func) {
477 // no static check is required if T is an interface
478 // spec: "If T is an interface type, x.(T) asserts that the
479 // dynamic type of x implements the interface T."
480 if IsInterface(T) && !forceStrict {
483 return check.missingMethod(T, V, false)
486 // deref dereferences typ if it is a *Pointer and returns its base and true.
487 // Otherwise it returns (typ, false).
488 func deref(typ Type) (Type, bool) {
489 if p, _ := typ.(*Pointer); p != nil {
490 // p.base should never be nil, but be conservative
493 panic("pointer with nil base type (possibly due to an invalid cyclic declaration)")
495 return Typ[Invalid], true
502 // derefStructPtr dereferences typ if it is a (named or unnamed) pointer to a
503 // (named or unnamed) struct and returns its base. Otherwise it returns typ.
504 func derefStructPtr(typ Type) Type {
505 if p, _ := under(typ).(*Pointer); p != nil {
506 if _, ok := under(p.base).(*Struct); ok {
513 // concat returns the result of concatenating list and i.
514 // The result does not share its underlying array with list.
515 func concat(list []int, i int) []int {
517 t = append(t, list...)
521 // fieldIndex returns the index for the field with matching package and name, or a value < 0.
522 func fieldIndex(fields []*Var, pkg *Package, name string) int {
524 for i, f := range fields {
525 if f.sameId(pkg, name) {
533 // lookupMethod returns the index of and method with matching package and name, or (-1, nil).
534 func lookupMethod(methods []*Func, pkg *Package, name string) (int, *Func) {
536 for i, m := range methods {
537 if m.sameId(pkg, name) {
545 // lookupMethodFold is like lookupMethod, but if checkFold is true, it matches a method
546 // name if the names are equal with case folding.
547 func lookupMethodFold(methods []*Func, pkg *Package, name string, checkFold bool) (int, *Func) {
549 for i, m := range methods {
550 if m.name != name && !(checkFold && strings.EqualFold(m.name, name)) {
553 // Use m.name, since we've already checked that m.name and
554 // name are equal with folding.
555 if m.sameId(pkg, m.name) {