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