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