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