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 415 // method is the named type t. For an uninstantiated generic type t, each 416 // method receiver is instantiated with its receiver type parameters. 417 // 418 // Methods are numbered deterministically: given the same list of source files 419 // presented to the type checker, or the same sequence of NewMethod and AddMethod 420 // calls, the mapping from method index to corresponding method remains the same. 421 // But the specific ordering is not specified and must not be relied on as it may 422 // change in the future. 423 func (t *Named) Method(i int) *Func { 424 t.unpack() 425 426 if t.stateHas(hasMethods) { 427 return t.methods[i] 428 } 429 430 assert(t.inst != nil) // only instances should have unexpanded methods 431 orig := t.inst.orig 432 433 t.mu.Lock() 434 defer t.mu.Unlock() 435 436 if len(t.methods) != len(orig.methods) { 437 assert(len(t.methods) == 0) 438 t.methods = make([]*Func, len(orig.methods)) 439 } 440 441 if t.methods[i] == nil { 442 assert(t.inst.ctxt != nil) // we should still have a context remaining from the resolution phase 443 t.methods[i] = t.expandMethod(i) 444 t.inst.expandedMethods++ 445 446 // Check if we've created all methods at this point. If we have, mark the 447 // type as having all of its methods. 448 if t.inst.expandedMethods == len(orig.methods) { 449 t.setState(hasMethods) 450 t.inst.ctxt = nil // no need for a context anymore 451 } 452 } 453 454 return t.methods[i] 455 } 456 457 // expandMethod substitutes type arguments in the i'th method for an 458 // instantiated receiver. 459 func (t *Named) expandMethod(i int) *Func { 460 // t.orig.methods is not lazy. origm is the method instantiated with its 461 // receiver type parameters (the "origin" method). 462 origm := t.inst.orig.Method(i) 463 assert(origm != nil) 464 465 check := t.check 466 // Ensure that the original method is type-checked. 467 if check != nil { 468 check.objDecl(origm) 469 } 470 471 origSig := origm.typ.(*Signature) 472 rbase, _ := deref(origSig.Recv().Type()) 473 474 // If rbase is t, then origm is already the instantiated method we're looking 475 // for. In this case, we return origm to preserve the invariant that 476 // traversing Method->Receiver Type->Method should get back to the same 477 // method. 478 // 479 // This occurs if t is instantiated with the receiver type parameters, as in 480 // the use of m in func (r T[_]) m() { r.m() }. 481 if rbase == t { 482 return origm 483 } 484 485 sig := origSig 486 // We can only substitute if we have a correspondence between type arguments 487 // and type parameters. This check is necessary in the presence of invalid 488 // code. 489 if origSig.RecvTypeParams().Len() == t.inst.targs.Len() { 490 smap := makeSubstMap(origSig.RecvTypeParams().list(), t.inst.targs.list()) 491 var ctxt *Context 492 if check != nil { 493 ctxt = check.context() 494 } 495 sig = check.subst(origm.pos, origSig, smap, t, ctxt).(*Signature) 496 } 497 498 if sig == origSig { 499 // No substitution occurred, but we still need to create a new signature to 500 // hold the instantiated receiver. 501 copy := *origSig 502 sig = © 503 } 504 505 var rtyp Type 506 if origm.hasPtrRecv() { 507 rtyp = NewPointer(t) 508 } else { 509 rtyp = t 510 } 511 512 sig.recv = cloneVar(origSig.recv, rtyp) 513 return cloneFunc(origm, sig) 514 } 515 516 // SetUnderlying sets the underlying type and marks t as complete. 517 // t must not have type arguments. 518 func (t *Named) SetUnderlying(u Type) { 519 assert(t.inst == nil) 520 if u == nil { 521 panic("underlying type must not be nil") 522 } 523 if asNamed(u) != nil { 524 panic("underlying type must not be *Named") 525 } 526 // be careful to uphold the state invariants 527 t.mu.Lock() 528 defer t.mu.Unlock() 529 530 t.fromRHS = u 531 t.allowNilRHS = false 532 t.setState(lazyLoaded | unpacked | hasMethods) // TODO(markfreeman): Why hasMethods? 533 534 t.underlying = u 535 t.setState(hasUnder) 536 } 537 538 // AddMethod adds method m unless it is already in the method list. 539 // The method must be in the same package as t, and t must not have 540 // type arguments. 541 func (t *Named) AddMethod(m *Func) { 542 assert(samePkg(t.obj.pkg, m.pkg)) 543 assert(t.inst == nil) 544 t.unpack() 545 if t.methodIndex(m.name, false) < 0 { 546 t.methods = append(t.methods, m) 547 } 548 } 549 550 // methodIndex returns the index of the method with the given name. 551 // If foldCase is set, capitalization in the name is ignored. 552 // The result is negative if no such method exists. 553 func (t *Named) methodIndex(name string, foldCase bool) int { 554 if name == "_" { 555 return -1 556 } 557 if foldCase { 558 for i, m := range t.methods { 559 if strings.EqualFold(m.name, name) { 560 return i 561 } 562 } 563 } else { 564 for i, m := range t.methods { 565 if m.name == name { 566 return i 567 } 568 } 569 } 570 return -1 571 } 572 573 // rhs returns [Named.fromRHS]. 574 // 575 // In debug mode, it also asserts that n is in an appropriate state. 576 func (n *Named) rhs() Type { 577 if debug { 578 assert(n.stateHas(lazyLoaded | unpacked)) 579 } 580 return n.fromRHS 581 } 582 583 // Underlying returns the [underlying type] of the named type t, resolving all 584 // forwarding declarations. Underlying types are never Named, TypeParam, or 585 // Alias types. 586 // 587 // [underlying type]: https://go.dev/ref/spec#Underlying_types. 588 func (n *Named) Underlying() Type { 589 n.unpack() 590 591 // The gccimporter depends on writing a nil underlying via NewNamed and 592 // immediately reading it back. Rather than putting that in Named.under 593 // and complicating things there, we just check for that special case here. 594 if n.rhs() == nil { 595 assert(n.allowNilRHS) 596 return nil 597 } 598 599 if !n.stateHas(hasUnder) { // minor performance optimization 600 n.resolveUnderlying() 601 } 602 603 return n.underlying 604 } 605 606 func (t *Named) String() string { return TypeString(t, nil) } 607 608 // ---------------------------------------------------------------------------- 609 // Implementation 610 // 611 // TODO(rfindley): reorganize the loading and expansion methods under this 612 // heading. 613 614 // resolveUnderlying computes the underlying type of n. If n already has an 615 // underlying type, nothing happens. 616 // 617 // It does so by following RHS type chains for alias and named types. If any 618 // other type T is found, each named type in the chain has its underlying 619 // type set to T. Aliases are skipped because their underlying type is 620 // not memoized. 621 // 622 // resolveUnderlying assumes that there are no direct cycles; if there were 623 // any, they were broken (by setting the respective types to invalid) during 624 // the directCycles check phase. 625 func (n *Named) resolveUnderlying() { 626 assert(n.stateHas(unpacked)) 627 628 var seen map[*Named]bool // for debugging only 629 if debug { 630 seen = make(map[*Named]bool) 631 } 632 633 var path []*Named 634 var u Type 635 for rhs := Type(n); u == nil; { 636 switch t := rhs.(type) { 637 case *Alias: 638 rhs = unalias(t) 639 640 case *Named: 641 if debug { 642 assert(!seen[t]) 643 seen[t] = true 644 } 645 646 // don't recalculate the underlying 647 if t.stateHas(hasUnder) { 648 u = t.underlying 649 break 650 } 651 652 if debug { 653 seen[t] = true 654 } 655 path = append(path, t) 656 657 t.unpack() 658 rhs = t.rhs() 659 assert(rhs != nil) 660 661 default: 662 u = rhs // any type literal or predeclared type works 663 } 664 } 665 666 for _, t := range path { 667 func() { 668 t.mu.Lock() 669 defer t.mu.Unlock() 670 // Careful, t.underlying has lock-free readers. Since we might be racing 671 // another call to resolveUnderlying, we have to avoid overwriting 672 // t.underlying. Otherwise, the race detector will be tripped. 673 if !t.stateHas(hasUnder) { 674 t.underlying = u 675 t.setState(hasUnder) 676 } 677 }() 678 } 679 } 680 681 func (n *Named) lookupMethod(pkg *Package, name string, foldCase bool) (int, *Func) { 682 n.unpack() 683 if samePkg(n.obj.pkg, pkg) || isExported(name) || foldCase { 684 // If n is an instance, we may not have yet instantiated all of its methods. 685 // Look up the method index in orig, and only instantiate method at the 686 // matching index (if any). 687 if i := n.Origin().methodIndex(name, foldCase); i >= 0 { 688 // For instances, m.Method(i) will be different from the orig method. 689 return i, n.Method(i) 690 } 691 } 692 return -1, nil 693 } 694 695 // context returns the type-checker context. 696 func (check *Checker) context() *Context { 697 if check.ctxt == nil { 698 check.ctxt = NewContext() 699 } 700 return check.ctxt 701 } 702 703 // expandRHS crafts a synthetic RHS for an instantiated type using the RHS of 704 // its origin type (which must be a generic type). 705 // 706 // Suppose that we had: 707 // 708 // type T[P any] struct { 709 // f P 710 // } 711 // 712 // type U T[int] 713 // 714 // When we go to U, we observe T[int]. Since T[int] is an instantiation, it has no 715 // declaration. Here, we craft a synthetic RHS for T[int] as if it were declared, 716 // somewhat similar to: 717 // 718 // type T[int] struct { 719 // f int 720 // } 721 // 722 // And note that the synthetic RHS here is the same as the underlying for U. Now, 723 // consider: 724 // 725 // type T[_ any] U 726 // type U int 727 // type V T[U] 728 // 729 // The synthetic RHS for T[U] becomes: 730 // 731 // type T[U] U 732 // 733 // Whereas the underlying of V is int, not U. 734 func (n *Named) expandRHS() (rhs Type) { 735 check := n.check 736 if check != nil && check.conf._Trace { 737 check.trace(n.obj.pos, "-- Named.expandRHS %s", n) 738 check.indent++ 739 defer func() { 740 check.indent-- 741 check.trace(n.obj.pos, "=> %s (rhs = %s)", n, rhs) 742 }() 743 } 744 745 assert(!n.stateHas(unpacked)) 746 assert(n.inst.orig.stateHas(lazyLoaded | unpacked)) 747 748 if n.inst.ctxt == nil { 749 n.inst.ctxt = NewContext() 750 } 751 752 ctxt := n.inst.ctxt 753 orig := n.inst.orig 754 755 targs := n.inst.targs 756 tpars := orig.tparams 757 758 if targs.Len() != tpars.Len() { 759 return Typ[Invalid] 760 } 761 762 h := ctxt.instanceHash(orig, targs.list()) 763 u := ctxt.update(h, orig, targs.list(), n) // block fixed point infinite instantiation 764 assert(n == u) 765 766 m := makeSubstMap(tpars.list(), targs.list()) 767 if check != nil { 768 ctxt = check.context() 769 } 770 771 rhs = check.subst(n.obj.pos, orig.rhs(), m, n, ctxt) 772 773 // TODO(markfreeman): Can we handle this in substitution? 774 // If the RHS is an interface, we must set the receiver of interface methods 775 // to the named type. 776 if iface, _ := rhs.(*Interface); iface != nil { 777 if methods, copied := replaceRecvType(iface.methods, orig, n); copied { 778 // If the RHS doesn't use type parameters, it may not have been 779 // substituted; we need to craft a new interface first. 780 if iface == orig.rhs() { 781 assert(iface.complete) // otherwise we are copying incomplete data 782 783 crafted := check.newInterface() 784 crafted.complete = true 785 crafted.implicit = false 786 crafted.embeddeds = iface.embeddeds 787 788 iface = crafted 789 } 790 iface.methods = methods 791 iface.tset = nil // recompute type set with new methods 792 793 // go.dev/issue/61561: We have to complete the interface even without a checker. 794 if check == nil { 795 iface.typeSet() 796 } 797 798 return iface 799 } 800 } 801 802 return rhs 803 } 804 805 // safeUnderlying returns the underlying type of typ without expanding 806 // instances, to avoid infinite recursion. 807 // 808 // TODO(rfindley): eliminate this function or give it a better name. 809 func safeUnderlying(typ Type) Type { 810 if t := asNamed(typ); t != nil { 811 return t.underlying 812 } 813 return typ.Underlying() 814 } 815