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