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