]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/compile/internal/types2/lookup.go
go/types, types2: complete methods on pointer receivers in missingMethod
[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 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, 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, false, 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 // If checkFold is true, the lookup for methods will include looking for any method
73 // which case-folds to the same as 'name' (used for giving helpful error messages).
74 //
75 // The resulting object may not be fully type-checked.
76 func lookupFieldOrMethod(T Type, addressable, checkFold bool, pkg *Package, name string) (obj Object, index []int, indirect bool) {
77         // WARNING: The code in this function is extremely subtle - do not modify casually!
78
79         if name == "_" {
80                 return // blank fields/methods are never found
81         }
82
83         typ, isPtr := deref(T)
84
85         // *typ where typ is an interface has no methods.
86         if isPtr {
87                 if _, ok := under(typ).(*Interface); ok {
88                         return
89                 }
90         }
91
92         // Start with typ as single entry at shallowest depth.
93         current := []embeddedType{{typ, nil, isPtr, false}}
94
95         // Named types that we have seen already, allocated lazily.
96         // Used to avoid endless searches in case of recursive types.
97         // Since only Named types can be used for recursive types, we
98         // only need to track those.
99         // (If we ever allow type aliases to construct recursive types,
100         // we must use type identity rather than pointer equality for
101         // the map key comparison, as we do in consolidateMultiples.)
102         var seen map[*Named]bool
103
104         // search current depth
105         for len(current) > 0 {
106                 var next []embeddedType // embedded types found at current depth
107
108                 // look for (pkg, name) in all types at current depth
109                 var tpar *TypeParam // set if obj receiver is a type parameter
110                 for _, e := range current {
111                         typ := e.typ
112
113                         // If we have a named type, we may have associated methods.
114                         // Look for those first.
115                         if named, _ := typ.(*Named); named != nil {
116                                 if seen[named] {
117                                         // We have seen this type before, at a more shallow depth
118                                         // (note that multiples of this type at the current depth
119                                         // were consolidated before). The type at that depth shadows
120                                         // this same type at the current depth, so we can ignore
121                                         // this one.
122                                         continue
123                                 }
124                                 if seen == nil {
125                                         seen = make(map[*Named]bool)
126                                 }
127                                 seen[named] = true
128
129                                 // look for a matching attached method
130                                 named.resolve(nil)
131                                 if i, m := lookupMethodFold(named.methods, pkg, name, checkFold); m != nil {
132                                         // potential match
133                                         // caution: method may not have a proper signature yet
134                                         index = concat(e.index, i)
135                                         if obj != nil || e.multiples {
136                                                 return nil, index, false // collision
137                                         }
138                                         obj = m
139                                         indirect = e.indirect
140                                         continue // we can't have a matching field or interface method
141                                 }
142
143                                 // continue with underlying type
144                                 typ = named.under()
145                         }
146
147                         tpar = nil
148                         switch t := typ.(type) {
149                         case *Struct:
150                                 // look for a matching field and collect embedded types
151                                 for i, f := range t.fields {
152                                         if f.sameId(pkg, name) {
153                                                 assert(f.typ != nil)
154                                                 index = concat(e.index, i)
155                                                 if obj != nil || e.multiples {
156                                                         return nil, index, false // collision
157                                                 }
158                                                 obj = f
159                                                 indirect = e.indirect
160                                                 continue // we can't have a matching interface method
161                                         }
162                                         // Collect embedded struct fields for searching the next
163                                         // lower depth, but only if we have not seen a match yet
164                                         // (if we have a match it is either the desired field or
165                                         // we have a name collision on the same depth; in either
166                                         // case we don't need to look further).
167                                         // Embedded fields are always of the form T or *T where
168                                         // T is a type name. If e.typ appeared multiple times at
169                                         // this depth, f.typ appears multiple times at the next
170                                         // depth.
171                                         if obj == nil && f.embedded {
172                                                 typ, isPtr := deref(f.typ)
173                                                 // TODO(gri) optimization: ignore types that can't
174                                                 // have fields or methods (only Named, Struct, and
175                                                 // Interface types need to be considered).
176                                                 next = append(next, embeddedType{typ, concat(e.index, i), e.indirect || isPtr, e.multiples})
177                                         }
178                                 }
179
180                         case *Interface:
181                                 // look for a matching method
182                                 if i, m := lookupMethodFold(t.typeSet().methods, pkg, name, checkFold); m != nil {
183                                         assert(m.typ != nil)
184                                         index = concat(e.index, i)
185                                         if obj != nil || e.multiples {
186                                                 return nil, index, false // collision
187                                         }
188                                         obj = m
189                                         indirect = e.indirect
190                                 }
191
192                         case *TypeParam:
193                                 if i, m := lookupMethodFold(t.iface().typeSet().methods, pkg, name, checkFold); m != nil {
194                                         assert(m.typ != nil)
195                                         index = concat(e.index, i)
196                                         if obj != nil || e.multiples {
197                                                 return nil, index, false // collision
198                                         }
199                                         tpar = t
200                                         obj = m
201                                         indirect = e.indirect
202                                 }
203                                 if obj == nil {
204                                         // At this point we're not (yet) looking into methods
205                                         // that any underlying type of the types in the type list
206                                         // might have.
207                                         // TODO(gri) Do we want to specify the language that way?
208                                 }
209                         }
210                 }
211
212                 if obj != nil {
213                         // found a potential match
214                         // spec: "A method call x.m() is valid if the method set of (the type of) x
215                         //        contains m and the argument list can be assigned to the parameter
216                         //        list of m. If x is addressable and &x's method set contains m, x.m()
217                         //        is shorthand for (&x).m()".
218                         if f, _ := obj.(*Func); f != nil {
219                                 // determine if method has a pointer receiver
220                                 hasPtrRecv := tpar == nil && f.hasPtrRecv()
221                                 if hasPtrRecv && !indirect && !addressable {
222                                         return nil, nil, true // pointer/addressable receiver required
223                                 }
224                         }
225                         return
226                 }
227
228                 current = consolidateMultiples(next)
229         }
230
231         return nil, nil, false // not found
232 }
233
234 // embeddedType represents an embedded type
235 type embeddedType struct {
236         typ       Type
237         index     []int // embedded field indices, starting with index at depth 0
238         indirect  bool  // if set, there was a pointer indirection on the path to this field
239         multiples bool  // if set, typ appears multiple times at this depth
240 }
241
242 // consolidateMultiples collects multiple list entries with the same type
243 // into a single entry marked as containing multiples. The result is the
244 // consolidated list.
245 func consolidateMultiples(list []embeddedType) []embeddedType {
246         if len(list) <= 1 {
247                 return list // at most one entry - nothing to do
248         }
249
250         n := 0                     // number of entries w/ unique type
251         prev := make(map[Type]int) // index at which type was previously seen
252         for _, e := range list {
253                 if i, found := lookupType(prev, e.typ); found {
254                         list[i].multiples = true
255                         // ignore this entry
256                 } else {
257                         prev[e.typ] = n
258                         list[n] = e
259                         n++
260                 }
261         }
262         return list[:n]
263 }
264
265 func lookupType(m map[Type]int, typ Type) (int, bool) {
266         // fast path: maybe the types are equal
267         if i, found := m[typ]; found {
268                 return i, true
269         }
270
271         for t, i := range m {
272                 if Identical(t, typ) {
273                         return i, true
274                 }
275         }
276
277         return 0, false
278 }
279
280 // MissingMethod returns (nil, false) if V implements T, otherwise it
281 // returns a missing method required by T and whether it is missing or
282 // just has the wrong type.
283 //
284 // For non-interface types V, or if static is set, V implements T if all
285 // methods of T are present in V. Otherwise (V is an interface and static
286 // is not set), MissingMethod only checks that methods of T which are also
287 // present in V have matching types (e.g., for a type assertion x.(T) where
288 // x is of interface type V).
289 //
290 func MissingMethod(V Type, T *Interface, static bool) (method *Func, wrongType bool) {
291         m, typ := (*Checker)(nil).missingMethod(V, T, static)
292         return m, typ != nil
293 }
294
295 // missingMethod is like MissingMethod but accepts a *Checker as
296 // receiver and an addressable flag.
297 // The receiver may be nil if missingMethod is invoked through
298 // an exported API call (such as MissingMethod), i.e., when all
299 // methods have been type-checked.
300 // If the type has the correctly named method, but with the wrong
301 // signature, the existing method is returned as well.
302 // To improve error messages, also report the wrong signature
303 // when the method exists on *V instead of V.
304 func (check *Checker) missingMethod(V Type, T *Interface, static bool) (method, wrongType *Func) {
305         // fast path for common case
306         if T.Empty() {
307                 return
308         }
309
310         if ityp, _ := under(V).(*Interface); ityp != nil {
311                 // TODO(gri) the methods are sorted - could do this more efficiently
312                 for _, m := range T.typeSet().methods {
313                         _, f := ityp.typeSet().LookupMethod(m.pkg, m.name)
314
315                         if f == nil {
316                                 if !static {
317                                         continue
318                                 }
319                                 // We don't do any case-fold check if V is an interface.
320                                 return m, f
321                         }
322
323                         // both methods must have the same number of type parameters
324                         ftyp := f.typ.(*Signature)
325                         mtyp := m.typ.(*Signature)
326                         if ftyp.TypeParams().Len() != mtyp.TypeParams().Len() {
327                                 return m, f
328                         }
329                         if !acceptMethodTypeParams && ftyp.TypeParams().Len() > 0 {
330                                 panic("method with type parameters")
331                         }
332
333                         // If the methods have type parameters we don't care whether they
334                         // are the same or not, as long as they match up. Use unification
335                         // to see if they can be made to match.
336                         // TODO(gri) is this always correct? what about type bounds?
337                         // (Alternative is to rename/subst type parameters and compare.)
338                         u := newUnifier(true)
339                         u.x.init(ftyp.TypeParams().list())
340                         if !u.unify(ftyp, mtyp) {
341                                 return m, f
342                         }
343                 }
344
345                 return
346         }
347
348         // A concrete type implements T if it implements all methods of T.
349         for _, m := range T.typeSet().methods {
350                 // TODO(gri) should this be calling LookupFieldOrMethod instead (and why not)?
351                 obj, _, _ := lookupFieldOrMethod(V, false, false, m.pkg, m.name)
352
353                 // Check if *V implements this method of T.
354                 if obj == nil {
355                         ptr := NewPointer(V)
356                         obj, _, _ = lookupFieldOrMethod(ptr, false, false, m.pkg, m.name)
357                         if obj == nil {
358                                 // If we didn't find the exact method (even with pointer
359                                 // receiver), look to see if there is a method that
360                                 // matches m.name with case-folding.
361                                 obj, _, _ = lookupFieldOrMethod(V, false, true, m.pkg, m.name)
362                         }
363                         if obj != nil {
364                                 // methods may not have a fully set up signature yet
365                                 if check != nil {
366                                         check.objDecl(obj, nil)
367                                 }
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                         return m, nil
376                 }
377
378                 // methods may not have a fully set up signature yet
379                 if check != nil {
380                         check.objDecl(f, nil)
381                 }
382
383                 // both methods must have the same number of type parameters
384                 ftyp := f.typ.(*Signature)
385                 mtyp := m.typ.(*Signature)
386                 if ftyp.TypeParams().Len() != mtyp.TypeParams().Len() {
387                         return m, f
388                 }
389                 if !acceptMethodTypeParams && ftyp.TypeParams().Len() > 0 {
390                         panic("method with type parameters")
391                 }
392
393                 // If the methods have type parameters we don't care whether they
394                 // are the same or not, as long as they match up. Use unification
395                 // to see if they can be made to match.
396                 // TODO(gri) is this always correct? what about type bounds?
397                 // (Alternative is to rename/subst type parameters and compare.)
398                 u := newUnifier(true)
399                 if ftyp.TypeParams().Len() > 0 {
400                         // We reach here only if we accept method type parameters.
401                         // In this case, unification must consider any receiver
402                         // and method type parameters as "free" type parameters.
403                         assert(acceptMethodTypeParams)
404                         // We don't have a test case for this at the moment since
405                         // we can't parse method type parameters. Keeping the
406                         // unimplemented call so that we test this code if we
407                         // enable method type parameters.
408                         unimplemented()
409                         u.x.init(append(ftyp.RecvTypeParams().list(), ftyp.TypeParams().list()...))
410                 } else {
411                         u.x.init(ftyp.RecvTypeParams().list())
412                 }
413                 if !u.unify(ftyp, mtyp) {
414                         return m, f
415                 }
416         }
417
418         return
419 }
420
421 // missingMethodReason returns a string giving the detailed reason for a missing method m,
422 // where m is missing from V, but required by T. It puts the reason in parentheses,
423 // and may include more have/want info after that. If non-nil, wrongType is a relevant
424 // method that matches in some way. It may have the correct name, but wrong type, or
425 // it may have a pointer receiver, or it may have the correct name except wrong case.
426 func (check *Checker) missingMethodReason(V, T Type, m, wrongType *Func) string {
427         var r string
428         var mname string
429         if check.conf.CompilerErrorMessages {
430                 mname = m.Name() + " method"
431         } else {
432                 mname = "method " + m.Name()
433         }
434         if wrongType != nil {
435                 if Identical(m.typ, wrongType.typ) {
436                         if m.Name() == wrongType.Name() {
437                                 r = fmt.Sprintf("(%s has pointer receiver)", mname)
438                         } else {
439                                 r = fmt.Sprintf("(missing %s)\n\t\thave %s^^%s\n\t\twant %s^^%s",
440                                         mname, wrongType.Name(), wrongType.typ, m.Name(), m.typ)
441                         }
442                 } else {
443                         if check.conf.CompilerErrorMessages {
444                                 r = fmt.Sprintf("(wrong type for %s)\n\t\thave %s^^%s\n\t\twant %s^^%s",
445                                         mname, wrongType.Name(), wrongType.typ, m.Name(), m.typ)
446                         } else {
447                                 r = fmt.Sprintf("(wrong type for %s: have %s, want %s)",
448                                         mname, wrongType.typ, m.typ)
449                         }
450                 }
451                 // This is a hack to print the function type without the leading
452                 // 'func' keyword in the have/want printouts. We could change to have
453                 // an extra formatting option for types2.Type that doesn't print out
454                 // 'func'.
455                 r = strings.Replace(r, "^^func", "", -1)
456         } else if IsInterface(T) && !isTypeParam(T) {
457                 if isInterfacePtr(V) {
458                         r = fmt.Sprintf("(%s is pointer to interface, not interface)", V)
459                 }
460         } else if isInterfacePtr(T) && !isTypeParam(T) {
461                 r = fmt.Sprintf("(%s is pointer to interface, not interface)", T)
462         }
463         if r == "" {
464                 r = fmt.Sprintf("(missing %s)", mname)
465         }
466         return r
467 }
468
469 func isInterfacePtr(T Type) bool {
470         p, _ := under(T).(*Pointer)
471         return p != nil && IsInterface(p.base) && !isTypeParam(p.base)
472 }
473
474 // assertableTo reports whether a value of type V can be asserted to have type T.
475 // It returns (nil, false) as affirmative answer. Otherwise it returns a missing
476 // method required by V and whether it is missing or just has the wrong type.
477 // The receiver may be nil if assertableTo is invoked through an exported API call
478 // (such as AssertableTo), i.e., when all methods have been type-checked.
479 // If the global constant forceStrict is set, assertions that are known to fail
480 // are not permitted.
481 func (check *Checker) assertableTo(V *Interface, T Type) (method, wrongType *Func) {
482         // no static check is required if T is an interface
483         // spec: "If T is an interface type, x.(T) asserts that the
484         //        dynamic type of x implements the interface T."
485         if IsInterface(T) && !forceStrict {
486                 return
487         }
488         return check.missingMethod(T, V, false)
489 }
490
491 // deref dereferences typ if it is a *Pointer and returns its base and true.
492 // Otherwise it returns (typ, false).
493 func deref(typ Type) (Type, bool) {
494         if p, _ := typ.(*Pointer); p != nil {
495                 // p.base should never be nil, but be conservative
496                 if p.base == nil {
497                         if debug {
498                                 panic("pointer with nil base type (possibly due to an invalid cyclic declaration)")
499                         }
500                         return Typ[Invalid], true
501                 }
502                 return p.base, true
503         }
504         return typ, false
505 }
506
507 // derefStructPtr dereferences typ if it is a (named or unnamed) pointer to a
508 // (named or unnamed) struct and returns its base. Otherwise it returns typ.
509 func derefStructPtr(typ Type) Type {
510         if p, _ := under(typ).(*Pointer); p != nil {
511                 if _, ok := under(p.base).(*Struct); ok {
512                         return p.base
513                 }
514         }
515         return typ
516 }
517
518 // concat returns the result of concatenating list and i.
519 // The result does not share its underlying array with list.
520 func concat(list []int, i int) []int {
521         var t []int
522         t = append(t, list...)
523         return append(t, i)
524 }
525
526 // fieldIndex returns the index for the field with matching package and name, or a value < 0.
527 func fieldIndex(fields []*Var, pkg *Package, name string) int {
528         if name != "_" {
529                 for i, f := range fields {
530                         if f.sameId(pkg, name) {
531                                 return i
532                         }
533                 }
534         }
535         return -1
536 }
537
538 // lookupMethod returns the index of and method with matching package and name, or (-1, nil).
539 func lookupMethod(methods []*Func, pkg *Package, name string) (int, *Func) {
540         if name != "_" {
541                 for i, m := range methods {
542                         if m.sameId(pkg, name) {
543                                 return i, m
544                         }
545                 }
546         }
547         return -1, nil
548 }
549
550 // lookupMethodFold is like lookupMethod, but if checkFold is true, it matches a method
551 // name if the names are equal with case folding.
552 func lookupMethodFold(methods []*Func, pkg *Package, name string, checkFold bool) (int, *Func) {
553         if name != "_" {
554                 for i, m := range methods {
555                         if m.name != name && !(checkFold && strings.EqualFold(m.name, name)) {
556                                 continue
557                         }
558                         // Use m.name, since we've already checked that m.name and
559                         // name are equal with folding.
560                         if m.sameId(pkg, m.name) {
561                                 return i, m
562                         }
563                 }
564         }
565         return -1, nil
566 }