Source file src/go/types/named.go
1 // Code generated by "go test -run=Generate -write=all"; DO NOT EDIT. 2 // Source: ../../cmd/compile/internal/types2/named.go 3 4 // Copyright 2011 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 package types 9 10 import ( 11 "go/token" 12 "strings" 13 "sync" 14 "sync/atomic" 15 ) 16 17 // Type-checking Named types is subtle, because they may be recursively 18 // defined, and because their full details may be spread across multiple 19 // declarations (via methods). For this reason they are type-checked lazily, 20 // to avoid information being accessed before it is complete. 21 // 22 // Conceptually, it is helpful to think of named types as having two distinct 23 // sets of information: 24 // - "LHS" information, defining their identity: Obj() and TypeArgs() 25 // - "RHS" information, defining their details: TypeParams(), Underlying(), 26 // and methods. 27 // 28 // In this taxonomy, LHS information is available immediately, but RHS 29 // information is lazy. Specifically, a named type N may be constructed in any 30 // of the following ways: 31 // 1. type-checked from the source 32 // 2. loaded eagerly from export data 33 // 3. loaded lazily from export data (when using unified IR) 34 // 4. instantiated from a generic type 35 // 36 // In cases 1, 3, and 4, it is possible that the underlying type or methods of 37 // N may not be immediately available. 38 // - During type-checking, we allocate N before type-checking its underlying 39 // type or methods, so that we can create recursive references. 40 // - When loading from export data, we may load its methods and underlying 41 // type lazily using a provided load function. 42 // - After instantiating, we lazily expand the underlying type and methods 43 // (note that instances may be created while still in the process of 44 // type-checking the original type declaration). 45 // 46 // In cases 3 and 4 this lazy construction may also occur concurrently, due to 47 // concurrent use of the type checker API (after type checking or importing has 48 // finished). It is critical that we keep track of state, so that Named types 49 // are constructed exactly once and so that we do not access their details too 50 // soon. 51 // 52 // We achieve this by tracking state with an atomic state variable, and 53 // guarding potentially concurrent calculations with a mutex. See [stateMask] 54 // for details. 55 // 56 // GLOSSARY: Here are a few terms used in this file to describe Named types: 57 // - We say that a Named type is "instantiated" if it has been constructed by 58 // instantiating a generic named type with type arguments. 59 // - We say that a Named type is "declared" if it corresponds to a type 60 // declaration in the source. Instantiated named types correspond to a type 61 // instantiation in the source, not a declaration. But their Origin type is 62 // a declared type. 63 // - We say that a Named type is "unpacked" if its RHS information has been 64 // populated, normalizing its representation for use in type-checking 65 // operations and abstracting away how it was created: 66 // - For a Named type constructed from unified IR, this involves invoking 67 // a lazy loader function to extract details from UIR as needed. 68 // - For an instantiated Named type, this involves extracting information 69 // from its origin and substituting type arguments into a "synthetic" 70 // RHS; this process is called "expanding" the RHS (see below). 71 // - We say that a Named type is "expanded" if it is an instantiated type and 72 // type parameters in its RHS and methods have been substituted with the type 73 // arguments from the instantiation. A type may be partially expanded if some 74 // but not all of these details have been substituted. Similarly, we refer to 75 // these individual details (RHS or method) as being "expanded". 76 // 77 // Some invariants to keep in mind: each declared Named type has a single 78 // corresponding object, and that object's type is the (possibly generic) Named 79 // type. Declared Named types are identical if and only if their pointers are 80 // identical. On the other hand, multiple instantiated Named types may be 81 // identical even though their pointers are not identical. One has to use 82 // Identical to compare them. For instantiated named types, their obj is a 83 // synthetic placeholder that records their position of the corresponding 84 // instantiation in the source (if they were constructed during type checking). 85 // 86 // To prevent infinite expansion of named instances that are created outside of 87 // type-checking, instances share a Context with other instances created during 88 // their expansion. Via the pidgeonhole principle, this guarantees that in the 89 // presence of a cycle of named types, expansion will eventually find an 90 // existing instance in the Context and short-circuit the expansion. 91 // 92 // Once an instance is fully expanded, we can nil out this shared Context to unpin 93 // memory, though the Context may still be held by other incomplete instances 94 // in its "lineage". 95 96 // A Named represents a named (defined) type. 97 // 98 // A declaration such as: 99 // 100 // type S struct { ... } 101 // 102 // creates a defined type whose underlying type is a struct, 103 // and binds this type to the object S, a [TypeName]. 104 // Use [Named.Underlying] to access the underlying type. 105 // Use [Named.Obj] to obtain the object S. 106 // 107 // Before type aliases (Go 1.9), the spec called defined types "named types". 108 type Named struct { 109 check *Checker // non-nil during type-checking; nil otherwise 110 obj *TypeName // corresponding declared object for declared types; see above for instantiated types 111 112 allowNilRHS bool // may be true from creation via [NewNamed] until [Named.SetUnderlying] 113 114 inst *instance // information for instantiated types; nil otherwise 115 116 mu sync.Mutex // guards all fields below 117 state_ uint32 // the current state of this type; must only be accessed atomically or when mu is held 118 fromRHS Type // the declaration RHS this type is derived from 119 tparams *TypeParamList // type parameters, or nil 120 underlying Type // underlying type, or nil 121 varSize bool // whether the type has variable size 122 123 // methods declared for this type (not the method set of this type) 124 // Signatures are type-checked lazily. 125 // For non-instantiated types, this is a fully populated list of methods. For 126 // instantiated types, methods are individually expanded when they are first 127 // accessed. 128 methods []*Func 129 130 // loader may be provided to lazily load type parameters, underlying type, methods, and delayed functions 131 loader func(*Named) ([]*TypeParam, Type, []*Func, []func()) 132 } 133 134 // instance holds information that is only necessary for instantiated named 135 // types. 136 type instance struct { 137 orig *Named // original, uninstantiated type 138 targs *TypeList // type arguments 139 expandedMethods int // number of expanded methods; expandedMethods <= len(orig.methods) 140 ctxt *Context // local Context; set to nil after full expansion 141 } 142 143 // stateMask represents each state in the lifecycle of a named type. 144 // 145 // Each named type begins in the initial state. A named type may transition to a new state 146 // according to the below diagram: 147 // 148 // initial 149 // lazyLoaded 150 // unpacked 151 // └── hasMethods 152 // └── hasUnder 153 // └── hasVarSize 154 // 155 // That is, descent down the tree is mostly linear (initial through unpacked), except upon 156 // reaching the leaves (hasMethods, hasUnder, and hasVarSize). A type may occupy any 157 // combination of the leaf states at once (they are independent states). 158 // 159 // To represent this independence, the set of active states is represented with a bit set. State 160 // transitions are monotonic. Once a state bit is set, it remains set. 161 // 162 // The above constraints significantly narrow the possible bit sets for a named type. With bits 163 // set left-to-right, they are: 164 // 165 // 00000 | initial 166 // 10000 | lazyLoaded 167 // 11000 | unpacked, which implies lazyLoaded 168 // 11100 | hasMethods, which implies unpacked (which in turn implies lazyLoaded) 169 // 11010 | hasUnder, which implies unpacked ... 170 // 11001 | hasVarSize, which implies unpacked ... 171 // 11110 | both hasMethods and hasUnder which implies unpacked ... 172 // ... | (other combinations of leaf states) 173 // 174 // To read the state of a named type, use [Named.stateHas]; to write, use [Named.setState]. 175 type stateMask uint32 176 177 const ( 178 // initially, type parameters, RHS, underlying, and methods might be unavailable 179 lazyLoaded stateMask = 1 << iota // methods are available, but constraints might be unexpanded (for generic types) 180 unpacked // methods might be unexpanded (for instances) 181 hasMethods // methods are all expanded (for instances) 182 hasUnder // underlying type is available 183 hasVarSize // varSize is available 184 ) 185 186 // NewNamed returns a new named type for the given type name, underlying type, and associated methods. 187 // If the given type name obj doesn't have a type yet, its type is set to the returned named type. 188 // The underlying type must not be a *Named. 189 func NewNamed(obj *TypeName, underlying Type, methods []*Func) *Named { 190 if asNamed(underlying) != nil { 191 panic("underlying type must not be *Named") 192 } 193 n := (*Checker)(nil).newNamed(obj, underlying, methods) 194 if underlying == nil { 195 n.allowNilRHS = true 196 } else { 197 n.SetUnderlying(underlying) 198 } 199 return n 200 201 } 202 203 // unpack populates the type parameters, methods, and RHS of n. 204 // 205 // For the purposes of unpacking, there are three categories of named types: 206 // 1. Lazy loaded types 207 // 2. Instantiated types 208 // 3. All others 209 // 210 // Note that the above form a partition. 211 // 212 // Lazy loaded types: 213 // Type parameters, methods, and RHS of n become accessible and are fully 214 // expanded. 215 // 216 // Instantiated types: 217 // Type parameters, methods, and RHS of n become accessible, though methods 218 // are lazily populated as needed. 219 // 220 // All others: 221 // Effectively, nothing happens. 222 func (n *Named) unpack() *Named { 223 if n.stateHas(lazyLoaded | unpacked) { // avoid locking below 224 return n 225 } 226 227 // TODO(rfindley): if n.check is non-nil we can avoid locking here, since 228 // type-checking is not concurrent. Evaluate if this is worth doing. 229 n.mu.Lock() 230 defer n.mu.Unlock() 231 232 // only atomic for consistency; we are holding the mutex 233 if n.stateHas(lazyLoaded | unpacked) { 234 return n 235 } 236 237 if n.inst != nil { 238 assert(n.fromRHS == nil) // instantiated types are not declared types 239 assert(n.loader == nil) // cannot import an instantiation 240 241 orig := n.inst.orig 242 orig.unpack() 243 244 n.fromRHS = n.expandRHS() 245 n.tparams = orig.tparams 246 247 if len(orig.methods) == 0 { 248 n.setState(lazyLoaded | unpacked | hasMethods) // nothing further to do 249 n.inst.ctxt = nil 250 } else { 251 n.setState(lazyLoaded | unpacked) 252 } 253 // underlying comes after unpacking, do not set it 254 assert(!n.stateHas(hasUnder)) 255 return n 256 } 257 258 // TODO(mdempsky): Since we're passing n to the loader anyway 259 // (necessary because types2 expects the receiver type for methods 260 // on defined interface types to be the Named rather than the 261 // underlying Interface), maybe it should just handle calling 262 // SetTypeParams, SetUnderlying, and AddMethod instead? Those 263 // methods would need to support reentrant calls though. It would 264 // also make the API more future-proof towards further extensions. 265 if n.loader != nil { 266 assert(n.fromRHS == nil) // not loaded yet 267 assert(n.inst == nil) // cannot import an instantiation 268 269 tparams, underlying, methods, delayed := n.loader(n) 270 n.loader = nil 271 272 n.tparams = bindTParams(tparams) 273 n.underlying = underlying 274 n.fromRHS = underlying // for cycle detection 275 n.methods = methods 276 277 // Careful: A delayed function could need the underlying type of 278 // the type we are loading, so we must advance to hasUnder to 279 // avoid a deadlock (see go.dev/issue/80258). 280 n.setState(lazyLoaded | unpacked | hasMethods | hasUnder) 281 for _, f := range delayed { 282 f() 283 } 284 return n 285 } 286 287 // underlying comes after unpacking, do not set it 288 n.setState(lazyLoaded | unpacked | hasMethods) 289 assert(!n.stateHas(hasUnder)) 290 return n 291 } 292 293 // stateHas atomically determines whether the current state includes any active bit in sm. 294 func (n *Named) stateHas(m stateMask) bool { 295 return stateMask(atomic.LoadUint32(&n.state_))&m != 0 296 } 297 298 // setState atomically sets the current state to include each active bit in sm. 299 // Must only be called while holding n.mu. 300 func (n *Named) setState(m stateMask) { 301 atomic.OrUint32(&n.state_, uint32(m)) 302 // verify state transitions 303 if debug { 304 m := stateMask(atomic.LoadUint32(&n.state_)) 305 u := m&unpacked != 0 306 // unpacked => lazyLoaded 307 if u { 308 assert(m&lazyLoaded != 0) 309 } 310 // hasMethods => unpacked 311 if m&hasMethods != 0 { 312 assert(u) 313 } 314 // hasUnder => unpacked 315 if m&hasUnder != 0 { 316 assert(u) 317 } 318 // hasVarSize => unpacked 319 if m&hasVarSize != 0 { 320 assert(u) 321 } 322 } 323 } 324 325 // newNamed is like NewNamed but with a *Checker receiver. 326 func (check *Checker) newNamed(obj *TypeName, fromRHS Type, methods []*Func) *Named { 327 typ := &Named{check: check, obj: obj, fromRHS: fromRHS, methods: methods} 328 if obj.typ == nil { 329 obj.typ = typ 330 } 331 // Ensure that typ is always sanity-checked. 332 if check != nil { 333 check.needsCleanup(typ) 334 } 335 return typ 336 } 337 338 // newNamedInstance creates a new named instance for the given origin and type 339 // arguments, recording pos as the position of its synthetic object (for error 340 // reporting). 341 // 342 // If set, expanding is the named type instance currently being expanded, that 343 // led to the creation of this instance. 344 func (check *Checker) newNamedInstance(pos token.Pos, orig *Named, targs []Type, expanding *Named) *Named { 345 assert(len(targs) > 0) 346 347 obj := NewTypeName(pos, orig.obj.pkg, orig.obj.name, nil) 348 inst := &instance{orig: orig, targs: newTypeList(targs)} 349 350 // Only pass the expanding context to the new instance if their packages 351 // match. Since type reference cycles are only possible within a single 352 // package, this is sufficient for the purposes of short-circuiting cycles. 353 // Avoiding passing the context in other cases prevents unnecessary coupling 354 // of types across packages. 355 if expanding != nil && expanding.Obj().pkg == obj.pkg { 356 inst.ctxt = expanding.inst.ctxt 357 } 358 typ := &Named{check: check, obj: obj, inst: inst} 359 obj.typ = typ 360 // Ensure that typ is always sanity-checked. 361 if check != nil { 362 check.needsCleanup(typ) 363 } 364 return typ 365 } 366 367 func (n *Named) cleanup() { 368 // Instances can have a nil underlying at the end of type checking — they 369 // will lazily expand it as needed. All other types must have one. 370 if n.inst == nil { 371 n.Underlying() 372 } 373 n.check = nil 374 } 375 376 // Obj returns the type name for the declaration defining the named type t. For 377 // instantiated types, this is same as the type name of the origin type. 378 func (t *Named) Obj() *TypeName { 379 if t.inst == nil { 380 return t.obj 381 } 382 return t.inst.orig.obj 383 } 384 385 // Origin returns the generic type from which the named type t is 386 // instantiated. If t is not an instantiated type, the result is t. 387 func (t *Named) Origin() *Named { 388 if t.inst == nil { 389 return t 390 } 391 return t.inst.orig 392 } 393 394 // TypeParams returns the type parameters of the named type t, or nil. 395 // The result is non-nil for an (originally) generic type even if it is instantiated. 396 func (t *Named) TypeParams() *TypeParamList { return t.unpack().tparams } 397 398 // SetTypeParams sets the type parameters of the named type t. 399 // t must not have type arguments. 400 func (t *Named) SetTypeParams(tparams []*TypeParam) { 401 assert(t.inst == nil) 402 t.unpack().tparams = bindTParams(tparams) 403 } 404 405 // TypeArgs returns the type arguments used to instantiate the named type t. 406 func (t *Named) TypeArgs() *TypeList { 407 if t.inst == nil { 408 return nil 409 } 410 return t.inst.targs 411 } 412 413 // NumMethods returns the number of explicit methods defined for t. 414 func (t *Named) NumMethods() int { 415 return len(t.Origin().unpack().methods) 416 } 417 418 // Method returns the i'th method of named type t for 0 <= i < t.NumMethods(). 419 // 420 // For an ordinary or instantiated type t, the receiver base type of this method 421 // is the named type t. The returned Func's Signature will not have receiver 422 // type parameters. 423 // 424 // For an uninstantiated generic type t, each method receiver is instantiated with 425 // its receiver type parameters. The returned Func's Signature will have the 426 // receiver type parameters used to instantiate the receiver. 427 // 428 // Methods are numbered deterministically: given the same list of source files 429 // presented to the type checker, or the same sequence of NewMethod and AddMethod 430 // calls, the mapping from method index to corresponding method remains the same. 431 // But the specific ordering is not specified and must not be relied on as it may 432 // change in the future. 433 func (t *Named) Method(i int) *Func { 434 t.unpack() 435 436 if t.stateHas(hasMethods) { 437 return t.methods[i] 438 } 439 440 assert(t.inst != nil) // only instances should have unexpanded methods 441 orig := t.inst.orig 442 443 t.mu.Lock() 444 defer t.mu.Unlock() 445 446 if len(t.methods) != len(orig.methods) { 447 assert(len(t.methods) == 0) 448 t.methods = make([]*Func, len(orig.methods)) 449 } 450 451 if t.methods[i] == nil { 452 assert(t.inst.ctxt != nil) // we should still have a context remaining from the resolution phase 453 t.methods[i] = t.expandMethod(i) 454 t.inst.expandedMethods++ 455 456 // Check if we've created all methods at this point. If we have, mark the 457 // type as having all of its methods. 458 if t.inst.expandedMethods == len(orig.methods) { 459 t.setState(hasMethods) 460 t.inst.ctxt = nil // no need for a context anymore 461 } 462 } 463 464 return t.methods[i] 465 } 466 467 // expandMethod substitutes type arguments in the i'th method for an 468 // instantiated receiver. A returned Func's Signature never has 469 // receiver type parameters. 470 func (t *Named) expandMethod(i int) *Func { 471 // t.orig.methods is not lazy. orig is the declared function on t, which 472 // must have receiver type parameters (since t is generic). 473 orig := t.inst.orig.Method(i) 474 assert(orig != nil) 475 476 check := t.check 477 // Ensure that the original method is type-checked. 478 if check != nil { 479 check.objDecl(orig) 480 } 481 482 oldSig := orig.typ.(*Signature) 483 rtpars := oldSig.rparams.list() 484 rtargs := t.inst.targs.list() 485 486 // Consider: 487 // 488 // type T[P any] struct{} 489 // func (t T[P]) m() { t.m() } 490 // 491 // At t.m, m is expanded for T[P] to get a new Func, which must be different from 492 // the declared Func for the origin method T.m; notably, the Func for t.m lacks 493 // receiver type parameters, since it is instantiated (as opposed to declared) 494 // and thus no longer generic. One must not return the origin method here. 495 496 // We can only substitute if we have a correspondence between type arguments 497 // and type parameters. This check is necessary in the presence of invalid 498 // code. 499 newSig := oldSig 500 if len(rtpars) == len(rtargs) { 501 smap := makeSubstMap(rtpars, rtargs) 502 var ctxt *Context 503 if check != nil { 504 ctxt = check.context() 505 } 506 newSig = check.subst(orig.pos, oldSig, smap, t, ctxt).(*Signature) 507 } 508 509 if newSig == oldSig { 510 // No substitution occurred, but we still need to create a new signature to 511 // hold the instantiated receiver. 512 copy := *oldSig 513 newSig = © 514 } 515 516 var rtyp Type 517 if orig.hasPtrRecv() { 518 rtyp = NewPointer(t) 519 } else { 520 rtyp = t 521 } 522 523 newSig.recv = cloneVar(oldSig.recv, rtyp) 524 newSig.rparams = nil 525 526 return cloneFunc(orig, newSig) 527 } 528 529 // SetUnderlying sets the underlying type and marks t as complete. 530 // t must not have type arguments. 531 func (t *Named) SetUnderlying(u Type) { 532 assert(t.inst == nil) 533 if u == nil { 534 panic("underlying type must not be nil") 535 } 536 if asNamed(u) != nil { 537 panic("underlying type must not be *Named") 538 } 539 // be careful to uphold the state invariants 540 t.mu.Lock() 541 defer t.mu.Unlock() 542 543 t.fromRHS = u 544 t.allowNilRHS = false 545 t.setState(lazyLoaded | unpacked | hasMethods) // TODO(markfreeman): Why hasMethods? 546 547 t.underlying = u 548 t.setState(hasUnder) 549 } 550 551 // AddMethod adds method m unless it is already in the method list. 552 // The method must be in the same package as t, and t must not have 553 // type arguments. 554 func (t *Named) AddMethod(m *Func) { 555 assert(samePkg(t.obj.pkg, m.pkg)) 556 assert(t.inst == nil) 557 t.unpack() 558 if t.methodIndex(m.name, false) < 0 { 559 t.methods = append(t.methods, m) 560 } 561 } 562 563 // methodIndex returns the index of the method with the given name. 564 // If foldCase is set, capitalization in the name is ignored. 565 // The result is negative if no such method exists. 566 func (t *Named) methodIndex(name string, foldCase bool) int { 567 if name == "_" { 568 return -1 569 } 570 if foldCase { 571 for i, m := range t.methods { 572 if strings.EqualFold(m.name, name) { 573 return i 574 } 575 } 576 } else { 577 for i, m := range t.methods { 578 if m.name == name { 579 return i 580 } 581 } 582 } 583 return -1 584 } 585 586 // rhs returns [Named.fromRHS]. 587 // 588 // In debug mode, it also asserts that n is in an appropriate state. 589 func (n *Named) rhs() Type { 590 if debug { 591 assert(n.stateHas(lazyLoaded | unpacked)) 592 } 593 return n.fromRHS 594 } 595 596 // Underlying returns the [underlying type] of the named type t, resolving all 597 // forwarding declarations. Underlying types are never Named, TypeParam, or 598 // Alias types. 599 // 600 // [underlying type]: https://go.dev/ref/spec#Underlying_types. 601 func (n *Named) Underlying() Type { 602 n.unpack() 603 604 // The gccimporter depends on writing a nil underlying via NewNamed and 605 // immediately reading it back. Rather than putting that in Named.under 606 // and complicating things there, we just check for that special case here. 607 if n.rhs() == nil { 608 assert(n.allowNilRHS) 609 return nil 610 } 611 612 if !n.stateHas(hasUnder) { // minor performance optimization 613 n.resolveUnderlying() 614 } 615 616 return n.underlying 617 } 618 619 func (t *Named) String() string { return TypeString(t, nil) } 620 621 // ---------------------------------------------------------------------------- 622 // Implementation 623 // 624 // TODO(rfindley): reorganize the loading and expansion methods under this 625 // heading. 626 627 // resolveUnderlying computes the underlying type of n. If n already has an 628 // underlying type, nothing happens. 629 // 630 // It does so by following RHS type chains for alias and named types. If any 631 // other type T is found, each named type in the chain has its underlying 632 // type set to T. Aliases are skipped because their underlying type is 633 // not memoized. 634 // 635 // resolveUnderlying assumes that there are no direct cycles; if there were 636 // any, they were broken (by setting the respective types to invalid) during 637 // the directCycles check phase. 638 func (n *Named) resolveUnderlying() { 639 assert(n.stateHas(lazyLoaded | unpacked)) 640 641 var seen map[*Named]bool // for debugging only 642 if debug { 643 seen = make(map[*Named]bool) 644 } 645 646 var path []*Named 647 var u Type 648 for rhs := Type(n); u == nil; { 649 switch t := rhs.(type) { 650 case *Alias: 651 rhs = unalias(t) 652 653 case *Named: 654 if debug { 655 assert(!seen[t]) 656 seen[t] = true 657 } 658 659 // don't recalculate the underlying 660 if t.stateHas(hasUnder) { 661 u = t.underlying 662 break 663 } 664 665 if debug { 666 seen[t] = true 667 } 668 path = append(path, t) 669 670 t.unpack() 671 rhs = t.rhs() 672 assert(rhs != nil) 673 674 default: 675 u = rhs // any type literal or predeclared type works 676 } 677 } 678 679 for _, t := range path { 680 func() { 681 t.mu.Lock() 682 defer t.mu.Unlock() 683 // Careful, t.underlying has lock-free readers. Since we might be racing 684 // another call to resolveUnderlying, we have to avoid overwriting 685 // t.underlying. Otherwise, the race detector will be tripped. 686 if !t.stateHas(hasUnder) { 687 t.underlying = u 688 t.setState(hasUnder) 689 } 690 }() 691 } 692 } 693 694 func (n *Named) lookupMethod(pkg *Package, name string, foldCase bool) (int, *Func) { 695 n.unpack() 696 if samePkg(n.obj.pkg, pkg) || isExported(name) || foldCase { 697 // If n is an instance, we may not have yet instantiated all of its methods. 698 // Look up the method index in orig, and only instantiate method at the 699 // matching index (if any). 700 if i := n.Origin().methodIndex(name, foldCase); i >= 0 { 701 // For instances, m.Method(i) will be different from the orig method. 702 return i, n.Method(i) 703 } 704 } 705 return -1, nil 706 } 707 708 // context returns the type-checker context. 709 func (check *Checker) context() *Context { 710 if check.ctxt == nil { 711 check.ctxt = NewContext() 712 } 713 return check.ctxt 714 } 715 716 // expandRHS crafts a synthetic RHS for an instantiated type using the RHS of 717 // its origin type (which must be a generic type). 718 // 719 // Suppose that we had: 720 // 721 // type T[P any] struct { 722 // f P 723 // } 724 // 725 // type U T[int] 726 // 727 // When we go to U, we observe T[int]. Since T[int] is an instantiation, it has no 728 // declaration. Here, we craft a synthetic RHS for T[int] as if it were declared, 729 // somewhat similar to: 730 // 731 // type T[int] struct { 732 // f int 733 // } 734 // 735 // And note that the synthetic RHS here is the same as the underlying for U. Now, 736 // consider: 737 // 738 // type T[_ any] U 739 // type U int 740 // type V T[U] 741 // 742 // The synthetic RHS for T[U] becomes: 743 // 744 // type T[U] U 745 // 746 // Whereas the underlying of V is int, not U. 747 func (n *Named) expandRHS() (rhs Type) { 748 check := n.check 749 if check != nil && check.conf._Trace { 750 check.trace(n.obj.pos, "-- Named.expandRHS %s", n) 751 check.indent++ 752 defer func() { 753 check.indent-- 754 check.trace(n.obj.pos, "=> %s (rhs = %s)", n, rhs) 755 }() 756 } 757 758 assert(!n.stateHas(unpacked)) 759 assert(n.inst.orig.stateHas(lazyLoaded | unpacked)) 760 761 if n.inst.ctxt == nil { 762 n.inst.ctxt = NewContext() 763 } 764 765 ctxt := n.inst.ctxt 766 orig := n.inst.orig 767 768 targs := n.inst.targs 769 tpars := orig.tparams 770 771 if targs.Len() != tpars.Len() { 772 return Typ[Invalid] 773 } 774 775 h := ctxt.instanceHash(orig, targs.list()) 776 u := ctxt.update(h, orig, targs.list(), n) // block fixed point infinite instantiation 777 assert(n == u) 778 779 m := makeSubstMap(tpars.list(), targs.list()) 780 if check != nil { 781 ctxt = check.context() 782 } 783 784 rhs = check.subst(n.obj.pos, orig.rhs(), m, n, ctxt) 785 786 // TODO(markfreeman): Can we handle this in substitution? 787 // If the RHS is an interface, we must set the receiver of interface methods 788 // to the named type. 789 if iface, _ := rhs.(*Interface); iface != nil { 790 if methods, copied := replaceRecvType(iface.methods, orig, n); copied { 791 // If the RHS doesn't use type parameters, it may not have been 792 // substituted; we need to craft a new interface first. 793 if iface == orig.rhs() { 794 assert(iface.complete) // otherwise we are copying incomplete data 795 796 crafted := check.newInterface() 797 crafted.complete = true 798 crafted.implicit = false 799 crafted.embeddeds = iface.embeddeds 800 801 iface = crafted 802 } 803 iface.methods = methods 804 iface.tset = nil // recompute type set with new methods 805 806 // go.dev/issue/61561: We have to complete the interface even without a checker. 807 if check == nil { 808 iface.typeSet() 809 } 810 811 return iface 812 } 813 } 814 815 return rhs 816 } 817 818 // safeUnderlying returns the underlying type of typ without expanding 819 // instances, to avoid infinite recursion. 820 // 821 // TODO(rfindley): eliminate this function or give it a better name. 822 func safeUnderlying(typ Type) Type { 823 if t := asNamed(typ); t != nil { 824 return t.underlying 825 } 826 return typ.Underlying() 827 } 828