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