Source file src/cmd/compile/internal/types2/named.go

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

View as plain text