Source file 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 "bytes" 10 11 // LookupSelection selects the field or method whose ID is Id(pkg, 12 // name), on a value of type T. If addressable is set, T is the type 13 // of an addressable variable (this matters only for method lookups). 14 // T must not be nil. 15 // 16 // If the selection is valid: 17 // 18 // - [Selection.Obj] returns the field ([Var]) or method ([Func]); 19 // - [Selection.Indirect] reports whether there were any pointer 20 // indirections on the path to the field or method. 21 // - [Selection.Index] returns the index sequence, defined below. 22 // 23 // The last index entry is the field or method index in the (possibly 24 // embedded) type where the entry was found, either: 25 // 26 // 1. the list of declared methods of a named type; or 27 // 2. the list of all methods (method set) of an interface type; or 28 // 3. the list of fields of a struct type. 29 // 30 // The earlier index entries are the indices of the embedded struct 31 // fields traversed to get to the found entry, starting at depth 0. 32 // 33 // See also [LookupFieldOrMethod], which returns the components separately. 34 func LookupSelection(T Type, addressable bool, pkg *Package, name string) (Selection, bool) { 35 obj, index, indirect := LookupFieldOrMethod(T, addressable, pkg, name) 36 var kind SelectionKind 37 switch obj.(type) { 38 case nil: 39 return Selection{}, false 40 case *Func: 41 kind = MethodVal 42 case *Var: 43 kind = FieldVal 44 default: 45 panic(obj) // can't happen 46 } 47 return Selection{kind, T, obj, index, indirect}, true 48 } 49 50 // Internal use of LookupFieldOrMethod: If the obj result is a method 51 // associated with a concrete (non-interface) type, the method's signature 52 // may not be fully set up. Call Checker.objDecl(obj, nil) before accessing 53 // the method's type. 54 55 // LookupFieldOrMethod looks up a field or method with given package and name 56 // in T and returns the corresponding *Var or *Func, an index sequence, and a 57 // bool indicating if there were any pointer indirections on the path to the 58 // field or method. If addressable is set, T is the type of an addressable 59 // variable (only matters for method lookups). T must not be nil. 60 // 61 // The last index entry is the field or method index in the (possibly embedded) 62 // type where the entry was found, either: 63 // 64 // 1. the list of declared methods of a named type; or 65 // 2. the list of all methods (method set) of an interface type; or 66 // 3. the list of fields of a struct type. 67 // 68 // The earlier index entries are the indices of the embedded struct fields 69 // traversed to get to the found entry, starting at depth 0. 70 // 71 // If no entry is found, a nil object is returned. In this case, the returned 72 // index and indirect values have the following meaning: 73 // 74 // - If index != nil, the index sequence points to an ambiguous entry 75 // (the same name appeared more than once at the same embedding level). 76 // 77 // - If indirect is set, a method with a pointer receiver type was found 78 // but there was no pointer on the path from the actual receiver type to 79 // the method's formal receiver base type, nor was the receiver addressable. 80 // 81 // See also [LookupSelection], which returns the result as a [Selection]. 82 func LookupFieldOrMethod(T Type, addressable bool, pkg *Package, name string) (obj Object, index []int, indirect bool) { 83 if T == nil { 84 panic("LookupFieldOrMethod on nil type") 85 } 86 return lookupFieldOrMethod(T, addressable, pkg, name, false) 87 } 88 89 // lookupFieldOrMethod is like LookupFieldOrMethod but with the additional foldCase parameter 90 // (see Object.sameId for the meaning of foldCase). 91 func lookupFieldOrMethod(T Type, addressable bool, pkg *Package, name string, foldCase bool) (obj Object, index []int, indirect bool) { 92 // Methods cannot be associated to a named pointer type. 93 // (spec: "The type denoted by T is called the receiver base type; 94 // it must not be a pointer or interface type and it must be declared 95 // in the same package as the method."). 96 // Thus, if we have a named pointer type, proceed with the underlying 97 // pointer type but discard the result if it is a method since we would 98 // not have found it for T (see also go.dev/issue/8590). 99 if t := asNamed(T); t != nil { 100 if p, _ := t.Underlying().(*Pointer); p != nil { 101 obj, index, indirect = lookupFieldOrMethodImpl(p, false, pkg, name, foldCase) 102 if _, ok := obj.(*Func); ok { 103 return nil, nil, false 104 } 105 return 106 } 107 } 108 109 obj, index, indirect = lookupFieldOrMethodImpl(T, addressable, pkg, name, foldCase) 110 111 // If we didn't find anything and if we have a type parameter with a common underlying 112 // type, see if there is a matching field (but not a method, those need to be declared 113 // explicitly in the constraint). If the constraint is a named pointer type (see above), 114 // we are ok here because only fields are accepted as results. 115 const enableTParamFieldLookup = false // see go.dev/issue/51576 116 if enableTParamFieldLookup && obj == nil && isTypeParam(T) { 117 if t, _ := commonUnder(T, nil); t != nil { 118 obj, index, indirect = lookupFieldOrMethodImpl(t, addressable, pkg, name, foldCase) 119 if _, ok := obj.(*Var); !ok { 120 obj, index, indirect = nil, nil, false // accept fields (variables) only 121 } 122 } 123 } 124 return 125 } 126 127 // lookupFieldOrMethodImpl is the implementation of lookupFieldOrMethod. 128 // Notably, in contrast to lookupFieldOrMethod, it won't find struct fields 129 // in base types of defined (*Named) pointer types T. For instance, given 130 // the declaration: 131 // 132 // type T *struct{f int} 133 // 134 // lookupFieldOrMethodImpl won't find the field f in the defined (*Named) type T 135 // (methods on T are not permitted in the first place). 136 // 137 // Thus, lookupFieldOrMethodImpl should only be called by lookupFieldOrMethod 138 // and missingMethod (the latter doesn't care about struct fields). 139 // 140 // The resulting object may not be fully type-checked. 141 func lookupFieldOrMethodImpl(T Type, addressable bool, pkg *Package, name string, foldCase bool) (obj Object, index []int, indirect bool) { 142 // WARNING: The code in this function is extremely subtle - do not modify casually! 143 144 if name == "_" { 145 return // blank fields/methods are never found 146 } 147 148 // Importantly, we must not call under before the call to deref below (nor 149 // does deref call under), as doing so could incorrectly result in finding 150 // methods of the pointer base type when T is a (*Named) pointer type. 151 typ, isPtr := deref(T) 152 153 // *typ where typ is an interface (incl. a type parameter) has no methods. 154 if isPtr { 155 if _, ok := under(typ).(*Interface); ok { 156 return 157 } 158 } 159 160 // Start with typ as single entry at shallowest depth. 161 current := []embeddedType{{typ, nil, isPtr, false}} 162 163 // seen tracks named types that we have seen already, allocated lazily. 164 // Used to avoid endless searches in case of recursive types. 165 // 166 // We must use a lookup on identity rather than a simple map[*Named]bool as 167 // instantiated types may be identical but not equal. 168 var seen instanceLookup 169 170 // search current depth 171 for len(current) > 0 { 172 var next []embeddedType // embedded types found at current depth 173 174 // look for (pkg, name) in all types at current depth 175 for _, e := range current { 176 typ := e.typ 177 178 // If we have a named type, we may have associated methods. 179 // Look for those first. 180 if named := asNamed(typ); named != nil { 181 if alt := seen.lookup(named); alt != nil { 182 // We have seen this type before, at a more shallow depth 183 // (note that multiples of this type at the current depth 184 // were consolidated before). The type at that depth shadows 185 // this same type at the current depth, so we can ignore 186 // this one. 187 continue 188 } 189 seen.add(named) 190 191 // look for a matching attached method 192 if i, m := named.lookupMethod(pkg, name, foldCase); m != nil { 193 // potential match 194 // caution: method may not have a proper signature yet 195 index = concat(e.index, i) 196 if obj != nil || e.multiples { 197 return nil, index, false // collision 198 } 199 obj = m 200 indirect = e.indirect 201 continue // we can't have a matching field or interface method 202 } 203 } 204 205 switch t := under(typ).(type) { 206 case *Struct: 207 // look for a matching field and collect embedded types 208 for i, f := range t.fields { 209 if f.sameId(pkg, name, foldCase) { 210 assert(f.typ != nil) 211 index = concat(e.index, i) 212 if obj != nil || e.multiples { 213 return nil, index, false // collision 214 } 215 obj = f 216 indirect = e.indirect 217 continue // we can't have a matching interface method 218 } 219 // Collect embedded struct fields for searching the next 220 // lower depth, but only if we have not seen a match yet 221 // (if we have a match it is either the desired field or 222 // we have a name collision on the same depth; in either 223 // case we don't need to look further). 224 // Embedded fields are always of the form T or *T where 225 // T is a type name. If e.typ appeared multiple times at 226 // this depth, f.typ appears multiple times at the next 227 // depth. 228 if obj == nil && f.embedded { 229 typ, isPtr := deref(f.typ) 230 // TODO(gri) optimization: ignore types that can't 231 // have fields or methods (only Named, Struct, and 232 // Interface types need to be considered). 233 next = append(next, embeddedType{typ, concat(e.index, i), e.indirect || isPtr, e.multiples}) 234 } 235 } 236 237 case *Interface: 238 // look for a matching method (interface may be a type parameter) 239 if i, m := t.typeSet().LookupMethod(pkg, name, foldCase); m != nil { 240 assert(m.typ != nil) 241 index = concat(e.index, i) 242 if obj != nil || e.multiples { 243 return nil, index, false // collision 244 } 245 obj = m 246 indirect = e.indirect 247 } 248 } 249 } 250 251 if obj != nil { 252 // found a potential match 253 // spec: "A method call x.m() is valid if the method set of (the type of) x 254 // contains m and the argument list can be assigned to the parameter 255 // list of m. If x is addressable and &x's method set contains m, x.m() 256 // is shorthand for (&x).m()". 257 if f, _ := obj.(*Func); f != nil { 258 // determine if method has a pointer receiver 259 if f.hasPtrRecv() && !indirect && !addressable { 260 return nil, nil, true // pointer/addressable receiver required 261 } 262 } 263 return 264 } 265 266 current = consolidateMultiples(next) 267 } 268 269 return nil, nil, false // not found 270 } 271 272 // embeddedType represents an embedded type 273 type embeddedType struct { 274 typ Type 275 index []int // embedded field indices, starting with index at depth 0 276 indirect bool // if set, there was a pointer indirection on the path to this field 277 multiples bool // if set, typ appears multiple times at this depth 278 } 279 280 // consolidateMultiples collects multiple list entries with the same type 281 // into a single entry marked as containing multiples. The result is the 282 // consolidated list. 283 func consolidateMultiples(list []embeddedType) []embeddedType { 284 if len(list) <= 1 { 285 return list // at most one entry - nothing to do 286 } 287 288 n := 0 // number of entries w/ unique type 289 prev := make(map[Type]int) // index at which type was previously seen 290 for _, e := range list { 291 if i, found := lookupType(prev, e.typ); found { 292 list[i].multiples = true 293 // ignore this entry 294 } else { 295 prev[e.typ] = n 296 list[n] = e 297 n++ 298 } 299 } 300 return list[:n] 301 } 302 303 func lookupType(m map[Type]int, typ Type) (int, bool) { 304 // fast path: maybe the types are equal 305 if i, found := m[typ]; found { 306 return i, true 307 } 308 309 for t, i := range m { 310 if Identical(t, typ) { 311 return i, true 312 } 313 } 314 315 return 0, false 316 } 317 318 type instanceLookup struct { 319 // buf is used to avoid allocating the map m in the common case of a small 320 // number of instances. 321 buf [3]*Named 322 m map[*Named][]*Named 323 } 324 325 func (l *instanceLookup) lookup(inst *Named) *Named { 326 for _, t := range l.buf { 327 if t != nil && Identical(inst, t) { 328 return t 329 } 330 } 331 for _, t := range l.m[inst.Origin()] { 332 if Identical(inst, t) { 333 return t 334 } 335 } 336 return nil 337 } 338 339 func (l *instanceLookup) add(inst *Named) { 340 for i, t := range l.buf { 341 if t == nil { 342 l.buf[i] = inst 343 return 344 } 345 } 346 if l.m == nil { 347 l.m = make(map[*Named][]*Named) 348 } 349 insts := l.m[inst.Origin()] 350 l.m[inst.Origin()] = append(insts, inst) 351 } 352 353 // MissingMethod returns (nil, false) if V implements T, otherwise it 354 // returns a missing method required by T and whether it is missing or 355 // just has the wrong type: either a pointer receiver or wrong signature. 356 // 357 // For non-interface types V, or if static is set, V implements T if all 358 // methods of T are present in V. Otherwise (V is an interface and static 359 // is not set), MissingMethod only checks that methods of T which are also 360 // present in V have matching types (e.g., for a type assertion x.(T) where 361 // x is of interface type V). 362 func MissingMethod(V Type, T *Interface, static bool) (method *Func, wrongType bool) { 363 return (*Checker)(nil).missingMethod(V, T, static, Identical, nil) 364 } 365 366 // missingMethod is like MissingMethod but accepts a *Checker as receiver, 367 // a comparator equivalent for type comparison, and a *string for error causes. 368 // The receiver may be nil if missingMethod is invoked through an exported 369 // API call (such as MissingMethod), i.e., when all methods have been type- 370 // checked. 371 // The underlying type of T must be an interface; T (rather than its under- 372 // lying type) is used for better error messages (reported through *cause). 373 // The comparator is used to compare signatures. 374 // If a method is missing and cause is not nil, *cause describes the error. 375 func (check *Checker) missingMethod(V, T Type, static bool, equivalent func(x, y Type) bool, cause *string) (method *Func, wrongType bool) { 376 methods := under(T).(*Interface).typeSet().methods // T must be an interface 377 if len(methods) == 0 { 378 return nil, false 379 } 380 381 const ( 382 ok = iota 383 notFound 384 wrongName 385 unexported 386 wrongSig 387 ambigSel 388 ptrRecv 389 field 390 ) 391 392 state := ok 393 var m *Func // method on T we're trying to implement 394 var f *Func // method on V, if found (state is one of ok, wrongName, wrongSig) 395 396 if u, _ := under(V).(*Interface); u != nil { 397 tset := u.typeSet() 398 for _, m = range methods { 399 _, f = tset.LookupMethod(m.pkg, m.name, false) 400 401 if f == nil { 402 if !static { 403 continue 404 } 405 state = notFound 406 break 407 } 408 409 if !equivalent(f.typ, m.typ) { 410 state = wrongSig 411 break 412 } 413 } 414 } else { 415 for _, m = range methods { 416 obj, index, indirect := lookupFieldOrMethodImpl(V, false, m.pkg, m.name, false) 417 418 // check if m is ambiguous, on *V, or on V with case-folding 419 if obj == nil { 420 switch { 421 case index != nil: 422 state = ambigSel 423 case indirect: 424 state = ptrRecv 425 default: 426 state = notFound 427 obj, _, _ = lookupFieldOrMethodImpl(V, false, m.pkg, m.name, true /* fold case */) 428 f, _ = obj.(*Func) 429 if f != nil { 430 state = wrongName 431 if f.name == m.name { 432 // If the names are equal, f must be unexported 433 // (otherwise the package wouldn't matter). 434 state = unexported 435 } 436 } 437 } 438 break 439 } 440 441 // we must have a method (not a struct field) 442 f, _ = obj.(*Func) 443 if f == nil { 444 state = field 445 break 446 } 447 448 // methods may not have a fully set up signature yet 449 if check != nil { 450 check.objDecl(f, nil) 451 } 452 453 if !equivalent(f.typ, m.typ) { 454 state = wrongSig 455 break 456 } 457 } 458 } 459 460 if state == ok { 461 return nil, false 462 } 463 464 if cause != nil { 465 if f != nil { 466 // This method may be formatted in funcString below, so must have a fully 467 // set up signature. 468 if check != nil { 469 check.objDecl(f, nil) 470 } 471 } 472 switch state { 473 case notFound: 474 switch { 475 case isInterfacePtr(V): 476 *cause = "(" + check.interfacePtrError(V) + ")" 477 case isInterfacePtr(T): 478 *cause = "(" + check.interfacePtrError(T) + ")" 479 default: 480 *cause = check.sprintf("(missing method %s)", m.Name()) 481 } 482 case wrongName: 483 fs, ms := check.funcString(f, false), check.funcString(m, false) 484 *cause = check.sprintf("(missing method %s)\n\t\thave %s\n\t\twant %s", m.Name(), fs, ms) 485 case unexported: 486 *cause = check.sprintf("(unexported method %s)", m.Name()) 487 case wrongSig: 488 fs, ms := check.funcString(f, false), check.funcString(m, false) 489 if fs == ms { 490 // Don't report "want Foo, have Foo". 491 // Add package information to disambiguate (go.dev/issue/54258). 492 fs, ms = check.funcString(f, true), check.funcString(m, true) 493 } 494 if fs == ms { 495 // We still have "want Foo, have Foo". 496 // This is most likely due to different type parameters with 497 // the same name appearing in the instantiated signatures 498 // (go.dev/issue/61685). 499 // Rather than reporting this misleading error cause, for now 500 // just point out that the method signature is incorrect. 501 // TODO(gri) should find a good way to report the root cause 502 *cause = check.sprintf("(wrong type for method %s)", m.Name()) 503 break 504 } 505 *cause = check.sprintf("(wrong type for method %s)\n\t\thave %s\n\t\twant %s", m.Name(), fs, ms) 506 case ambigSel: 507 *cause = check.sprintf("(ambiguous selector %s.%s)", V, m.Name()) 508 case ptrRecv: 509 *cause = check.sprintf("(method %s has pointer receiver)", m.Name()) 510 case field: 511 *cause = check.sprintf("(%s.%s is a field, not a method)", V, m.Name()) 512 default: 513 panic("unreachable") 514 } 515 } 516 517 return m, state == wrongSig || state == ptrRecv 518 } 519 520 // hasAllMethods is similar to checkMissingMethod but instead reports whether all methods are present. 521 // If V is not a valid type, or if it is a struct containing embedded fields with invalid types, the 522 // result is true because it is not possible to say with certainty whether a method is missing or not 523 // (an embedded field may have the method in question). 524 // If the result is false and cause is not nil, *cause describes the error. 525 // Use hasAllMethods to avoid follow-on errors due to incorrect types. 526 func (check *Checker) hasAllMethods(V, T Type, static bool, equivalent func(x, y Type) bool, cause *string) bool { 527 if !isValid(V) { 528 return true // we don't know anything about V, assume it implements T 529 } 530 m, _ := check.missingMethod(V, T, static, equivalent, cause) 531 return m == nil || hasInvalidEmbeddedFields(V, nil) 532 } 533 534 // hasInvalidEmbeddedFields reports whether T is a struct (or a pointer to a struct) that contains 535 // (directly or indirectly) embedded fields with invalid types. 536 func hasInvalidEmbeddedFields(T Type, seen map[*Struct]bool) bool { 537 if S, _ := under(derefStructPtr(T)).(*Struct); S != nil && !seen[S] { 538 if seen == nil { 539 seen = make(map[*Struct]bool) 540 } 541 seen[S] = true 542 for _, f := range S.fields { 543 if f.embedded && (!isValid(f.typ) || hasInvalidEmbeddedFields(f.typ, seen)) { 544 return true 545 } 546 } 547 } 548 return false 549 } 550 551 func isInterfacePtr(T Type) bool { 552 p, _ := under(T).(*Pointer) 553 return p != nil && IsInterface(p.base) 554 } 555 556 // check may be nil. 557 func (check *Checker) interfacePtrError(T Type) string { 558 assert(isInterfacePtr(T)) 559 if p, _ := under(T).(*Pointer); isTypeParam(p.base) { 560 return check.sprintf("type %s is pointer to type parameter, not type parameter", T) 561 } 562 return check.sprintf("type %s is pointer to interface, not interface", T) 563 } 564 565 // funcString returns a string of the form name + signature for f. 566 // check may be nil. 567 func (check *Checker) funcString(f *Func, pkgInfo bool) string { 568 buf := bytes.NewBufferString(f.name) 569 var qf Qualifier 570 if check != nil && !pkgInfo { 571 qf = check.qualifier 572 } 573 w := newTypeWriter(buf, qf) 574 w.pkgInfo = pkgInfo 575 w.paramNames = false 576 w.signature(f.typ.(*Signature)) 577 return buf.String() 578 } 579 580 // assertableTo reports whether a value of type V can be asserted to have type T. 581 // The receiver may be nil if assertableTo is invoked through an exported API call 582 // (such as AssertableTo), i.e., when all methods have been type-checked. 583 // The underlying type of V must be an interface. 584 // If the result is false and cause is not nil, *cause describes the error. 585 // TODO(gri) replace calls to this function with calls to newAssertableTo. 586 func (check *Checker) assertableTo(V, T Type, cause *string) bool { 587 // no static check is required if T is an interface 588 // spec: "If T is an interface type, x.(T) asserts that the 589 // dynamic type of x implements the interface T." 590 if IsInterface(T) { 591 return true 592 } 593 // TODO(gri) fix this for generalized interfaces 594 return check.hasAllMethods(T, V, false, Identical, cause) 595 } 596 597 // newAssertableTo reports whether a value of type V can be asserted to have type T. 598 // It also implements behavior for interfaces that currently are only permitted 599 // in constraint position (we have not yet defined that behavior in the spec). 600 // The underlying type of V must be an interface. 601 // If the result is false and cause is not nil, *cause is set to the error cause. 602 func (check *Checker) newAssertableTo(V, T Type, cause *string) bool { 603 // no static check is required if T is an interface 604 // spec: "If T is an interface type, x.(T) asserts that the 605 // dynamic type of x implements the interface T." 606 if IsInterface(T) { 607 return true 608 } 609 return check.implements(T, V, false, cause) 610 } 611 612 // deref dereferences typ if it is a *Pointer (but not a *Named type 613 // with an underlying pointer type!) and returns its base and true. 614 // Otherwise it returns (typ, false). 615 func deref(typ Type) (Type, bool) { 616 if p, _ := Unalias(typ).(*Pointer); p != nil { 617 // p.base should never be nil, but be conservative 618 if p.base == nil { 619 if debug { 620 panic("pointer with nil base type (possibly due to an invalid cyclic declaration)") 621 } 622 return Typ[Invalid], true 623 } 624 return p.base, true 625 } 626 return typ, false 627 } 628 629 // derefStructPtr dereferences typ if it is a (named or unnamed) pointer to a 630 // (named or unnamed) struct and returns its base. Otherwise it returns typ. 631 func derefStructPtr(typ Type) Type { 632 if p, _ := under(typ).(*Pointer); p != nil { 633 if _, ok := under(p.base).(*Struct); ok { 634 return p.base 635 } 636 } 637 return typ 638 } 639 640 // concat returns the result of concatenating list and i. 641 // The result does not share its underlying array with list. 642 func concat(list []int, i int) []int { 643 var t []int 644 t = append(t, list...) 645 return append(t, i) 646 } 647 648 // fieldIndex returns the index for the field with matching package and name, or a value < 0. 649 // See Object.sameId for the meaning of foldCase. 650 func fieldIndex(fields []*Var, pkg *Package, name string, foldCase bool) int { 651 if name != "_" { 652 for i, f := range fields { 653 if f.sameId(pkg, name, foldCase) { 654 return i 655 } 656 } 657 } 658 return -1 659 } 660 661 // methodIndex returns the index of and method with matching package and name, or (-1, nil). 662 // See Object.sameId for the meaning of foldCase. 663 func methodIndex(methods []*Func, pkg *Package, name string, foldCase bool) (int, *Func) { 664 if name != "_" { 665 for i, m := range methods { 666 if m.sameId(pkg, name, foldCase) { 667 return i, m 668 } 669 } 670 } 671 return -1, nil 672 } 673