]> Cypherpunks.ru repositories - gostls13.git/blob - src/go/types/lookup.go
go/types: match Go 1.17 compiler error messages more closely
[gostls13.git] / src / go / types / 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 types
8
9 import (
10         "fmt"
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).
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 //
45 func LookupFieldOrMethod(T Type, addressable bool, pkg *Package, name string) (obj Object, index []int, indirect bool) {
46         // Methods cannot be associated to a named pointer type
47         // (spec: "The type denoted by T is called the receiver base type;
48         // it must not be a pointer or interface type and it must be declared
49         // in the same package as the method.").
50         // Thus, if we have a named pointer type, proceed with the underlying
51         // pointer type but discard the result if it is a method since we would
52         // not have found it for T (see also issue 8590).
53         if t := asNamed(T); t != nil {
54                 if p, _ := safeUnderlying(t).(*Pointer); p != nil {
55                         obj, index, indirect = lookupFieldOrMethod(p, false, pkg, name)
56                         if _, ok := obj.(*Func); ok {
57                                 return nil, nil, false
58                         }
59                         return
60                 }
61         }
62
63         return lookupFieldOrMethod(T, addressable, pkg, name)
64 }
65
66 // TODO(gri) The named type consolidation and seen maps below must be
67 //           indexed by unique keys for a given type. Verify that named
68 //           types always have only one representation (even when imported
69 //           indirectly via different packages.)
70
71 // lookupFieldOrMethod should only be called by LookupFieldOrMethod and missingMethod.
72 func lookupFieldOrMethod(T Type, addressable bool, pkg *Package, name string) (obj Object, index []int, indirect bool) {
73         // WARNING: The code in this function is extremely subtle - do not modify casually!
74
75         if name == "_" {
76                 return // blank fields/methods are never found
77         }
78
79         typ, isPtr := deref(T)
80
81         // *typ where typ is an interface or type parameter has no methods.
82         if isPtr {
83                 // don't look at under(typ) here - was bug (issue #47747)
84                 if _, ok := typ.(*TypeParam); ok {
85                         return
86                 }
87                 if _, ok := under(typ).(*Interface); ok {
88                         return
89                 }
90         }
91
92         // Start with typ as single entry at shallowest depth.
93         current := []embeddedType{{typ, nil, isPtr, false}}
94
95         // Named types that we have seen already, allocated lazily.
96         // Used to avoid endless searches in case of recursive types.
97         // Since only Named types can be used for recursive types, we
98         // only need to track those.
99         // (If we ever allow type aliases to construct recursive types,
100         // we must use type identity rather than pointer equality for
101         // the map key comparison, as we do in consolidateMultiples.)
102         var seen map[*Named]bool
103
104         // search current depth
105         for len(current) > 0 {
106                 var next []embeddedType // embedded types found at current depth
107
108                 // look for (pkg, name) in all types at current depth
109                 var tpar *TypeParam // set if obj receiver is a type parameter
110                 for _, e := range current {
111                         typ := e.typ
112
113                         // If we have a named type, we may have associated methods.
114                         // Look for those first.
115                         if named := asNamed(typ); named != nil {
116                                 if seen[named] {
117                                         // We have seen this type before, at a more shallow depth
118                                         // (note that multiples of this type at the current depth
119                                         // were consolidated before). The type at that depth shadows
120                                         // this same type at the current depth, so we can ignore
121                                         // this one.
122                                         continue
123                                 }
124                                 if seen == nil {
125                                         seen = make(map[*Named]bool)
126                                 }
127                                 seen[named] = true
128
129                                 // look for a matching attached method
130                                 if i, m := lookupMethod(named.methods, pkg, name); m != nil {
131                                         // potential match
132                                         // caution: method may not have a proper signature yet
133                                         index = concat(e.index, i)
134                                         if obj != nil || e.multiples {
135                                                 return nil, index, false // collision
136                                         }
137                                         obj = m
138                                         indirect = e.indirect
139                                         continue // we can't have a matching field or interface method
140                                 }
141
142                                 // continue with underlying type
143                                 typ = named.under()
144                         }
145
146                         tpar = nil
147                         switch t := typ.(type) {
148                         case *Struct:
149                                 // look for a matching field and collect embedded types
150                                 for i, f := range t.fields {
151                                         if f.sameId(pkg, name) {
152                                                 assert(f.typ != nil)
153                                                 index = concat(e.index, i)
154                                                 if obj != nil || e.multiples {
155                                                         return nil, index, false // collision
156                                                 }
157                                                 obj = f
158                                                 indirect = e.indirect
159                                                 continue // we can't have a matching interface method
160                                         }
161                                         // Collect embedded struct fields for searching the next
162                                         // lower depth, but only if we have not seen a match yet
163                                         // (if we have a match it is either the desired field or
164                                         // we have a name collision on the same depth; in either
165                                         // case we don't need to look further).
166                                         // Embedded fields are always of the form T or *T where
167                                         // T is a type name. If e.typ appeared multiple times at
168                                         // this depth, f.typ appears multiple times at the next
169                                         // depth.
170                                         if obj == nil && f.embedded {
171                                                 typ, isPtr := deref(f.typ)
172                                                 // TODO(gri) optimization: ignore types that can't
173                                                 // have fields or methods (only Named, Struct, and
174                                                 // Interface types need to be considered).
175                                                 next = append(next, embeddedType{typ, concat(e.index, i), e.indirect || isPtr, e.multiples})
176                                         }
177                                 }
178
179                         case *Interface:
180                                 // look for a matching method
181                                 if i, m := t.typeSet().LookupMethod(pkg, name); m != nil {
182                                         assert(m.typ != nil)
183                                         index = concat(e.index, i)
184                                         if obj != nil || e.multiples {
185                                                 return nil, index, false // collision
186                                         }
187                                         obj = m
188                                         indirect = e.indirect
189                                 }
190
191                         case *TypeParam:
192                                 if i, m := t.iface().typeSet().LookupMethod(pkg, name); m != nil {
193                                         assert(m.typ != nil)
194                                         index = concat(e.index, i)
195                                         if obj != nil || e.multiples {
196                                                 return nil, index, false // collision
197                                         }
198                                         tpar = t
199                                         obj = m
200                                         indirect = e.indirect
201                                 }
202                         }
203                 }
204
205                 if obj != nil {
206                         // found a potential match
207                         // spec: "A method call x.m() is valid if the method set of (the type of) x
208                         //        contains m and the argument list can be assigned to the parameter
209                         //        list of m. If x is addressable and &x's method set contains m, x.m()
210                         //        is shorthand for (&x).m()".
211                         if f, _ := obj.(*Func); f != nil {
212                                 // determine if method has a pointer receiver
213                                 hasPtrRecv := tpar == nil && f.hasPtrRecv()
214                                 if hasPtrRecv && !indirect && !addressable {
215                                         return nil, nil, true // pointer/addressable receiver required
216                                 }
217                         }
218                         return
219                 }
220
221                 current = consolidateMultiples(next)
222         }
223
224         return nil, nil, false // not found
225 }
226
227 // embeddedType represents an embedded type
228 type embeddedType struct {
229         typ       Type
230         index     []int // embedded field indices, starting with index at depth 0
231         indirect  bool  // if set, there was a pointer indirection on the path to this field
232         multiples bool  // if set, typ appears multiple times at this depth
233 }
234
235 // consolidateMultiples collects multiple list entries with the same type
236 // into a single entry marked as containing multiples. The result is the
237 // consolidated list.
238 func consolidateMultiples(list []embeddedType) []embeddedType {
239         if len(list) <= 1 {
240                 return list // at most one entry - nothing to do
241         }
242
243         n := 0                     // number of entries w/ unique type
244         prev := make(map[Type]int) // index at which type was previously seen
245         for _, e := range list {
246                 if i, found := lookupType(prev, e.typ); found {
247                         list[i].multiples = true
248                         // ignore this entry
249                 } else {
250                         prev[e.typ] = n
251                         list[n] = e
252                         n++
253                 }
254         }
255         return list[:n]
256 }
257
258 func lookupType(m map[Type]int, typ Type) (int, bool) {
259         // fast path: maybe the types are equal
260         if i, found := m[typ]; found {
261                 return i, true
262         }
263
264         for t, i := range m {
265                 if Identical(t, typ) {
266                         return i, true
267                 }
268         }
269
270         return 0, false
271 }
272
273 // MissingMethod returns (nil, false) if V implements T, otherwise it
274 // returns a missing method required by T and whether it is missing or
275 // just has the wrong type.
276 //
277 // For non-interface types V, or if static is set, V implements T if all
278 // methods of T are present in V. Otherwise (V is an interface and static
279 // is not set), MissingMethod only checks that methods of T which are also
280 // present in V have matching types (e.g., for a type assertion x.(T) where
281 // x is of interface type V).
282 //
283 func MissingMethod(V Type, T *Interface, static bool) (method *Func, wrongType bool) {
284         m, typ := (*Checker)(nil).missingMethod(V, T, static)
285         return m, typ != nil
286 }
287
288 // missingMethod is like MissingMethod but accepts a *Checker as
289 // receiver and an addressable flag.
290 // The receiver may be nil if missingMethod is invoked through
291 // an exported API call (such as MissingMethod), i.e., when all
292 // methods have been type-checked.
293 // If the type has the correctly named method, but with the wrong
294 // signature, the existing method is returned as well.
295 // To improve error messages, also report the wrong signature
296 // when the method exists on *V instead of V.
297 func (check *Checker) missingMethod(V Type, T *Interface, static bool) (method, wrongType *Func) {
298         // fast path for common case
299         if T.Empty() {
300                 return
301         }
302
303         if ityp, _ := under(V).(*Interface); ityp != nil {
304                 // TODO(gri) the methods are sorted - could do this more efficiently
305                 for _, m := range T.typeSet().methods {
306                         _, f := ityp.typeSet().LookupMethod(m.pkg, m.name)
307
308                         if f == nil {
309                                 if !static {
310                                         continue
311                                 }
312                                 return m, f
313                         }
314
315                         // both methods must have the same number of type parameters
316                         ftyp := f.typ.(*Signature)
317                         mtyp := m.typ.(*Signature)
318                         if ftyp.TypeParams().Len() != mtyp.TypeParams().Len() {
319                                 return m, f
320                         }
321                         if ftyp.TypeParams().Len() > 0 {
322                                 panic("method with type parameters")
323                         }
324
325                         // If the methods have type parameters we don't care whether they
326                         // are the same or not, as long as they match up. Use unification
327                         // to see if they can be made to match.
328                         // TODO(gri) is this always correct? what about type bounds?
329                         // (Alternative is to rename/subst type parameters and compare.)
330                         u := newUnifier(true)
331                         u.x.init(ftyp.TypeParams().list())
332                         if !u.unify(ftyp, mtyp) {
333                                 return m, f
334                         }
335                 }
336
337                 return
338         }
339
340         // A concrete type implements T if it implements all methods of T.
341         for _, m := range T.typeSet().methods {
342                 // TODO(gri) should this be calling lookupFieldOrMethod instead (and why not)?
343                 obj, _, _ := lookupFieldOrMethod(V, false, m.pkg, m.name)
344
345                 // Check if *V implements this method of T.
346                 if obj == nil {
347                         ptr := NewPointer(V)
348                         obj, _, _ = lookupFieldOrMethod(ptr, false, m.pkg, m.name)
349                         if obj != nil {
350                                 return m, obj.(*Func)
351                         }
352                 }
353
354                 // we must have a method (not a field of matching function type)
355                 f, _ := obj.(*Func)
356                 if f == nil {
357                         return m, nil
358                 }
359
360                 // methods may not have a fully set up signature yet
361                 if check != nil {
362                         check.objDecl(f, nil)
363                 }
364
365                 // both methods must have the same number of type parameters
366                 ftyp := f.typ.(*Signature)
367                 mtyp := m.typ.(*Signature)
368                 if ftyp.TypeParams().Len() != mtyp.TypeParams().Len() {
369                         return m, f
370                 }
371                 if ftyp.TypeParams().Len() > 0 {
372                         panic("method with type parameters")
373                 }
374
375                 // If the methods have type parameters we don't care whether they
376                 // are the same or not, as long as they match up. Use unification
377                 // to see if they can be made to match.
378                 // TODO(gri) is this always correct? what about type bounds?
379                 // (Alternative is to rename/subst type parameters and compare.)
380                 u := newUnifier(true)
381                 u.x.init(ftyp.RecvTypeParams().list())
382                 if !u.unify(ftyp, mtyp) {
383                         return m, f
384                 }
385         }
386
387         return
388 }
389
390 // missingMethodReason returns a string giving the detailed reason for a missing method m,
391 // where m is missing from V, but required by T. It puts the reason in parentheses,
392 // and may include more have/want info after that. If non-nil, wrongType is a relevant
393 // method that matches in some way. It may have the correct name, but wrong type, or
394 // it may have a pointer receiver.
395 func (check *Checker) missingMethodReason(V, T Type, m, wrongType *Func) string {
396         var r string
397         var mname string
398         if compilerErrorMessages {
399                 mname = m.Name() + " method"
400         } else {
401                 mname = "method " + m.Name()
402         }
403         if wrongType != nil {
404                 if Identical(m.typ, wrongType.typ) {
405                         if m.Name() == wrongType.Name() {
406                                 r = fmt.Sprintf("(%s has pointer receiver)", mname)
407                         } else {
408                                 r = fmt.Sprintf("(missing %s)\n\t\thave %s^^%s\n\t\twant %s^^%s",
409                                         mname, wrongType.Name(), wrongType.typ, m.Name(), m.typ)
410                         }
411                 } else {
412                         if compilerErrorMessages {
413                                 r = fmt.Sprintf("(wrong type for %s)\n\t\thave %s^^%s\n\t\twant %s^^%s",
414                                         mname, wrongType.Name(), wrongType.typ, m.Name(), m.typ)
415                         } else {
416                                 r = fmt.Sprintf("(wrong type for %s: have %s, want %s)",
417                                         mname, wrongType.typ, m.typ)
418                         }
419                 }
420                 // This is a hack to print the function type without the leading
421                 // 'func' keyword in the have/want printouts. We could change to have
422                 // an extra formatting option for types2.Type that doesn't print out
423                 // 'func'.
424                 r = strings.Replace(r, "^^func", "", -1)
425         } else if IsInterface(T) {
426                 if isInterfacePtr(V) {
427                         r = fmt.Sprintf("(%s is pointer to interface, not interface)", V)
428                 }
429         } else if isInterfacePtr(T) {
430                 r = fmt.Sprintf("(%s is pointer to interface, not interface)", T)
431         }
432         if r == "" {
433                 r = fmt.Sprintf("(missing %s)", mname)
434         }
435         return r
436 }
437
438 func isInterfacePtr(T Type) bool {
439         p, _ := under(T).(*Pointer)
440         return p != nil && IsInterface(p.base)
441 }
442
443 // assertableTo reports whether a value of type V can be asserted to have type T.
444 // It returns (nil, false) as affirmative answer. Otherwise it returns a missing
445 // method required by V and whether it is missing or just has the wrong type.
446 // The receiver may be nil if assertableTo is invoked through an exported API call
447 // (such as AssertableTo), i.e., when all methods have been type-checked.
448 // If the global constant forceStrict is set, assertions that are known to fail
449 // are not permitted.
450 func (check *Checker) assertableTo(V *Interface, T Type) (method, wrongType *Func) {
451         // no static check is required if T is an interface
452         // spec: "If T is an interface type, x.(T) asserts that the
453         //        dynamic type of x implements the interface T."
454         if IsInterface(T) && !forceStrict {
455                 return
456         }
457         return check.missingMethod(T, V, false)
458 }
459
460 // deref dereferences typ if it is a *Pointer and returns its base and true.
461 // Otherwise it returns (typ, false).
462 func deref(typ Type) (Type, bool) {
463         if p, _ := typ.(*Pointer); p != nil {
464                 return p.base, true
465         }
466         return typ, false
467 }
468
469 // derefStructPtr dereferences typ if it is a (named or unnamed) pointer to a
470 // (named or unnamed) struct and returns its base. Otherwise it returns typ.
471 func derefStructPtr(typ Type) Type {
472         if p, _ := under(typ).(*Pointer); p != nil {
473                 if _, ok := under(p.base).(*Struct); ok {
474                         return p.base
475                 }
476         }
477         return typ
478 }
479
480 // concat returns the result of concatenating list and i.
481 // The result does not share its underlying array with list.
482 func concat(list []int, i int) []int {
483         var t []int
484         t = append(t, list...)
485         return append(t, i)
486 }
487
488 // fieldIndex returns the index for the field with matching package and name, or a value < 0.
489 func fieldIndex(fields []*Var, pkg *Package, name string) int {
490         if name != "_" {
491                 for i, f := range fields {
492                         if f.sameId(pkg, name) {
493                                 return i
494                         }
495                 }
496         }
497         return -1
498 }
499
500 // lookupMethod returns the index of and method with matching package and name, or (-1, nil).
501 func lookupMethod(methods []*Func, pkg *Package, name string) (int, *Func) {
502         if name != "_" {
503                 for i, m := range methods {
504                         if m.sameId(pkg, name) {
505                                 return i, m
506                         }
507                 }
508         }
509         return -1, nil
510 }