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 nointerface 397 ) 398 399 state := ok 400 var m *Func // method on T we're trying to implement 401 var f *Func // method on V, if found (state is one of ok, wrongName, wrongSig) 402 403 if u, _ := V.Underlying().(*Interface); u != nil { 404 tset := u.typeSet() 405 for _, m = range methods { 406 _, f = tset.LookupMethod(m.pkg, m.name, false) 407 408 if f == nil { 409 if !static { 410 continue 411 } 412 state = notFound 413 break 414 } 415 416 if !equivalent(f.typ, m.typ) { 417 state = wrongSig 418 break 419 } 420 } 421 } else { 422 for _, m = range methods { 423 obj, index, indirect := lookupFieldOrMethodImpl(V, false, m.pkg, m.name, false) 424 425 // check if m is ambiguous, on *V, or on V with case-folding 426 if obj == nil { 427 switch { 428 case index != nil: 429 state = ambigSel 430 case indirect: 431 state = ptrRecv 432 default: 433 state = notFound 434 obj, _, _ = lookupFieldOrMethodImpl(V, false, m.pkg, m.name, true /* fold case */) 435 f, _ = obj.(*Func) 436 if f != nil { 437 state = wrongName 438 if f.name == m.name { 439 // If the names are equal, f must be unexported 440 // (otherwise the package wouldn't matter). 441 state = unexported 442 } 443 } 444 } 445 break 446 } 447 448 // we must have a method (not a struct field) 449 f, _ = obj.(*Func) 450 if f == nil { 451 state = field 452 break 453 } 454 455 // methods may not have a fully set up signature yet 456 if check != nil { 457 check.objDecl(f) 458 } 459 460 if f.nointerface { 461 state = nointerface 462 break 463 } 464 465 if !equivalent(f.typ, m.typ) { 466 state = wrongSig 467 break 468 } 469 } 470 } 471 472 if state == ok { 473 return nil, false 474 } 475 476 if cause != nil { 477 if f != nil { 478 // This method may be formatted in funcString below, so must have a fully 479 // set up signature. 480 if check != nil { 481 check.objDecl(f) 482 } 483 } 484 switch state { 485 case notFound: 486 switch { 487 case isInterfacePtr(V): 488 *cause = "(" + check.interfacePtrError(V) + ")" 489 case isInterfacePtr(T): 490 *cause = "(" + check.interfacePtrError(T) + ")" 491 default: 492 *cause = check.sprintf("(missing method %s)", m.Name()) 493 } 494 case wrongName: 495 fs, ms := check.funcString(f, false), check.funcString(m, false) 496 *cause = check.sprintf("(missing method %s)\n\t\thave %s\n\t\twant %s", m.Name(), fs, ms) 497 case unexported: 498 *cause = check.sprintf("(unexported method %s)", m.Name()) 499 case wrongSig: 500 fs, ms := check.funcString(f, false), check.funcString(m, false) 501 if fs == ms { 502 // Don't report "want Foo, have Foo". 503 // Add package information to disambiguate (go.dev/issue/54258). 504 fs, ms = check.funcString(f, true), check.funcString(m, true) 505 } 506 if fs == ms { 507 // We still have "want Foo, have Foo". 508 // This is most likely due to different type parameters with 509 // the same name appearing in the instantiated signatures 510 // (go.dev/issue/61685). 511 // Rather than reporting this misleading error cause, for now 512 // just point out that the method signature is incorrect. 513 // TODO(gri) should find a good way to report the root cause 514 *cause = check.sprintf("(wrong type for method %s)", m.Name()) 515 break 516 } 517 *cause = check.sprintf("(wrong type for method %s)\n\t\thave %s\n\t\twant %s", m.Name(), fs, ms) 518 case ambigSel: 519 *cause = check.sprintf("(ambiguous selector %s.%s)", V, m.Name()) 520 case ptrRecv: 521 *cause = check.sprintf("(method %s has pointer receiver)", m.Name()) 522 case field: 523 *cause = check.sprintf("(%s.%s is a field, not a method)", V, m.Name()) 524 case nointerface: 525 *cause = check.sprintf("(%s method is marked 'nointerface')", m.Name()) 526 default: 527 panic("unreachable") 528 } 529 } 530 531 return m, state == wrongSig || state == ptrRecv 532 } 533 534 // hasAllMethods is similar to checkMissingMethod but instead reports whether all methods are present. 535 // If V is not a valid type, or if it is a struct containing embedded fields with invalid types, the 536 // result is true because it is not possible to say with certainty whether a method is missing or not 537 // (an embedded field may have the method in question). 538 // If the result is false and cause is not nil, *cause describes the error. 539 // Use hasAllMethods to avoid follow-on errors due to incorrect types. 540 func (check *Checker) hasAllMethods(V, T Type, static bool, equivalent func(x, y Type) bool, cause *string) bool { 541 if !isValid(V) { 542 return true // we don't know anything about V, assume it implements T 543 } 544 m, _ := check.missingMethod(V, T, static, equivalent, cause) 545 return m == nil || hasInvalidEmbeddedFields(V, nil) 546 } 547 548 // hasInvalidEmbeddedFields reports whether T is a struct (or a pointer to a struct) that contains 549 // (directly or indirectly) embedded fields with invalid types. 550 func hasInvalidEmbeddedFields(T Type, seen map[*Struct]bool) bool { 551 if S, _ := derefStructPtr(T).Underlying().(*Struct); S != nil && !seen[S] { 552 if seen == nil { 553 seen = make(map[*Struct]bool) 554 } 555 seen[S] = true 556 for _, f := range S.fields { 557 if f.embedded && (!isValid(f.typ) || hasInvalidEmbeddedFields(f.typ, seen)) { 558 return true 559 } 560 } 561 } 562 return false 563 } 564 565 func isInterfacePtr(T Type) bool { 566 p, _ := T.Underlying().(*Pointer) 567 return p != nil && IsInterface(p.base) 568 } 569 570 // check may be nil. 571 func (check *Checker) interfacePtrError(T Type) string { 572 assert(isInterfacePtr(T)) 573 if p, _ := T.Underlying().(*Pointer); isTypeParam(p.base) { 574 return check.sprintf("type %s is pointer to type parameter, not type parameter", T) 575 } 576 return check.sprintf("type %s is pointer to interface, not interface", T) 577 } 578 579 // funcString returns a string of the form name + signature for f. 580 // check may be nil. 581 func (check *Checker) funcString(f *Func, pkgInfo bool) string { 582 buf := bytes.NewBufferString(f.name) 583 var qf Qualifier 584 if check != nil && !pkgInfo { 585 qf = check.qualifier 586 } 587 w := newTypeWriter(buf, qf) 588 w.pkgInfo = pkgInfo 589 w.paramNames = false 590 w.signature(f.typ.(*Signature)) 591 return buf.String() 592 } 593 594 // assertableTo reports whether a value of type V can be asserted to have type T. 595 // The receiver may be nil if assertableTo is invoked through an exported API call 596 // (such as AssertableTo), i.e., when all methods have been type-checked. 597 // The underlying type of V must be an interface. 598 // If the result is false and cause is not nil, *cause describes the error. 599 // TODO(gri) replace calls to this function with calls to newAssertableTo. 600 func (check *Checker) assertableTo(V, T Type, cause *string) bool { 601 // no static check is required if T is an interface 602 // spec: "If T is an interface type, x.(T) asserts that the 603 // dynamic type of x implements the interface T." 604 if IsInterface(T) { 605 return true 606 } 607 // TODO(gri) fix this for generalized interfaces 608 return check.hasAllMethods(T, V, false, Identical, cause) 609 } 610 611 // newAssertableTo reports whether a value of type V can be asserted to have type T. 612 // It also implements behavior for interfaces that currently are only permitted 613 // in constraint position (we have not yet defined that behavior in the spec). 614 // The underlying type of V must be an interface. 615 // If the result is false and cause is not nil, *cause is set to the error cause. 616 func (check *Checker) newAssertableTo(V, T Type, cause *string) bool { 617 // no static check is required if T is an interface 618 // spec: "If T is an interface type, x.(T) asserts that the 619 // dynamic type of x implements the interface T." 620 if IsInterface(T) { 621 return true 622 } 623 return check.implements(T, V, false, cause) 624 } 625 626 // deref dereferences typ if it is a *Pointer (but not a *Named type 627 // with an underlying pointer type!) and returns its base and true. 628 // Otherwise it returns (typ, false). 629 func deref(typ Type) (Type, bool) { 630 if p, _ := Unalias(typ).(*Pointer); p != nil { 631 // p.base should never be nil, but be conservative 632 if p.base == nil { 633 if debug { 634 panic("pointer with nil base type (possibly due to an invalid cyclic declaration)") 635 } 636 return Typ[Invalid], true 637 } 638 return p.base, true 639 } 640 return typ, false 641 } 642 643 // derefStructPtr dereferences typ if it is a (named or unnamed) pointer to a 644 // (named or unnamed) struct and returns its base. Otherwise it returns typ. 645 func derefStructPtr(typ Type) Type { 646 if p, _ := typ.Underlying().(*Pointer); p != nil { 647 if _, ok := p.base.Underlying().(*Struct); ok { 648 return p.base 649 } 650 } 651 return typ 652 } 653 654 // concat returns the result of concatenating list and i. 655 // The result does not share its underlying array with list. 656 func concat(list []int, i int) []int { 657 var t []int 658 t = append(t, list...) 659 return append(t, i) 660 } 661 662 // methodIndex returns the index of and method with matching package and name, or (-1, nil). 663 // See Object.sameId for the meaning of foldCase. 664 func methodIndex(methods []*Func, pkg *Package, name string, foldCase bool) (int, *Func) { 665 if name != "_" { 666 for i, m := range methods { 667 if m.sameId(pkg, name, foldCase) { 668 return i, m 669 } 670 } 671 } 672 return -1, nil 673 } 674 675 // Given a (possibly pointer to a) struct type and field index sequence, 676 // fieldPath returns the dot-separated concatenated field names for the 677 // given index sequence (e.g. "a.b.c"). 678 // Use for error reporting etc. where speed is not important. 679 func fieldPath(typ Type, index []int) string { 680 var names []string 681 for _, i := range index { 682 u, ok := derefStructPtr(typ).Underlying().(*Struct) 683 if !ok { 684 // should not happen if index is valid for typ 685 break 686 } 687 fld := u.Field(i) 688 names = append(names, fld.name) 689 typ = fld.typ 690 } 691 return strings.Join(names, ".") 692 } 693