]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/compile/internal/types2/lookup.go
cmd/compile/internal/types2: clean up asT converters (step 1 of 2)
[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, _ := safeUnderlying(t).(*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         if isPtr {
78                 // don't look at under(typ) here - was bug (issue #47747)
79                 if _, ok := typ.(*TypeParam); ok {
80                         return
81                 }
82                 if _, ok := under(typ).(*Interface); ok {
83                         return
84                 }
85         }
86
87         // Start with typ as single entry at shallowest depth.
88         current := []embeddedType{{typ, nil, isPtr, false}}
89
90         // Named types that we have seen already, allocated lazily.
91         // Used to avoid endless searches in case of recursive types.
92         // Since only Named types can be used for recursive types, we
93         // only need to track those.
94         // (If we ever allow type aliases to construct recursive types,
95         // we must use type identity rather than pointer equality for
96         // the map key comparison, as we do in consolidateMultiples.)
97         var seen map[*Named]bool
98
99         // search current depth
100         for len(current) > 0 {
101                 var next []embeddedType // embedded types found at current depth
102
103                 // look for (pkg, name) in all types at current depth
104                 var tpar *TypeParam // set if obj receiver is a type parameter
105                 for _, e := range current {
106                         typ := e.typ
107
108                         // If we have a named type, we may have associated methods.
109                         // Look for those first.
110                         if named := asNamed(typ); named != nil {
111                                 if seen[named] {
112                                         // We have seen this type before, at a more shallow depth
113                                         // (note that multiples of this type at the current depth
114                                         // were consolidated before). The type at that depth shadows
115                                         // this same type at the current depth, so we can ignore
116                                         // this one.
117                                         continue
118                                 }
119                                 if seen == nil {
120                                         seen = make(map[*Named]bool)
121                                 }
122                                 seen[named] = true
123
124                                 // look for a matching attached method
125                                 named.resolve(nil)
126                                 if i, m := lookupMethod(named.methods, pkg, name); m != nil {
127                                         // potential match
128                                         // caution: method may not have a proper signature yet
129                                         index = concat(e.index, i)
130                                         if obj != nil || e.multiples {
131                                                 return nil, index, false // collision
132                                         }
133                                         obj = m
134                                         indirect = e.indirect
135                                         continue // we can't have a matching field or interface method
136                                 }
137
138                                 // continue with underlying type, but only if it's not a type parameter
139                                 // TODO(gri) is this what we want to do for type parameters? (spec question)
140                                 typ = named.under()
141                                 if asTypeParam(typ) != nil {
142                                         continue
143                                 }
144                         }
145
146                         tpar = nil
147                         switch t := typ.(type) {
148                         case *Struct:
149                                 // look for a matching field and collect embedded types
150                                 for i, f := range t.fields {
151                                         if f.sameId(pkg, name) {
152                                                 assert(f.typ != nil)
153                                                 index = concat(e.index, i)
154                                                 if obj != nil || e.multiples {
155                                                         return nil, index, false // collision
156                                                 }
157                                                 obj = f
158                                                 indirect = e.indirect
159                                                 continue // we can't have a matching interface method
160                                         }
161                                         // Collect embedded struct fields for searching the next
162                                         // lower depth, but only if we have not seen a match yet
163                                         // (if we have a match it is either the desired field or
164                                         // we have a name collision on the same depth; in either
165                                         // case we don't need to look further).
166                                         // Embedded fields are always of the form T or *T where
167                                         // T is a type name. If e.typ appeared multiple times at
168                                         // this depth, f.typ appears multiple times at the next
169                                         // depth.
170                                         if obj == nil && f.embedded {
171                                                 typ, isPtr := deref(f.typ)
172                                                 // TODO(gri) optimization: ignore types that can't
173                                                 // have fields or methods (only Named, Struct, and
174                                                 // Interface types need to be considered).
175                                                 next = append(next, embeddedType{typ, concat(e.index, i), e.indirect || isPtr, e.multiples})
176                                         }
177                                 }
178
179                         case *Interface:
180                                 // look for a matching method
181                                 if i, m := t.typeSet().LookupMethod(pkg, name); m != nil {
182                                         assert(m.typ != nil)
183                                         index = concat(e.index, i)
184                                         if obj != nil || e.multiples {
185                                                 return nil, index, false // collision
186                                         }
187                                         obj = m
188                                         indirect = e.indirect
189                                 }
190
191                         case *TypeParam:
192                                 if i, m := t.iface().typeSet().LookupMethod(pkg, name); m != nil {
193                                         assert(m.typ != nil)
194                                         index = concat(e.index, i)
195                                         if obj != nil || e.multiples {
196                                                 return nil, index, false // collision
197                                         }
198                                         tpar = t
199                                         obj = m
200                                         indirect = e.indirect
201                                 }
202                                 if obj == nil {
203                                         // At this point we're not (yet) looking into methods
204                                         // that any underlying type of the types in the type list
205                                         // might have.
206                                         // TODO(gri) Do we want to specify the language that way?
207                                 }
208                         }
209                 }
210
211                 if obj != nil {
212                         // found a potential match
213                         // spec: "A method call x.m() is valid if the method set of (the type of) x
214                         //        contains m and the argument list can be assigned to the parameter
215                         //        list of m. If x is addressable and &x's method set contains m, x.m()
216                         //        is shorthand for (&x).m()".
217                         if f, _ := obj.(*Func); f != nil {
218                                 // determine if method has a pointer receiver
219                                 hasPtrRecv := tpar == nil && f.hasPtrRecv()
220                                 if hasPtrRecv && !indirect && !addressable {
221                                         return nil, nil, true // pointer/addressable receiver required
222                                 }
223                         }
224                         return
225                 }
226
227                 current = consolidateMultiples(next)
228         }
229
230         return nil, nil, false // not found
231 }
232
233 // embeddedType represents an embedded type
234 type embeddedType struct {
235         typ       Type
236         index     []int // embedded field indices, starting with index at depth 0
237         indirect  bool  // if set, there was a pointer indirection on the path to this field
238         multiples bool  // if set, typ appears multiple times at this depth
239 }
240
241 // consolidateMultiples collects multiple list entries with the same type
242 // into a single entry marked as containing multiples. The result is the
243 // consolidated list.
244 func consolidateMultiples(list []embeddedType) []embeddedType {
245         if len(list) <= 1 {
246                 return list // at most one entry - nothing to do
247         }
248
249         n := 0                     // number of entries w/ unique type
250         prev := make(map[Type]int) // index at which type was previously seen
251         for _, e := range list {
252                 if i, found := lookupType(prev, e.typ); found {
253                         list[i].multiples = true
254                         // ignore this entry
255                 } else {
256                         prev[e.typ] = n
257                         list[n] = e
258                         n++
259                 }
260         }
261         return list[:n]
262 }
263
264 func lookupType(m map[Type]int, typ Type) (int, bool) {
265         // fast path: maybe the types are equal
266         if i, found := m[typ]; found {
267                 return i, true
268         }
269
270         for t, i := range m {
271                 if Identical(t, typ) {
272                         return i, true
273                 }
274         }
275
276         return 0, false
277 }
278
279 // MissingMethod returns (nil, false) if V implements T, otherwise it
280 // returns a missing method required by T and whether it is missing or
281 // just has the wrong type.
282 //
283 // For non-interface types V, or if static is set, V implements T if all
284 // methods of T are present in V. Otherwise (V is an interface and static
285 // is not set), MissingMethod only checks that methods of T which are also
286 // present in V have matching types (e.g., for a type assertion x.(T) where
287 // x is of interface type V).
288 //
289 func MissingMethod(V Type, T *Interface, static bool) (method *Func, wrongType bool) {
290         m, typ := (*Checker)(nil).missingMethod(V, T, static)
291         return m, typ != nil
292 }
293
294 // missingMethod is like MissingMethod but accepts a *Checker as
295 // receiver and an addressable flag.
296 // The receiver may be nil if missingMethod is invoked through
297 // an exported API call (such as MissingMethod), i.e., when all
298 // methods have been type-checked.
299 // If the type has the correctly named method, but with the wrong
300 // signature, the existing method is returned as well.
301 // To improve error messages, also report the wrong signature
302 // when the method exists on *V instead of V.
303 func (check *Checker) missingMethod(V Type, T *Interface, static bool) (method, wrongType *Func) {
304         // fast path for common case
305         if T.Empty() {
306                 return
307         }
308
309         if ityp := toInterface(V); ityp != nil {
310                 // TODO(gri) the methods are sorted - could do this more efficiently
311                 for _, m := range T.typeSet().methods {
312                         _, f := ityp.typeSet().LookupMethod(m.pkg, m.name)
313
314                         if f == nil {
315                                 if !static {
316                                         continue
317                                 }
318                                 return m, f
319                         }
320
321                         // both methods must have the same number of type parameters
322                         ftyp := f.typ.(*Signature)
323                         mtyp := m.typ.(*Signature)
324                         if ftyp.TypeParams().Len() != mtyp.TypeParams().Len() {
325                                 return m, f
326                         }
327                         if !acceptMethodTypeParams && ftyp.TypeParams().Len() > 0 {
328                                 panic("method with type parameters")
329                         }
330
331                         // If the methods have type parameters we don't care whether they
332                         // are the same or not, as long as they match up. Use unification
333                         // to see if they can be made to match.
334                         // TODO(gri) is this always correct? what about type bounds?
335                         // (Alternative is to rename/subst type parameters and compare.)
336                         u := newUnifier(true)
337                         u.x.init(ftyp.TypeParams().list())
338                         if !u.unify(ftyp, mtyp) {
339                                 return m, f
340                         }
341                 }
342
343                 return
344         }
345
346         // A concrete type implements T if it implements all methods of T.
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                         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 ftyp.TypeParams().Len() != mtyp.TypeParams().Len() {
375                         return m, f
376                 }
377                 if !acceptMethodTypeParams && ftyp.TypeParams().Len() > 0 {
378                         panic("method with type parameters")
379                 }
380
381                 // If the methods have type parameters we don't care whether they
382                 // are the same or not, as long as they match up. Use unification
383                 // to see if they can be made to match.
384                 // TODO(gri) is this always correct? what about type bounds?
385                 // (Alternative is to rename/subst type parameters and compare.)
386                 u := newUnifier(true)
387                 if ftyp.TypeParams().Len() > 0 {
388                         // We reach here only if we accept method type parameters.
389                         // In this case, unification must consider any receiver
390                         // and method type parameters as "free" type parameters.
391                         assert(acceptMethodTypeParams)
392                         // We don't have a test case for this at the moment since
393                         // we can't parse method type parameters. Keeping the
394                         // unimplemented call so that we test this code if we
395                         // enable method type parameters.
396                         unimplemented()
397                         u.x.init(append(ftyp.RecvTypeParams().list(), ftyp.TypeParams().list()...))
398                 } else {
399                         u.x.init(ftyp.RecvTypeParams().list())
400                 }
401                 if !u.unify(ftyp, mtyp) {
402                         return m, f
403                 }
404         }
405
406         return
407 }
408
409 // assertableTo reports whether a value of type V can be asserted to have type T.
410 // It returns (nil, false) as affirmative answer. Otherwise it returns a missing
411 // method required by V and whether it is missing or just has the wrong type.
412 // The receiver may be nil if assertableTo is invoked through an exported API call
413 // (such as AssertableTo), i.e., when all methods have been type-checked.
414 // If the global constant forceStrict is set, assertions that are known to fail
415 // are not permitted.
416 func (check *Checker) assertableTo(V *Interface, T Type) (method, wrongType *Func) {
417         // no static check is required if T is an interface
418         // spec: "If T is an interface type, x.(T) asserts that the
419         //        dynamic type of x implements the interface T."
420         if toInterface(T) != nil && !forceStrict {
421                 return
422         }
423         return check.missingMethod(T, V, false)
424 }
425
426 // deref dereferences typ if it is a *Pointer and returns its base and true.
427 // Otherwise it returns (typ, false).
428 func deref(typ Type) (Type, bool) {
429         if p, _ := typ.(*Pointer); p != nil {
430                 return p.base, true
431         }
432         return typ, false
433 }
434
435 // derefStructPtr dereferences typ if it is a (named or unnamed) pointer to a
436 // (named or unnamed) struct and returns its base. Otherwise it returns typ.
437 func derefStructPtr(typ Type) Type {
438         if p := toPointer(typ); p != nil {
439                 if toStruct(p.base) != nil {
440                         return p.base
441                 }
442         }
443         return typ
444 }
445
446 // concat returns the result of concatenating list and i.
447 // The result does not share its underlying array with list.
448 func concat(list []int, i int) []int {
449         var t []int
450         t = append(t, list...)
451         return append(t, i)
452 }
453
454 // fieldIndex returns the index for the field with matching package and name, or a value < 0.
455 func fieldIndex(fields []*Var, pkg *Package, name string) int {
456         if name != "_" {
457                 for i, f := range fields {
458                         if f.sameId(pkg, name) {
459                                 return i
460                         }
461                 }
462         }
463         return -1
464 }
465
466 // lookupMethod returns the index of and method with matching package and name, or (-1, nil).
467 func lookupMethod(methods []*Func, pkg *Package, name string) (int, *Func) {
468         if name != "_" {
469                 for i, m := range methods {
470                         if m.sameId(pkg, name) {
471                                 return i, m
472                         }
473                 }
474         }
475         return -1, nil
476 }