1 // Code generated by "go run generator.go"; DO NOT EDIT.
3 // Copyright 2013 The Go Authors. All rights reserved.
4 // Use of this source code is governed by a BSD-style
5 // license that can be found in the LICENSE file.
7 // This file implements various field and method lookup functions.
16 // Internal use of LookupFieldOrMethod: If the obj result is a method
17 // associated with a concrete (non-interface) type, the method's signature
18 // may not be fully set up. Call Checker.objDecl(obj, nil) before accessing
21 // LookupFieldOrMethod looks up a field or method with given package and name
22 // in T and returns the corresponding *Var or *Func, an index sequence, and a
23 // bool indicating if there were any pointer indirections on the path to the
24 // field or method. If addressable is set, T is the type of an addressable
25 // variable (only matters for method lookups). T must not be nil.
27 // The last index entry is the field or method index in the (possibly embedded)
28 // type where the entry was found, either:
30 // 1. the list of declared methods of a named type; or
31 // 2. the list of all methods (method set) of an interface type; or
32 // 3. the list of fields of a struct type.
34 // The earlier index entries are the indices of the embedded struct fields
35 // traversed to get to the found entry, starting at depth 0.
37 // If no entry is found, a nil object is returned. In this case, the returned
38 // index and indirect values have the following meaning:
40 // - If index != nil, the index sequence points to an ambiguous entry
41 // (the same name appeared more than once at the same embedding level).
43 // - If indirect is set, a method with a pointer receiver type was found
44 // but there was no pointer on the path from the actual receiver type to
45 // the method's formal receiver base type, nor was the receiver addressable.
46 func LookupFieldOrMethod(T Type, addressable bool, pkg *Package, name string) (obj Object, index []int, indirect bool) {
48 panic("LookupFieldOrMethod on nil type")
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, _ := T.(*Named); t != nil {
59 if p, _ := t.Underlying().(*Pointer); p != nil {
60 obj, index, indirect = lookupFieldOrMethod(p, false, pkg, name, false)
61 if _, ok := obj.(*Func); ok {
62 return nil, nil, false
68 obj, index, indirect = lookupFieldOrMethod(T, addressable, pkg, name, false)
70 // If we didn't find anything and if we have a type parameter with a core type,
71 // see if there is a matching field (but not a method, those need to be declared
72 // explicitly in the constraint). If the constraint is a named pointer type (see
73 // above), we are ok here because only fields are accepted as results.
74 const enableTParamFieldLookup = false // see issue #51576
75 if enableTParamFieldLookup && obj == nil && isTypeParam(T) {
76 if t := coreType(T); t != nil {
77 obj, index, indirect = lookupFieldOrMethod(t, addressable, pkg, name, false)
78 if _, ok := obj.(*Var); !ok {
79 obj, index, indirect = nil, nil, false // accept fields (variables) only
86 // lookupFieldOrMethod should only be called by LookupFieldOrMethod and missingMethod.
87 // If foldCase is true, the lookup for methods will include looking for any method
88 // which case-folds to the same as 'name' (used for giving helpful error messages).
90 // The resulting object may not be fully type-checked.
91 func lookupFieldOrMethod(T Type, addressable bool, pkg *Package, name string, foldCase bool) (obj Object, index []int, indirect bool) {
92 // WARNING: The code in this function is extremely subtle - do not modify casually!
95 return // blank fields/methods are never found
98 typ, isPtr := deref(T)
100 // *typ where typ is an interface (incl. a type parameter) has no methods.
102 if _, ok := under(typ).(*Interface); ok {
107 // Start with typ as single entry at shallowest depth.
108 current := []embeddedType{{typ, nil, isPtr, false}}
110 // seen tracks named types that we have seen already, allocated lazily.
111 // Used to avoid endless searches in case of recursive types.
113 // We must use a lookup on identity rather than a simple map[*Named]bool as
114 // instantiated types may be identical but not equal.
115 var seen instanceLookup
117 // search current depth
118 for len(current) > 0 {
119 var next []embeddedType // embedded types found at current depth
121 // look for (pkg, name) in all types at current depth
122 for _, e := range current {
125 // If we have a named type, we may have associated methods.
126 // Look for those first.
127 if named, _ := typ.(*Named); named != nil {
128 if alt := seen.lookup(named); alt != nil {
129 // We have seen this type before, at a more shallow depth
130 // (note that multiples of this type at the current depth
131 // were consolidated before). The type at that depth shadows
132 // this same type at the current depth, so we can ignore
138 // look for a matching attached method
139 if i, m := named.lookupMethod(pkg, name, foldCase); m != nil {
141 // caution: method may not have a proper signature yet
142 index = concat(e.index, i)
143 if obj != nil || e.multiples {
144 return nil, index, false // collision
147 indirect = e.indirect
148 continue // we can't have a matching field or interface method
152 switch t := under(typ).(type) {
154 // look for a matching field and collect embedded types
155 for i, f := range t.fields {
156 if f.sameId(pkg, name) {
158 index = concat(e.index, i)
159 if obj != nil || e.multiples {
160 return nil, index, false // collision
163 indirect = e.indirect
164 continue // we can't have a matching interface method
166 // Collect embedded struct fields for searching the next
167 // lower depth, but only if we have not seen a match yet
168 // (if we have a match it is either the desired field or
169 // we have a name collision on the same depth; in either
170 // case we don't need to look further).
171 // Embedded fields are always of the form T or *T where
172 // T is a type name. If e.typ appeared multiple times at
173 // this depth, f.typ appears multiple times at the next
175 if obj == nil && f.embedded {
176 typ, isPtr := deref(f.typ)
177 // TODO(gri) optimization: ignore types that can't
178 // have fields or methods (only Named, Struct, and
179 // Interface types need to be considered).
180 next = append(next, embeddedType{typ, concat(e.index, i), e.indirect || isPtr, e.multiples})
185 // look for a matching method (interface may be a type parameter)
186 if i, m := t.typeSet().LookupMethod(pkg, name, foldCase); m != nil {
188 index = concat(e.index, i)
189 if obj != nil || e.multiples {
190 return nil, index, false // collision
193 indirect = e.indirect
199 // found a potential match
200 // spec: "A method call x.m() is valid if the method set of (the type of) x
201 // contains m and the argument list can be assigned to the parameter
202 // list of m. If x is addressable and &x's method set contains m, x.m()
203 // is shorthand for (&x).m()".
204 if f, _ := obj.(*Func); f != nil {
205 // determine if method has a pointer receiver
206 if f.hasPtrRecv() && !indirect && !addressable {
207 return nil, nil, true // pointer/addressable receiver required
213 current = consolidateMultiples(next)
216 return nil, nil, false // not found
219 // embeddedType represents an embedded type
220 type embeddedType struct {
222 index []int // embedded field indices, starting with index at depth 0
223 indirect bool // if set, there was a pointer indirection on the path to this field
224 multiples bool // if set, typ appears multiple times at this depth
227 // consolidateMultiples collects multiple list entries with the same type
228 // into a single entry marked as containing multiples. The result is the
229 // consolidated list.
230 func consolidateMultiples(list []embeddedType) []embeddedType {
232 return list // at most one entry - nothing to do
235 n := 0 // number of entries w/ unique type
236 prev := make(map[Type]int) // index at which type was previously seen
237 for _, e := range list {
238 if i, found := lookupType(prev, e.typ); found {
239 list[i].multiples = true
250 func lookupType(m map[Type]int, typ Type) (int, bool) {
251 // fast path: maybe the types are equal
252 if i, found := m[typ]; found {
256 for t, i := range m {
257 if Identical(t, typ) {
265 type instanceLookup struct {
266 // buf is used to avoid allocating the map m in the common case of a small
267 // number of instances.
269 m map[*Named][]*Named
272 func (l *instanceLookup) lookup(inst *Named) *Named {
273 for _, t := range l.buf {
274 if t != nil && Identical(inst, t) {
278 for _, t := range l.m[inst.Origin()] {
279 if Identical(inst, t) {
286 func (l *instanceLookup) add(inst *Named) {
287 for i, t := range l.buf {
294 l.m = make(map[*Named][]*Named)
296 insts := l.m[inst.Origin()]
297 l.m[inst.Origin()] = append(insts, inst)
300 // MissingMethod returns (nil, false) if V implements T, otherwise it
301 // returns a missing method required by T and whether it is missing or
302 // just has the wrong type.
304 // For non-interface types V, or if static is set, V implements T if all
305 // methods of T are present in V. Otherwise (V is an interface and static
306 // is not set), MissingMethod only checks that methods of T which are also
307 // present in V have matching types (e.g., for a type assertion x.(T) where
308 // x is of interface type V).
309 func MissingMethod(V Type, T *Interface, static bool) (method *Func, wrongType bool) {
310 m, alt := (*Checker)(nil).missingMethod(V, T, static)
311 // Only report a wrong type if the alternative method has the same name as m.
312 return m, alt != nil && alt.name == m.name // alt != nil implies m != nil
315 // missingMethod is like MissingMethod but accepts a *Checker as receiver.
316 // The receiver may be nil if missingMethod is invoked through an exported
317 // API call (such as MissingMethod), i.e., when all methods have been type-
320 // If a method is missing on T but is found on *T, or if a method is found
321 // on T when looked up with case-folding, this alternative method is returned
322 // as the second result.
323 func (check *Checker) missingMethod(V Type, T *Interface, static bool) (method, alt *Func) {
324 if T.NumMethods() == 0 {
329 if u, _ := under(V).(*Interface); u != nil {
331 for _, m := range T.typeSet().methods {
332 _, f := tset.LookupMethod(m.pkg, m.name, false)
341 if !Identical(f.typ, m.typ) {
349 // V is not an interface
350 for _, m := range T.typeSet().methods {
351 // TODO(gri) should this be calling LookupFieldOrMethod instead (and why not)?
352 obj, _, _ := lookupFieldOrMethod(V, false, m.pkg, m.name, false)
354 // check if m is on *V, or on V with case-folding
357 // TODO(gri) Instead of NewPointer(V) below, can we just set the "addressable" argument?
358 obj, _, _ = lookupFieldOrMethod(NewPointer(V), false, m.pkg, m.name, false)
360 obj, _, _ = lookupFieldOrMethod(V, false, m.pkg, m.name, true /* fold case */)
364 // we must have a method (not a struct field)
370 // methods may not have a fully set up signature yet
372 check.objDecl(f, nil)
375 if !found || !Identical(f.typ, m.typ) {
383 // missingMethodCause returns a string giving the detailed cause for a missing method m,
384 // where m is missing from V, but required by T. It puts the cause in parentheses,
385 // and may include more have/want info after that. If non-nil, alt is a relevant
386 // method that matches in some way. It may have the correct name, but wrong type, or
387 // it may have a pointer receiver, or it may have the correct name except wrong case.
389 func (check *Checker) missingMethodCause(V, T Type, m, alt *Func) string {
390 mname := "method " + m.Name()
393 if m.Name() != alt.Name() {
394 return check.sprintf("(missing %s)\n\t\thave %s\n\t\twant %s",
395 mname, check.funcString(alt, false), check.funcString(m, false))
398 if Identical(m.typ, alt.typ) {
399 return check.sprintf("(%s has pointer receiver)", mname)
402 altS, mS := check.funcString(alt, false), check.funcString(m, false)
404 // Would tell the user that Foo isn't a Foo, add package information to disambiguate. See #54258.
405 altS, mS = check.funcString(alt, true), check.funcString(m, true)
408 return check.sprintf("(wrong type for %s)\n\t\thave %s\n\t\twant %s",
412 if isInterfacePtr(V) {
413 return "(" + check.interfacePtrError(V) + ")"
416 if isInterfacePtr(T) {
417 return "(" + check.interfacePtrError(T) + ")"
420 obj, _, _ := lookupFieldOrMethod(V, true /* auto-deref */, m.pkg, m.name, false)
421 if fld, _ := obj.(*Var); fld != nil {
422 return check.sprintf("(%s.%s is a field, not a method)", V, fld.Name())
425 return check.sprintf("(missing %s)", mname)
428 func isInterfacePtr(T Type) bool {
429 p, _ := under(T).(*Pointer)
430 return p != nil && IsInterface(p.base)
434 func (check *Checker) interfacePtrError(T Type) string {
435 assert(isInterfacePtr(T))
436 if p, _ := under(T).(*Pointer); isTypeParam(p.base) {
437 return check.sprintf("type %s is pointer to type parameter, not type parameter", T)
439 return check.sprintf("type %s is pointer to interface, not interface", T)
442 // funcString returns a string of the form name + signature for f.
444 func (check *Checker) funcString(f *Func, pkgInfo bool) string {
445 buf := bytes.NewBufferString(f.name)
447 if check != nil && !pkgInfo {
450 w := newTypeWriter(buf, qf)
453 w.signature(f.typ.(*Signature))
457 // assertableTo reports whether a value of type V can be asserted to have type T.
458 // It returns (nil, false) as affirmative answer. Otherwise it returns a missing
459 // method required by V and whether it is missing or just has the wrong type.
460 // The receiver may be nil if assertableTo is invoked through an exported API call
461 // (such as AssertableTo), i.e., when all methods have been type-checked.
462 // TODO(gri) replace calls to this function with calls to newAssertableTo.
463 func (check *Checker) assertableTo(V *Interface, T Type) (method, wrongType *Func) {
464 // no static check is required if T is an interface
465 // spec: "If T is an interface type, x.(T) asserts that the
466 // dynamic type of x implements the interface T."
470 // TODO(gri) fix this for generalized interfaces
471 return check.missingMethod(T, V, false)
474 // newAssertableTo reports whether a value of type V can be asserted to have type T.
475 // It also implements behavior for interfaces that currently are only permitted
476 // in constraint position (we have not yet defined that behavior in the spec).
477 func (check *Checker) newAssertableTo(V *Interface, T Type) bool {
478 // no static check is required if T is an interface
479 // spec: "If T is an interface type, x.(T) asserts that the
480 // dynamic type of x implements the interface T."
484 return check.implements(T, V, false, nil)
487 // deref dereferences typ if it is a *Pointer and returns its base and true.
488 // Otherwise it returns (typ, false).
489 func deref(typ Type) (Type, bool) {
490 if p, _ := typ.(*Pointer); p != nil {
491 // p.base should never be nil, but be conservative
494 panic("pointer with nil base type (possibly due to an invalid cyclic declaration)")
496 return Typ[Invalid], true
503 // derefStructPtr dereferences typ if it is a (named or unnamed) pointer to a
504 // (named or unnamed) struct and returns its base. Otherwise it returns typ.
505 func derefStructPtr(typ Type) Type {
506 if p, _ := under(typ).(*Pointer); p != nil {
507 if _, ok := under(p.base).(*Struct); ok {
514 // concat returns the result of concatenating list and i.
515 // The result does not share its underlying array with list.
516 func concat(list []int, i int) []int {
518 t = append(t, list...)
522 // fieldIndex returns the index for the field with matching package and name, or a value < 0.
523 func fieldIndex(fields []*Var, pkg *Package, name string) int {
525 for i, f := range fields {
526 if f.sameId(pkg, name) {
534 // lookupMethod returns the index of and method with matching package and name, or (-1, nil).
535 // If foldCase is true, method names are considered equal if they are equal with case folding.
536 func lookupMethod(methods []*Func, pkg *Package, name string, foldCase bool) (int, *Func) {
538 for i, m := range methods {
539 if (m.name == name || foldCase && strings.EqualFold(m.name, name)) && m.sameId(pkg, m.name) {