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

View as plain text