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