]> Cypherpunks.ru repositories - gostls13.git/blob - src/go/types/lookup.go
go/types, types2: better error when method is missing due to ambiguity
[gostls13.git] / src / go / types / lookup.go
1 // Code generated by "go test -run=Generate -write=all"; DO NOT EDIT.
2
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.
6
7 // This file implements various field and method lookup functions.
8
9 package types
10
11 import (
12         "bytes"
13         "strings"
14 )
15
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
19 // the method's type.
20
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.
26 //
27 // The last index entry is the field or method index in the (possibly embedded)
28 // type where the entry was found, either:
29 //
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.
33 //
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.
36 //
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:
39 //
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).
42 //
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) {
47         if T == nil {
48                 panic("LookupFieldOrMethod on nil type")
49         }
50
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 go.dev/issue/8590).
58         if t, _ := T.(*Named); t != nil {
59                 if p, _ := t.Underlying().(*Pointer); p != nil {
60                         obj, index, indirect = lookupFieldOrMethodImpl(p, false, pkg, name, false)
61                         if _, ok := obj.(*Func); ok {
62                                 return nil, nil, false
63                         }
64                         return
65                 }
66         }
67
68         obj, index, indirect = lookupFieldOrMethodImpl(T, addressable, pkg, name, false)
69
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 go.dev/issue/51576
75         if enableTParamFieldLookup && obj == nil && isTypeParam(T) {
76                 if t := coreType(T); t != nil {
77                         obj, index, indirect = lookupFieldOrMethodImpl(t, addressable, pkg, name, false)
78                         if _, ok := obj.(*Var); !ok {
79                                 obj, index, indirect = nil, nil, false // accept fields (variables) only
80                         }
81                 }
82         }
83         return
84 }
85
86 // lookupFieldOrMethodImpl is the implementation of LookupFieldOrMethod.
87 // Notably, in contrast to LookupFieldOrMethod, it won't find struct fields
88 // in base types of defined (*Named) pointer types T. For instance, given
89 // the declaration:
90 //
91 //      type T *struct{f int}
92 //
93 // lookupFieldOrMethodImpl won't find the field f in the defined (*Named) type T
94 // (methods on T are not permitted in the first place).
95 //
96 // Thus, lookupFieldOrMethodImpl should only be called by LookupFieldOrMethod
97 // and missingMethod (the latter doesn't care about struct fields).
98 //
99 // If foldCase is true, method names are considered equal if they are equal
100 // with case folding.
101 //
102 // The resulting object may not be fully type-checked.
103 func lookupFieldOrMethodImpl(T Type, addressable bool, pkg *Package, name string, foldCase bool) (obj Object, index []int, indirect bool) {
104         // WARNING: The code in this function is extremely subtle - do not modify casually!
105
106         if name == "_" {
107                 return // blank fields/methods are never found
108         }
109
110         // Importantly, we must not call under before the call to deref below (nor
111         // does deref call under), as doing so could incorrectly result in finding
112         // methods of the pointer base type when T is a (*Named) pointer type.
113         typ, isPtr := deref(T)
114
115         // *typ where typ is an interface (incl. a type parameter) has no methods.
116         if isPtr {
117                 if _, ok := under(typ).(*Interface); ok {
118                         return
119                 }
120         }
121
122         // Start with typ as single entry at shallowest depth.
123         current := []embeddedType{{typ, nil, isPtr, false}}
124
125         // seen tracks named types that we have seen already, allocated lazily.
126         // Used to avoid endless searches in case of recursive types.
127         //
128         // We must use a lookup on identity rather than a simple map[*Named]bool as
129         // instantiated types may be identical but not equal.
130         var seen instanceLookup
131
132         // search current depth
133         for len(current) > 0 {
134                 var next []embeddedType // embedded types found at current depth
135
136                 // look for (pkg, name) in all types at current depth
137                 for _, e := range current {
138                         typ := e.typ
139
140                         // If we have a named type, we may have associated methods.
141                         // Look for those first.
142                         if named, _ := typ.(*Named); named != nil {
143                                 if alt := seen.lookup(named); alt != nil {
144                                         // We have seen this type before, at a more shallow depth
145                                         // (note that multiples of this type at the current depth
146                                         // were consolidated before). The type at that depth shadows
147                                         // this same type at the current depth, so we can ignore
148                                         // this one.
149                                         continue
150                                 }
151                                 seen.add(named)
152
153                                 // look for a matching attached method
154                                 if i, m := named.lookupMethod(pkg, name, foldCase); m != nil {
155                                         // potential match
156                                         // caution: method may not have a proper signature yet
157                                         index = concat(e.index, i)
158                                         if obj != nil || e.multiples {
159                                                 return nil, index, false // collision
160                                         }
161                                         obj = m
162                                         indirect = e.indirect
163                                         continue // we can't have a matching field or interface method
164                                 }
165                         }
166
167                         switch t := under(typ).(type) {
168                         case *Struct:
169                                 // look for a matching field and collect embedded types
170                                 for i, f := range t.fields {
171                                         if f.sameId(pkg, name) {
172                                                 assert(f.typ != nil)
173                                                 index = concat(e.index, i)
174                                                 if obj != nil || e.multiples {
175                                                         return nil, index, false // collision
176                                                 }
177                                                 obj = f
178                                                 indirect = e.indirect
179                                                 continue // we can't have a matching interface method
180                                         }
181                                         // Collect embedded struct fields for searching the next
182                                         // lower depth, but only if we have not seen a match yet
183                                         // (if we have a match it is either the desired field or
184                                         // we have a name collision on the same depth; in either
185                                         // case we don't need to look further).
186                                         // Embedded fields are always of the form T or *T where
187                                         // T is a type name. If e.typ appeared multiple times at
188                                         // this depth, f.typ appears multiple times at the next
189                                         // depth.
190                                         if obj == nil && f.embedded {
191                                                 typ, isPtr := deref(f.typ)
192                                                 // TODO(gri) optimization: ignore types that can't
193                                                 // have fields or methods (only Named, Struct, and
194                                                 // Interface types need to be considered).
195                                                 next = append(next, embeddedType{typ, concat(e.index, i), e.indirect || isPtr, e.multiples})
196                                         }
197                                 }
198
199                         case *Interface:
200                                 // look for a matching method (interface may be a type parameter)
201                                 if i, m := t.typeSet().LookupMethod(pkg, name, foldCase); m != nil {
202                                         assert(m.typ != nil)
203                                         index = concat(e.index, i)
204                                         if obj != nil || e.multiples {
205                                                 return nil, index, false // collision
206                                         }
207                                         obj = m
208                                         indirect = e.indirect
209                                 }
210                         }
211                 }
212
213                 if obj != nil {
214                         // found a potential match
215                         // spec: "A method call x.m() is valid if the method set of (the type of) x
216                         //        contains m and the argument list can be assigned to the parameter
217                         //        list of m. If x is addressable and &x's method set contains m, x.m()
218                         //        is shorthand for (&x).m()".
219                         if f, _ := obj.(*Func); f != nil {
220                                 // determine if method has a pointer receiver
221                                 if f.hasPtrRecv() && !indirect && !addressable {
222                                         return nil, nil, true // pointer/addressable receiver required
223                                 }
224                         }
225                         return
226                 }
227
228                 current = consolidateMultiples(next)
229         }
230
231         return nil, nil, false // not found
232 }
233
234 // embeddedType represents an embedded type
235 type embeddedType struct {
236         typ       Type
237         index     []int // embedded field indices, starting with index at depth 0
238         indirect  bool  // if set, there was a pointer indirection on the path to this field
239         multiples bool  // if set, typ appears multiple times at this depth
240 }
241
242 // consolidateMultiples collects multiple list entries with the same type
243 // into a single entry marked as containing multiples. The result is the
244 // consolidated list.
245 func consolidateMultiples(list []embeddedType) []embeddedType {
246         if len(list) <= 1 {
247                 return list // at most one entry - nothing to do
248         }
249
250         n := 0                     // number of entries w/ unique type
251         prev := make(map[Type]int) // index at which type was previously seen
252         for _, e := range list {
253                 if i, found := lookupType(prev, e.typ); found {
254                         list[i].multiples = true
255                         // ignore this entry
256                 } else {
257                         prev[e.typ] = n
258                         list[n] = e
259                         n++
260                 }
261         }
262         return list[:n]
263 }
264
265 func lookupType(m map[Type]int, typ Type) (int, bool) {
266         // fast path: maybe the types are equal
267         if i, found := m[typ]; found {
268                 return i, true
269         }
270
271         for t, i := range m {
272                 if Identical(t, typ) {
273                         return i, true
274                 }
275         }
276
277         return 0, false
278 }
279
280 type instanceLookup struct {
281         // buf is used to avoid allocating the map m in the common case of a small
282         // number of instances.
283         buf [3]*Named
284         m   map[*Named][]*Named
285 }
286
287 func (l *instanceLookup) lookup(inst *Named) *Named {
288         for _, t := range l.buf {
289                 if t != nil && Identical(inst, t) {
290                         return t
291                 }
292         }
293         for _, t := range l.m[inst.Origin()] {
294                 if Identical(inst, t) {
295                         return t
296                 }
297         }
298         return nil
299 }
300
301 func (l *instanceLookup) add(inst *Named) {
302         for i, t := range l.buf {
303                 if t == nil {
304                         l.buf[i] = inst
305                         return
306                 }
307         }
308         if l.m == nil {
309                 l.m = make(map[*Named][]*Named)
310         }
311         insts := l.m[inst.Origin()]
312         l.m[inst.Origin()] = append(insts, inst)
313 }
314
315 // MissingMethod returns (nil, false) if V implements T, otherwise it
316 // returns a missing method required by T and whether it is missing or
317 // just has the wrong type: either a pointer receiver or wrong signature.
318 //
319 // For non-interface types V, or if static is set, V implements T if all
320 // methods of T are present in V. Otherwise (V is an interface and static
321 // is not set), MissingMethod only checks that methods of T which are also
322 // present in V have matching types (e.g., for a type assertion x.(T) where
323 // x is of interface type V).
324 func MissingMethod(V Type, T *Interface, static bool) (method *Func, wrongType bool) {
325         return (*Checker)(nil).missingMethod(V, T, static, Identical, nil)
326 }
327
328 // missingMethod is like MissingMethod but accepts a *Checker as receiver,
329 // a comparator equivalent for type comparison, and a *string for error causes.
330 // The receiver may be nil if missingMethod is invoked through an exported
331 // API call (such as MissingMethod), i.e., when all methods have been type-
332 // checked.
333 // The underlying type of T must be an interface; T (rather than its under-
334 // lying type) is used for better error messages (reported through *cause).
335 // The comparator is used to compare signatures.
336 // If a method is missing and cause is not nil, *cause describes the error.
337 func (check *Checker) missingMethod(V, T Type, static bool, equivalent func(x, y Type) bool, cause *string) (method *Func, wrongType bool) {
338         methods := under(T).(*Interface).typeSet().methods // T must be an interface
339         if len(methods) == 0 {
340                 return nil, false
341         }
342
343         const (
344                 ok = iota
345                 notFound
346                 wrongName
347                 wrongSig
348                 ambigSel
349                 ptrRecv
350                 field
351         )
352
353         state := ok
354         var m *Func // method on T we're trying to implement
355         var f *Func // method on V, if found (state is one of ok, wrongName, wrongSig)
356
357         if u, _ := under(V).(*Interface); u != nil {
358                 tset := u.typeSet()
359                 for _, m = range methods {
360                         _, f = tset.LookupMethod(m.pkg, m.name, false)
361
362                         if f == nil {
363                                 if !static {
364                                         continue
365                                 }
366                                 state = notFound
367                                 break
368                         }
369
370                         if !equivalent(f.typ, m.typ) {
371                                 state = wrongSig
372                                 break
373                         }
374                 }
375         } else {
376                 for _, m = range methods {
377                         obj, index, indirect := lookupFieldOrMethodImpl(V, false, m.pkg, m.name, false)
378
379                         // check if m is ambiguous, on *V, or on V with case-folding
380                         if obj == nil {
381                                 switch {
382                                 case index != nil:
383                                         state = ambigSel
384                                 case indirect:
385                                         state = ptrRecv
386                                 default:
387                                         state = notFound
388                                         obj, _, _ = lookupFieldOrMethodImpl(V, false, m.pkg, m.name, true /* fold case */)
389                                         f, _ = obj.(*Func)
390                                         if f != nil {
391                                                 state = wrongName
392                                         }
393                                 }
394                                 break
395                         }
396
397                         // we must have a method (not a struct field)
398                         f, _ = obj.(*Func)
399                         if f == nil {
400                                 state = field
401                                 break
402                         }
403
404                         // methods may not have a fully set up signature yet
405                         if check != nil {
406                                 check.objDecl(f, nil)
407                         }
408
409                         if !equivalent(f.typ, m.typ) {
410                                 state = wrongSig
411                                 break
412                         }
413                 }
414         }
415
416         if state == ok {
417                 return nil, false
418         }
419
420         if cause != nil {
421                 switch state {
422                 case notFound:
423                         switch {
424                         case isInterfacePtr(V):
425                                 *cause = "(" + check.interfacePtrError(V) + ")"
426                         case isInterfacePtr(T):
427                                 *cause = "(" + check.interfacePtrError(T) + ")"
428                         default:
429                                 *cause = check.sprintf("(missing method %s)", m.Name())
430                         }
431                 case wrongName:
432                         fs, ms := check.funcString(f, false), check.funcString(m, false)
433                         *cause = check.sprintf("(missing method %s)\n\t\thave %s\n\t\twant %s",
434                                 m.Name(), fs, ms)
435                 case wrongSig:
436                         fs, ms := check.funcString(f, false), check.funcString(m, false)
437                         if fs == ms {
438                                 // Don't report "want Foo, have Foo".
439                                 // Add package information to disambiguate (go.dev/issue/54258).
440                                 fs, ms = check.funcString(f, true), check.funcString(m, true)
441                         }
442                         *cause = check.sprintf("(wrong type for method %s)\n\t\thave %s\n\t\twant %s",
443                                 m.Name(), fs, ms)
444                 case ambigSel:
445                         *cause = check.sprintf("(ambiguous selector %s.%s)", V, m.Name())
446                 case ptrRecv:
447                         *cause = check.sprintf("(method %s has pointer receiver)", m.Name())
448                 case field:
449                         *cause = check.sprintf("(%s.%s is a field, not a method)", V, m.Name())
450                 default:
451                         unreachable()
452                 }
453         }
454
455         return m, state == wrongSig || state == ptrRecv
456 }
457
458 func isInterfacePtr(T Type) bool {
459         p, _ := under(T).(*Pointer)
460         return p != nil && IsInterface(p.base)
461 }
462
463 // check may be nil.
464 func (check *Checker) interfacePtrError(T Type) string {
465         assert(isInterfacePtr(T))
466         if p, _ := under(T).(*Pointer); isTypeParam(p.base) {
467                 return check.sprintf("type %s is pointer to type parameter, not type parameter", T)
468         }
469         return check.sprintf("type %s is pointer to interface, not interface", T)
470 }
471
472 // funcString returns a string of the form name + signature for f.
473 // check may be nil.
474 func (check *Checker) funcString(f *Func, pkgInfo bool) string {
475         buf := bytes.NewBufferString(f.name)
476         var qf Qualifier
477         if check != nil && !pkgInfo {
478                 qf = check.qualifier
479         }
480         w := newTypeWriter(buf, qf)
481         w.pkgInfo = pkgInfo
482         w.paramNames = false
483         w.signature(f.typ.(*Signature))
484         return buf.String()
485 }
486
487 // assertableTo reports whether a value of type V can be asserted to have type T.
488 // The receiver may be nil if assertableTo is invoked through an exported API call
489 // (such as AssertableTo), i.e., when all methods have been type-checked.
490 // The underlying type of V must be an interface.
491 // If the result is false and cause is not nil, *cause describes the error.
492 // TODO(gri) replace calls to this function with calls to newAssertableTo.
493 func (check *Checker) assertableTo(V, T Type, cause *string) bool {
494         // no static check is required if T is an interface
495         // spec: "If T is an interface type, x.(T) asserts that the
496         //        dynamic type of x implements the interface T."
497         if IsInterface(T) {
498                 return true
499         }
500         // TODO(gri) fix this for generalized interfaces
501         m, _ := check.missingMethod(T, V, false, Identical, cause)
502         return m == nil
503 }
504
505 // newAssertableTo reports whether a value of type V can be asserted to have type T.
506 // It also implements behavior for interfaces that currently are only permitted
507 // in constraint position (we have not yet defined that behavior in the spec).
508 // The underlying type of V must be an interface.
509 // If the result is false and cause is not nil, *cause is set to the error cause.
510 func (check *Checker) newAssertableTo(V, T Type, cause *string) bool {
511         // no static check is required if T is an interface
512         // spec: "If T is an interface type, x.(T) asserts that the
513         //        dynamic type of x implements the interface T."
514         if IsInterface(T) {
515                 return true
516         }
517         return check.implements(T, V, false, cause)
518 }
519
520 // deref dereferences typ if it is a *Pointer (but not a *Named type
521 // with an underlying pointer type!) and returns its base and true.
522 // Otherwise it returns (typ, false).
523 func deref(typ Type) (Type, bool) {
524         if p, _ := typ.(*Pointer); p != nil {
525                 // p.base should never be nil, but be conservative
526                 if p.base == nil {
527                         if debug {
528                                 panic("pointer with nil base type (possibly due to an invalid cyclic declaration)")
529                         }
530                         return Typ[Invalid], true
531                 }
532                 return p.base, true
533         }
534         return typ, false
535 }
536
537 // derefStructPtr dereferences typ if it is a (named or unnamed) pointer to a
538 // (named or unnamed) struct and returns its base. Otherwise it returns typ.
539 func derefStructPtr(typ Type) Type {
540         if p, _ := under(typ).(*Pointer); p != nil {
541                 if _, ok := under(p.base).(*Struct); ok {
542                         return p.base
543                 }
544         }
545         return typ
546 }
547
548 // concat returns the result of concatenating list and i.
549 // The result does not share its underlying array with list.
550 func concat(list []int, i int) []int {
551         var t []int
552         t = append(t, list...)
553         return append(t, i)
554 }
555
556 // fieldIndex returns the index for the field with matching package and name, or a value < 0.
557 func fieldIndex(fields []*Var, pkg *Package, name string) int {
558         if name != "_" {
559                 for i, f := range fields {
560                         if f.sameId(pkg, name) {
561                                 return i
562                         }
563                 }
564         }
565         return -1
566 }
567
568 // lookupMethod returns the index of and method with matching package and name, or (-1, nil).
569 // If foldCase is true, method names are considered equal if they are equal with case folding.
570 func lookupMethod(methods []*Func, pkg *Package, name string, foldCase bool) (int, *Func) {
571         if name != "_" {
572                 for i, m := range methods {
573                         if (m.name == name || foldCase && strings.EqualFold(m.name, name)) && m.sameId(pkg, m.name) {
574                                 return i, m
575                         }
576                 }
577         }
578         return -1, nil
579 }