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