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