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