]> Cypherpunks.ru repositories - gostls13.git/blob - src/go/types/lookup.go
go/types, types2: disentangle convoluted logic for missing method cause
[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 = lookupFieldOrMethod(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 = lookupFieldOrMethod(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 = lookupFieldOrMethod(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 // 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).
89 //
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!
93
94         if name == "_" {
95                 return // blank fields/methods are never found
96         }
97
98         typ, isPtr := deref(T)
99
100         // *typ where typ is an interface (incl. a type parameter) has no methods.
101         if isPtr {
102                 if _, ok := under(typ).(*Interface); ok {
103                         return
104                 }
105         }
106
107         // Start with typ as single entry at shallowest depth.
108         current := []embeddedType{{typ, nil, isPtr, false}}
109
110         // seen tracks named types that we have seen already, allocated lazily.
111         // Used to avoid endless searches in case of recursive types.
112         //
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
116
117         // search current depth
118         for len(current) > 0 {
119                 var next []embeddedType // embedded types found at current depth
120
121                 // look for (pkg, name) in all types at current depth
122                 for _, e := range current {
123                         typ := e.typ
124
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
133                                         // this one.
134                                         continue
135                                 }
136                                 seen.add(named)
137
138                                 // look for a matching attached method
139                                 if i, m := named.lookupMethod(pkg, name, foldCase); m != nil {
140                                         // potential match
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
145                                         }
146                                         obj = m
147                                         indirect = e.indirect
148                                         continue // we can't have a matching field or interface method
149                                 }
150                         }
151
152                         switch t := under(typ).(type) {
153                         case *Struct:
154                                 // look for a matching field and collect embedded types
155                                 for i, f := range t.fields {
156                                         if f.sameId(pkg, name) {
157                                                 assert(f.typ != nil)
158                                                 index = concat(e.index, i)
159                                                 if obj != nil || e.multiples {
160                                                         return nil, index, false // collision
161                                                 }
162                                                 obj = f
163                                                 indirect = e.indirect
164                                                 continue // we can't have a matching interface method
165                                         }
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
174                                         // depth.
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})
181                                         }
182                                 }
183
184                         case *Interface:
185                                 // look for a matching method (interface may be a type parameter)
186                                 if i, m := t.typeSet().LookupMethod(pkg, name, foldCase); m != nil {
187                                         assert(m.typ != nil)
188                                         index = concat(e.index, i)
189                                         if obj != nil || e.multiples {
190                                                 return nil, index, false // collision
191                                         }
192                                         obj = m
193                                         indirect = e.indirect
194                                 }
195                         }
196                 }
197
198                 if obj != nil {
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
208                                 }
209                         }
210                         return
211                 }
212
213                 current = consolidateMultiples(next)
214         }
215
216         return nil, nil, false // not found
217 }
218
219 // embeddedType represents an embedded type
220 type embeddedType struct {
221         typ       Type
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
225 }
226
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 {
231         if len(list) <= 1 {
232                 return list // at most one entry - nothing to do
233         }
234
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
240                         // ignore this entry
241                 } else {
242                         prev[e.typ] = n
243                         list[n] = e
244                         n++
245                 }
246         }
247         return list[:n]
248 }
249
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 {
253                 return i, true
254         }
255
256         for t, i := range m {
257                 if Identical(t, typ) {
258                         return i, true
259                 }
260         }
261
262         return 0, false
263 }
264
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.
268         buf [3]*Named
269         m   map[*Named][]*Named
270 }
271
272 func (l *instanceLookup) lookup(inst *Named) *Named {
273         for _, t := range l.buf {
274                 if t != nil && Identical(inst, t) {
275                         return t
276                 }
277         }
278         for _, t := range l.m[inst.Origin()] {
279                 if Identical(inst, t) {
280                         return t
281                 }
282         }
283         return nil
284 }
285
286 func (l *instanceLookup) add(inst *Named) {
287         for i, t := range l.buf {
288                 if t == nil {
289                         l.buf[i] = inst
290                         return
291                 }
292         }
293         if l.m == nil {
294                 l.m = make(map[*Named][]*Named)
295         }
296         insts := l.m[inst.Origin()]
297         l.m[inst.Origin()] = append(insts, inst)
298 }
299
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: either a pointer receiver or wrong signature.
303 //
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         return (*Checker)(nil).missingMethod(V, T, static, Identical, nil)
311 }
312
313 // missingMethod is like MissingMethod but accepts a *Checker as receiver,
314 // a comparator equivalent for type comparison, and a *string for error causes.
315 // The receiver may be nil if missingMethod is invoked through an exported
316 // API call (such as MissingMethod), i.e., when all methods have been type-
317 // checked.
318 // The underlying type of T must be an interface; T (rather than its under-
319 // lying type) is used for better error messages (reported through *cause).
320 // The comparator is used to compare signatures.
321 // If a method is missing and cause is not nil, *cause describes the error.
322 func (check *Checker) missingMethod(V, T Type, static bool, equivalent func(x, y Type) bool, cause *string) (method *Func, wrongType bool) {
323         methods := under(T).(*Interface).typeSet().methods // T must be an interface
324         if len(methods) == 0 {
325                 return
326         }
327
328         const (
329                 ok = iota
330                 notFound
331                 wrongName
332                 wrongSig
333                 ptrRecv
334                 field
335         )
336
337         state := ok
338         var alt *Func // alternative method, valid if state is wrongName or wrongSig
339
340         if u, _ := under(V).(*Interface); u != nil {
341                 tset := u.typeSet()
342                 for _, m := range methods {
343                         _, f := tset.LookupMethod(m.pkg, m.name, false)
344
345                         if f == nil {
346                                 if !static {
347                                         continue
348                                 }
349                                 state = notFound
350                                 method = m
351                                 break
352                         }
353
354                         if !equivalent(f.typ, m.typ) {
355                                 state = wrongSig
356                                 method, alt = m, f
357                                 break
358                         }
359                 }
360         } else {
361                 for _, m := range methods {
362                         // TODO(gri) should this be calling LookupFieldOrMethod instead (and why not)?
363                         obj, _, _ := lookupFieldOrMethod(V, false, m.pkg, m.name, false)
364
365                         // check if m is on *V, or on V with case-folding
366                         if obj == nil {
367                                 state = notFound
368                                 method = m
369                                 // TODO(gri) Instead of NewPointer(V) below, can we just set the "addressable" argument?
370                                 obj, _, _ = lookupFieldOrMethod(NewPointer(V), false, m.pkg, m.name, false)
371                                 if obj != nil {
372                                         alt, _ = obj.(*Func)
373                                         if alt != nil {
374                                                 state = ptrRecv
375                                         }
376                                         // otherwise we found a field, keep state == notFound
377                                         break
378                                 }
379                                 obj, _, _ = lookupFieldOrMethod(V, false, m.pkg, m.name, true /* fold case */)
380                                 if obj != nil {
381                                         alt, _ = obj.(*Func)
382                                         if alt != nil {
383                                                 state = wrongName
384                                         }
385                                         // otherwise we found a (differently spelled) field, keep state == notFound
386                                 }
387                                 break
388                         }
389
390                         // we must have a method (not a struct field)
391                         f, _ := obj.(*Func)
392                         if f == nil {
393                                 state = field
394                                 method = m
395                                 break
396                         }
397
398                         // methods may not have a fully set up signature yet
399                         if check != nil {
400                                 check.objDecl(f, nil)
401                         }
402
403                         if !equivalent(f.typ, m.typ) {
404                                 state = wrongSig
405                                 method, alt = m, f
406                                 break
407                         }
408                 }
409         }
410
411         if state == ok {
412                 return nil, false
413         }
414
415         if cause != nil {
416                 switch state {
417                 case notFound:
418                         switch {
419                         case isInterfacePtr(V):
420                                 *cause = "(" + check.interfacePtrError(V) + ")"
421                         case isInterfacePtr(T):
422                                 *cause = "(" + check.interfacePtrError(T) + ")"
423                         default:
424                                 *cause = check.sprintf("(missing method %s)", method.Name())
425                         }
426                 case wrongName:
427                         *cause = check.sprintf("(missing method %s)\n\t\thave %s\n\t\twant %s",
428                                 method.Name(), check.funcString(alt, false), check.funcString(method, false))
429                 case wrongSig:
430                         altS, methodS := check.funcString(alt, false), check.funcString(method, false)
431                         if altS == methodS {
432                                 // Would tell the user that Foo isn't a Foo, add package information to disambiguate.
433                                 // See go.dev/issue/54258.
434                                 altS, methodS = check.funcString(alt, true), check.funcString(method, true)
435                         }
436                         *cause = check.sprintf("(wrong type for method %s)\n\t\thave %s\n\t\twant %s",
437                                 method.Name(), altS, methodS)
438                 case ptrRecv:
439                         *cause = check.sprintf("(method %s has pointer receiver)", method.Name())
440                 case field:
441                         *cause = check.sprintf("(%s.%s is a field, not a method)", V, method.Name())
442                 default:
443                         unreachable()
444                 }
445         }
446
447         return method, state == wrongSig || state == ptrRecv
448 }
449
450 func isInterfacePtr(T Type) bool {
451         p, _ := under(T).(*Pointer)
452         return p != nil && IsInterface(p.base)
453 }
454
455 // check may be nil.
456 func (check *Checker) interfacePtrError(T Type) string {
457         assert(isInterfacePtr(T))
458         if p, _ := under(T).(*Pointer); isTypeParam(p.base) {
459                 return check.sprintf("type %s is pointer to type parameter, not type parameter", T)
460         }
461         return check.sprintf("type %s is pointer to interface, not interface", T)
462 }
463
464 // funcString returns a string of the form name + signature for f.
465 // check may be nil.
466 func (check *Checker) funcString(f *Func, pkgInfo bool) string {
467         buf := bytes.NewBufferString(f.name)
468         var qf Qualifier
469         if check != nil && !pkgInfo {
470                 qf = check.qualifier
471         }
472         w := newTypeWriter(buf, qf)
473         w.pkgInfo = pkgInfo
474         w.paramNames = false
475         w.signature(f.typ.(*Signature))
476         return buf.String()
477 }
478
479 // assertableTo reports whether a value of type V can be asserted to have type T.
480 // The receiver may be nil if assertableTo is invoked through an exported API call
481 // (such as AssertableTo), i.e., when all methods have been type-checked.
482 // The underlying type of V must be an interface.
483 // If the result is false and cause is not nil, *cause describes the error.
484 // TODO(gri) replace calls to this function with calls to newAssertableTo.
485 func (check *Checker) assertableTo(V, T Type, cause *string) bool {
486         // no static check is required if T is an interface
487         // spec: "If T is an interface type, x.(T) asserts that the
488         //        dynamic type of x implements the interface T."
489         if IsInterface(T) {
490                 return true
491         }
492         // TODO(gri) fix this for generalized interfaces
493         m, _ := check.missingMethod(T, V, false, Identical, cause)
494         return m == nil
495 }
496
497 // newAssertableTo reports whether a value of type V can be asserted to have type T.
498 // It also implements behavior for interfaces that currently are only permitted
499 // in constraint position (we have not yet defined that behavior in the spec).
500 // The underlying type of V must be an interface.
501 // If the result is false and cause is not nil, *cause is set to the error cause.
502 func (check *Checker) newAssertableTo(V, T Type, cause *string) bool {
503         // no static check is required if T is an interface
504         // spec: "If T is an interface type, x.(T) asserts that the
505         //        dynamic type of x implements the interface T."
506         if IsInterface(T) {
507                 return true
508         }
509         return check.implements(T, V, false, cause)
510 }
511
512 // deref dereferences typ if it is a *Pointer and returns its base and true.
513 // Otherwise it returns (typ, false).
514 func deref(typ Type) (Type, bool) {
515         if p, _ := typ.(*Pointer); p != nil {
516                 // p.base should never be nil, but be conservative
517                 if p.base == nil {
518                         if debug {
519                                 panic("pointer with nil base type (possibly due to an invalid cyclic declaration)")
520                         }
521                         return Typ[Invalid], true
522                 }
523                 return p.base, true
524         }
525         return typ, false
526 }
527
528 // derefStructPtr dereferences typ if it is a (named or unnamed) pointer to a
529 // (named or unnamed) struct and returns its base. Otherwise it returns typ.
530 func derefStructPtr(typ Type) Type {
531         if p, _ := under(typ).(*Pointer); p != nil {
532                 if _, ok := under(p.base).(*Struct); ok {
533                         return p.base
534                 }
535         }
536         return typ
537 }
538
539 // concat returns the result of concatenating list and i.
540 // The result does not share its underlying array with list.
541 func concat(list []int, i int) []int {
542         var t []int
543         t = append(t, list...)
544         return append(t, i)
545 }
546
547 // fieldIndex returns the index for the field with matching package and name, or a value < 0.
548 func fieldIndex(fields []*Var, pkg *Package, name string) int {
549         if name != "_" {
550                 for i, f := range fields {
551                         if f.sameId(pkg, name) {
552                                 return i
553                         }
554                 }
555         }
556         return -1
557 }
558
559 // lookupMethod returns the index of and method with matching package and name, or (-1, nil).
560 // If foldCase is true, method names are considered equal if they are equal with case folding.
561 func lookupMethod(methods []*Func, pkg *Package, name string, foldCase bool) (int, *Func) {
562         if name != "_" {
563                 for i, m := range methods {
564                         if (m.name == name || foldCase && strings.EqualFold(m.name, name)) && m.sameId(pkg, m.name) {
565                                 return i, m
566                         }
567                 }
568         }
569         return -1, nil
570 }