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