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