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