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