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