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