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 // underlying comes after unpacking, do not set it 238 defer (func() { assert(!n.stateHas(hasUnder)) })() 239 240 if n.inst != nil { 241 assert(n.fromRHS == nil) // instantiated types are not declared types 242 assert(n.loader == nil) // cannot import an instantiation 243 244 orig := n.inst.orig 245 orig.unpack() 246 247 n.fromRHS = n.expandRHS() 248 n.tparams = orig.tparams 249 250 if len(orig.methods) == 0 { 251 n.setState(lazyLoaded | unpacked | hasMethods) // nothing further to do 252 n.inst.ctxt = nil 253 } else { 254 n.setState(lazyLoaded | unpacked) 255 } 256 return n 257 } 258 259 // TODO(mdempsky): Since we're passing n to the loader anyway 260 // (necessary because types2 expects the receiver type for methods 261 // on defined interface types to be the Named rather than the 262 // underlying Interface), maybe it should just handle calling 263 // SetTypeParams, SetUnderlying, and AddMethod instead? Those 264 // methods would need to support reentrant calls though. It would 265 // also make the API more future-proof towards further extensions. 266 if n.loader != nil { 267 assert(n.fromRHS == nil) // not loaded yet 268 assert(n.inst == nil) // cannot import an instantiation 269 270 tparams, underlying, methods, delayed := n.loader(n) 271 n.loader = nil 272 273 n.tparams = bindTParams(tparams) 274 n.fromRHS = underlying // for cycle detection 275 n.methods = methods 276 277 n.setState(lazyLoaded) // avoid deadlock calling delayed functions 278 for _, f := range delayed { 279 f() 280 } 281 } 282 283 n.setState(lazyLoaded | unpacked | hasMethods) 284 return n 285 } 286 287 // stateHas atomically determines whether the current state includes any active bit in sm. 288 func (n *Named) stateHas(m stateMask) bool { 289 return stateMask(atomic.LoadUint32(&n.state_))&m != 0 290 } 291 292 // setState atomically sets the current state to include each active bit in sm. 293 // Must only be called while holding n.mu. 294 func (n *Named) setState(m stateMask) { 295 atomic.OrUint32(&n.state_, uint32(m)) 296 // verify state transitions 297 if debug { 298 m := stateMask(atomic.LoadUint32(&n.state_)) 299 u := m&unpacked != 0 300 // unpacked => lazyLoaded 301 if u { 302 assert(m&lazyLoaded != 0) 303 } 304 // hasMethods => unpacked 305 if m&hasMethods != 0 { 306 assert(u) 307 } 308 // hasUnder => unpacked 309 if m&hasUnder != 0 { 310 assert(u) 311 } 312 // hasVarSize => unpacked 313 if m&hasVarSize != 0 { 314 assert(u) 315 } 316 } 317 } 318 319 // newNamed is like NewNamed but with a *Checker receiver. 320 func (check *Checker) newNamed(obj *TypeName, fromRHS Type, methods []*Func) *Named { 321 typ := &Named{check: check, obj: obj, fromRHS: fromRHS, methods: methods} 322 if obj.typ == nil { 323 obj.typ = typ 324 } 325 // Ensure that typ is always sanity-checked. 326 if check != nil { 327 check.needsCleanup(typ) 328 } 329 return typ 330 } 331 332 // newNamedInstance creates a new named instance for the given origin and type 333 // arguments, recording pos as the position of its synthetic object (for error 334 // reporting). 335 // 336 // If set, expanding is the named type instance currently being expanded, that 337 // led to the creation of this instance. 338 func (check *Checker) newNamedInstance(pos token.Pos, orig *Named, targs []Type, expanding *Named) *Named { 339 assert(len(targs) > 0) 340 341 obj := NewTypeName(pos, orig.obj.pkg, orig.obj.name, nil) 342 inst := &instance{orig: orig, targs: newTypeList(targs)} 343 344 // Only pass the expanding context to the new instance if their packages 345 // match. Since type reference cycles are only possible within a single 346 // package, this is sufficient for the purposes of short-circuiting cycles. 347 // Avoiding passing the context in other cases prevents unnecessary coupling 348 // of types across packages. 349 if expanding != nil && expanding.Obj().pkg == obj.pkg { 350 inst.ctxt = expanding.inst.ctxt 351 } 352 typ := &Named{check: check, obj: obj, inst: inst} 353 obj.typ = typ 354 // Ensure that typ is always sanity-checked. 355 if check != nil { 356 check.needsCleanup(typ) 357 } 358 return typ 359 } 360 361 func (n *Named) cleanup() { 362 // Instances can have a nil underlying at the end of type checking — they 363 // will lazily expand it as needed. All other types must have one. 364 if n.inst == nil { 365 n.Underlying() 366 } 367 n.check = nil 368 } 369 370 // Obj returns the type name for the declaration defining the named type t. For 371 // instantiated types, this is same as the type name of the origin type. 372 func (t *Named) Obj() *TypeName { 373 if t.inst == nil { 374 return t.obj 375 } 376 return t.inst.orig.obj 377 } 378 379 // Origin returns the generic type from which the named type t is 380 // instantiated. If t is not an instantiated type, the result is t. 381 func (t *Named) Origin() *Named { 382 if t.inst == nil { 383 return t 384 } 385 return t.inst.orig 386 } 387 388 // TypeParams returns the type parameters of the named type t, or nil. 389 // The result is non-nil for an (originally) generic type even if it is instantiated. 390 func (t *Named) TypeParams() *TypeParamList { return t.unpack().tparams } 391 392 // SetTypeParams sets the type parameters of the named type t. 393 // t must not have type arguments. 394 func (t *Named) SetTypeParams(tparams []*TypeParam) { 395 assert(t.inst == nil) 396 t.unpack().tparams = bindTParams(tparams) 397 } 398 399 // TypeArgs returns the type arguments used to instantiate the named type t. 400 func (t *Named) TypeArgs() *TypeList { 401 if t.inst == nil { 402 return nil 403 } 404 return t.inst.targs 405 } 406 407 // NumMethods returns the number of explicit methods defined for t. 408 func (t *Named) NumMethods() int { 409 return len(t.Origin().unpack().methods) 410 } 411 412 // Method returns the i'th method of named type t for 0 <= i < t.NumMethods(). 413 // 414 // For an ordinary or instantiated type t, the receiver base type of this method 415 // is the named type t. The returned Func's Signature will not have receiver 416 // type parameters. 417 // 418 // For an uninstantiated generic type t, each method receiver is instantiated with 419 // its receiver type parameters. The returned Func's Signature will have the 420 // receiver type parameters used to instantiate the receiver. 421 // 422 // Methods are numbered deterministically: given the same list of source files 423 // presented to the type checker, or the same sequence of NewMethod and AddMethod 424 // calls, the mapping from method index to corresponding method remains the same. 425 // But the specific ordering is not specified and must not be relied on as it may 426 // change in the future. 427 func (t *Named) Method(i int) *Func { 428 t.unpack() 429 430 if t.stateHas(hasMethods) { 431 return t.methods[i] 432 } 433 434 assert(t.inst != nil) // only instances should have unexpanded methods 435 orig := t.inst.orig 436 437 t.mu.Lock() 438 defer t.mu.Unlock() 439 440 if len(t.methods) != len(orig.methods) { 441 assert(len(t.methods) == 0) 442 t.methods = make([]*Func, len(orig.methods)) 443 } 444 445 if t.methods[i] == nil { 446 assert(t.inst.ctxt != nil) // we should still have a context remaining from the resolution phase 447 t.methods[i] = t.expandMethod(i) 448 t.inst.expandedMethods++ 449 450 // Check if we've created all methods at this point. If we have, mark the 451 // type as having all of its methods. 452 if t.inst.expandedMethods == len(orig.methods) { 453 t.setState(hasMethods) 454 t.inst.ctxt = nil // no need for a context anymore 455 } 456 } 457 458 return t.methods[i] 459 } 460 461 // expandMethod substitutes type arguments in the i'th method for an 462 // instantiated receiver. A returned Func's Signature never has 463 // receiver type parameters. 464 func (t *Named) expandMethod(i int) *Func { 465 // t.orig.methods is not lazy. orig is the declared function on t, which 466 // must have receiver type parameters (since t is generic). 467 orig := t.inst.orig.Method(i) 468 assert(orig != nil) 469 470 check := t.check 471 // Ensure that the original method is type-checked. 472 if check != nil { 473 check.objDecl(orig) 474 } 475 476 oldSig := orig.typ.(*Signature) 477 rtpars := oldSig.rparams.list() 478 rtargs := t.inst.targs.list() 479 480 // Consider: 481 // 482 // type T[P any] struct{} 483 // func (t T[P]) m() { t.m() } 484 // 485 // At t.m, m is expanded for T[P] to get a new Func, which must be different from 486 // the declared Func for the origin method T.m; notably, the Func for t.m lacks 487 // receiver type parameters, since it is instantiated (as opposed to declared) 488 // and thus no longer generic. One must not return the origin method here. 489 490 // We can only substitute if we have a correspondence between type arguments 491 // and type parameters. This check is necessary in the presence of invalid 492 // code. 493 newSig := oldSig 494 if len(rtpars) == len(rtargs) { 495 smap := makeSubstMap(rtpars, rtargs) 496 var ctxt *Context 497 if check != nil { 498 ctxt = check.context() 499 } 500 newSig = check.subst(orig.pos, oldSig, smap, t, ctxt).(*Signature) 501 } 502 503 if newSig == oldSig { 504 // No substitution occurred, but we still need to create a new signature to 505 // hold the instantiated receiver. 506 copy := *oldSig 507 newSig = © 508 } 509 510 var rtyp Type 511 if orig.hasPtrRecv() { 512 rtyp = NewPointer(t) 513 } else { 514 rtyp = t 515 } 516 517 newSig.recv = cloneVar(oldSig.recv, rtyp) 518 newSig.rparams = nil 519 520 return cloneFunc(orig, newSig) 521 } 522 523 // SetUnderlying sets the underlying type and marks t as complete. 524 // t must not have type arguments. 525 func (t *Named) SetUnderlying(u Type) { 526 assert(t.inst == nil) 527 if u == nil { 528 panic("underlying type must not be nil") 529 } 530 if asNamed(u) != nil { 531 panic("underlying type must not be *Named") 532 } 533 // be careful to uphold the state invariants 534 t.mu.Lock() 535 defer t.mu.Unlock() 536 537 t.fromRHS = u 538 t.allowNilRHS = false 539 t.setState(lazyLoaded | unpacked | hasMethods) // TODO(markfreeman): Why hasMethods? 540 541 t.underlying = u 542 t.setState(hasUnder) 543 } 544 545 // AddMethod adds method m unless it is already in the method list. 546 // The method must be in the same package as t, and t must not have 547 // type arguments. 548 func (t *Named) AddMethod(m *Func) { 549 assert(samePkg(t.obj.pkg, m.pkg)) 550 assert(t.inst == nil) 551 t.unpack() 552 if t.methodIndex(m.name, false) < 0 { 553 t.methods = append(t.methods, m) 554 } 555 } 556 557 // methodIndex returns the index of the method with the given name. 558 // If foldCase is set, capitalization in the name is ignored. 559 // The result is negative if no such method exists. 560 func (t *Named) methodIndex(name string, foldCase bool) int { 561 if name == "_" { 562 return -1 563 } 564 if foldCase { 565 for i, m := range t.methods { 566 if strings.EqualFold(m.name, name) { 567 return i 568 } 569 } 570 } else { 571 for i, m := range t.methods { 572 if m.name == name { 573 return i 574 } 575 } 576 } 577 return -1 578 } 579 580 // rhs returns [Named.fromRHS]. 581 // 582 // In debug mode, it also asserts that n is in an appropriate state. 583 func (n *Named) rhs() Type { 584 if debug { 585 assert(n.stateHas(lazyLoaded | unpacked)) 586 } 587 return n.fromRHS 588 } 589 590 // Underlying returns the [underlying type] of the named type t, resolving all 591 // forwarding declarations. Underlying types are never Named, TypeParam, or 592 // Alias types. 593 // 594 // [underlying type]: https://go.dev/ref/spec#Underlying_types. 595 func (n *Named) Underlying() Type { 596 n.unpack() 597 598 // The gccimporter depends on writing a nil underlying via NewNamed and 599 // immediately reading it back. Rather than putting that in Named.under 600 // and complicating things there, we just check for that special case here. 601 if n.rhs() == nil { 602 assert(n.allowNilRHS) 603 return nil 604 } 605 606 if !n.stateHas(hasUnder) { // minor performance optimization 607 n.resolveUnderlying() 608 } 609 610 return n.underlying 611 } 612 613 func (t *Named) String() string { return TypeString(t, nil) } 614 615 // ---------------------------------------------------------------------------- 616 // Implementation 617 // 618 // TODO(rfindley): reorganize the loading and expansion methods under this 619 // heading. 620 621 // resolveUnderlying computes the underlying type of n. If n already has an 622 // underlying type, nothing happens. 623 // 624 // It does so by following RHS type chains for alias and named types. If any 625 // other type T is found, each named type in the chain has its underlying 626 // type set to T. Aliases are skipped because their underlying type is 627 // not memoized. 628 // 629 // resolveUnderlying assumes that there are no direct cycles; if there were 630 // any, they were broken (by setting the respective types to invalid) during 631 // the directCycles check phase. 632 func (n *Named) resolveUnderlying() { 633 assert(n.stateHas(lazyLoaded | unpacked)) 634 635 var seen map[*Named]bool // for debugging only 636 if debug { 637 seen = make(map[*Named]bool) 638 } 639 640 var path []*Named 641 var u Type 642 for rhs := Type(n); u == nil; { 643 switch t := rhs.(type) { 644 case *Alias: 645 rhs = unalias(t) 646 647 case *Named: 648 if debug { 649 assert(!seen[t]) 650 seen[t] = true 651 } 652 653 // don't recalculate the underlying 654 if t.stateHas(hasUnder) { 655 u = t.underlying 656 break 657 } 658 659 if debug { 660 seen[t] = true 661 } 662 path = append(path, t) 663 664 t.unpack() 665 rhs = t.rhs() 666 assert(rhs != nil) 667 668 default: 669 u = rhs // any type literal or predeclared type works 670 } 671 } 672 673 for _, t := range path { 674 func() { 675 t.mu.Lock() 676 defer t.mu.Unlock() 677 // Careful, t.underlying has lock-free readers. Since we might be racing 678 // another call to resolveUnderlying, we have to avoid overwriting 679 // t.underlying. Otherwise, the race detector will be tripped. 680 if !t.stateHas(hasUnder) { 681 t.underlying = u 682 t.setState(hasUnder) 683 } 684 }() 685 } 686 } 687 688 func (n *Named) lookupMethod(pkg *Package, name string, foldCase bool) (int, *Func) { 689 n.unpack() 690 if samePkg(n.obj.pkg, pkg) || isExported(name) || foldCase { 691 // If n is an instance, we may not have yet instantiated all of its methods. 692 // Look up the method index in orig, and only instantiate method at the 693 // matching index (if any). 694 if i := n.Origin().methodIndex(name, foldCase); i >= 0 { 695 // For instances, m.Method(i) will be different from the orig method. 696 return i, n.Method(i) 697 } 698 } 699 return -1, nil 700 } 701 702 // context returns the type-checker context. 703 func (check *Checker) context() *Context { 704 if check.ctxt == nil { 705 check.ctxt = NewContext() 706 } 707 return check.ctxt 708 } 709 710 // expandRHS crafts a synthetic RHS for an instantiated type using the RHS of 711 // its origin type (which must be a generic type). 712 // 713 // Suppose that we had: 714 // 715 // type T[P any] struct { 716 // f P 717 // } 718 // 719 // type U T[int] 720 // 721 // When we go to U, we observe T[int]. Since T[int] is an instantiation, it has no 722 // declaration. Here, we craft a synthetic RHS for T[int] as if it were declared, 723 // somewhat similar to: 724 // 725 // type T[int] struct { 726 // f int 727 // } 728 // 729 // And note that the synthetic RHS here is the same as the underlying for U. Now, 730 // consider: 731 // 732 // type T[_ any] U 733 // type U int 734 // type V T[U] 735 // 736 // The synthetic RHS for T[U] becomes: 737 // 738 // type T[U] U 739 // 740 // Whereas the underlying of V is int, not U. 741 func (n *Named) expandRHS() (rhs Type) { 742 check := n.check 743 if check != nil && check.conf._Trace { 744 check.trace(n.obj.pos, "-- Named.expandRHS %s", n) 745 check.indent++ 746 defer func() { 747 check.indent-- 748 check.trace(n.obj.pos, "=> %s (rhs = %s)", n, rhs) 749 }() 750 } 751 752 assert(!n.stateHas(unpacked)) 753 assert(n.inst.orig.stateHas(lazyLoaded | unpacked)) 754 755 if n.inst.ctxt == nil { 756 n.inst.ctxt = NewContext() 757 } 758 759 ctxt := n.inst.ctxt 760 orig := n.inst.orig 761 762 targs := n.inst.targs 763 tpars := orig.tparams 764 765 if targs.Len() != tpars.Len() { 766 return Typ[Invalid] 767 } 768 769 h := ctxt.instanceHash(orig, targs.list()) 770 u := ctxt.update(h, orig, targs.list(), n) // block fixed point infinite instantiation 771 assert(n == u) 772 773 m := makeSubstMap(tpars.list(), targs.list()) 774 if check != nil { 775 ctxt = check.context() 776 } 777 778 rhs = check.subst(n.obj.pos, orig.rhs(), m, n, ctxt) 779 780 // TODO(markfreeman): Can we handle this in substitution? 781 // If the RHS is an interface, we must set the receiver of interface methods 782 // to the named type. 783 if iface, _ := rhs.(*Interface); iface != nil { 784 if methods, copied := replaceRecvType(iface.methods, orig, n); copied { 785 // If the RHS doesn't use type parameters, it may not have been 786 // substituted; we need to craft a new interface first. 787 if iface == orig.rhs() { 788 assert(iface.complete) // otherwise we are copying incomplete data 789 790 crafted := check.newInterface() 791 crafted.complete = true 792 crafted.implicit = false 793 crafted.embeddeds = iface.embeddeds 794 795 iface = crafted 796 } 797 iface.methods = methods 798 iface.tset = nil // recompute type set with new methods 799 800 // go.dev/issue/61561: We have to complete the interface even without a checker. 801 if check == nil { 802 iface.typeSet() 803 } 804 805 return iface 806 } 807 } 808 809 return rhs 810 } 811 812 // safeUnderlying returns the underlying type of typ without expanding 813 // instances, to avoid infinite recursion. 814 // 815 // TODO(rfindley): eliminate this function or give it a better name. 816 func safeUnderlying(typ Type) Type { 817 if t := asNamed(typ); t != nil { 818 return t.underlying 819 } 820 return typ.Underlying() 821 } 822