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  	// flags indicating temporary violations of the invariants for fromRHS and underlying
   110  	allowNilRHS        bool // same as below, as well as briefly during checking of a type declaration
   111  	allowNilUnderlying bool // may be true from creation via [NewNamed] until [Named.SetUnderlying]
   112  
   113  	inst *instance // information for instantiated types; nil otherwise
   114  
   115  	mu         sync.Mutex     // guards all fields below
   116  	state_     uint32         // the current state of this type; must only be accessed atomically or when mu is held
   117  	fromRHS    Type           // the declaration RHS this type is derived from
   118  	tparams    *TypeParamList // type parameters, or nil
   119  	underlying Type           // underlying type, or nil
   120  	finite     bool           // whether the type has finite size
   121  
   122  	// methods declared for this type (not the method set of this type)
   123  	// Signatures are type-checked lazily.
   124  	// For non-instantiated types, this is a fully populated list of methods. For
   125  	// instantiated types, methods are individually expanded when they are first
   126  	// accessed.
   127  	methods []*Func
   128  
   129  	// loader may be provided to lazily load type parameters, underlying type, methods, and delayed functions
   130  	loader func(*Named) ([]*TypeParam, Type, []*Func, []func())
   131  }
   132  
   133  // instance holds information that is only necessary for instantiated named
   134  // types.
   135  type instance struct {
   136  	orig            *Named    // original, uninstantiated type
   137  	targs           *TypeList // type arguments
   138  	expandedMethods int       // number of expanded methods; expandedMethods <= len(orig.methods)
   139  	ctxt            *Context  // local Context; set to nil after full expansion
   140  }
   141  
   142  // stateMask represents each state in the lifecycle of a named type.
   143  //
   144  // Each named type begins in the initial state. A named type may transition to a new state
   145  // according to the below diagram:
   146  //
   147  //	initial
   148  //	lazyLoaded
   149  //	unpacked
   150  //	└── hasMethods
   151  //	└── hasUnder
   152  //	└── hasFinite
   153  //
   154  // That is, descent down the tree is mostly linear (initial through unpacked), except upon
   155  // reaching the leaves (hasMethods, hasUnder, and hasFinite). A type may occupy any
   156  // combination of the leaf states at once (they are independent states).
   157  //
   158  // To represent this independence, the set of active states is represented with a bit set. State
   159  // transitions are monotonic. Once a state bit is set, it remains set.
   160  //
   161  // The above constraints significantly narrow the possible bit sets for a named type. With bits
   162  // set left-to-right, they are:
   163  //
   164  //	00000 | initial
   165  //	10000 | lazyLoaded
   166  //	11000 | unpacked, which implies lazyLoaded
   167  //	11100 | hasMethods, which implies unpacked (which in turn implies lazyLoaded)
   168  //	11010 | hasUnder, which implies unpacked ...
   169  //	11001 | hasFinite, which implies unpacked ...
   170  //	11110 | both hasMethods and hasUnder which implies unpacked ...
   171  //	...   | (other combinations of leaf states)
   172  //
   173  // To read the state of a named type, use [Named.stateHas]; to write, use [Named.setState].
   174  type stateMask uint32
   175  
   176  const (
   177  	// initially, type parameters, RHS, underlying, and methods might be unavailable
   178  	lazyLoaded stateMask = 1 << iota // methods are available, but constraints might be unexpanded (for generic types)
   179  	unpacked                         // methods might be unexpanded (for instances)
   180  	hasMethods                       // methods are all expanded (for instances)
   181  	hasUnder                         // underlying type is available
   182  	hasFinite                        // size finiteness is available
   183  )
   184  
   185  // NewNamed returns a new named type for the given type name, underlying type, and associated methods.
   186  // If the given type name obj doesn't have a type yet, its type is set to the returned named type.
   187  // The underlying type must not be a *Named.
   188  func NewNamed(obj *TypeName, underlying Type, methods []*Func) *Named {
   189  	if asNamed(underlying) != nil {
   190  		panic("underlying type must not be *Named")
   191  	}
   192  	n := (*Checker)(nil).newNamed(obj, underlying, methods)
   193  	if underlying == nil {
   194  		n.allowNilRHS = true
   195  		n.allowNilUnderlying = 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  		// hasFinite => unpacked
   313  		if m&hasFinite != 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 syntax.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 = &copy
   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.allowNilUnderlying = false
   536  	t.setState(hasUnder)
   537  }
   538  
   539  // AddMethod adds method m unless it is already in the method list.
   540  // The method must be in the same package as t, and t must not have
   541  // type arguments.
   542  func (t *Named) AddMethod(m *Func) {
   543  	assert(samePkg(t.obj.pkg, m.pkg))
   544  	assert(t.inst == nil)
   545  	t.unpack()
   546  	if t.methodIndex(m.name, false) < 0 {
   547  		t.methods = append(t.methods, m)
   548  	}
   549  }
   550  
   551  // methodIndex returns the index of the method with the given name.
   552  // If foldCase is set, capitalization in the name is ignored.
   553  // The result is negative if no such method exists.
   554  func (t *Named) methodIndex(name string, foldCase bool) int {
   555  	if name == "_" {
   556  		return -1
   557  	}
   558  	if foldCase {
   559  		for i, m := range t.methods {
   560  			if strings.EqualFold(m.name, name) {
   561  				return i
   562  			}
   563  		}
   564  	} else {
   565  		for i, m := range t.methods {
   566  			if m.name == name {
   567  				return i
   568  			}
   569  		}
   570  	}
   571  	return -1
   572  }
   573  
   574  // rhs returns [Named.fromRHS].
   575  //
   576  // In debug mode, it also asserts that n is in an appropriate state.
   577  func (n *Named) rhs() Type {
   578  	if debug {
   579  		assert(n.stateHas(lazyLoaded | unpacked))
   580  	}
   581  	return n.fromRHS
   582  }
   583  
   584  // Underlying returns the [underlying type] of the named type t, resolving all
   585  // forwarding declarations. Underlying types are never Named, TypeParam, or
   586  // Alias types.
   587  //
   588  // [underlying type]: https://go.dev/ref/spec#Underlying_types.
   589  func (n *Named) Underlying() Type {
   590  	n.unpack()
   591  
   592  	// The gccimporter depends on writing a nil underlying via NewNamed and
   593  	// immediately reading it back. Rather than putting that in Named.under
   594  	// and complicating things there, we just check for that special case here.
   595  	if n.rhs() == nil {
   596  		assert(n.allowNilRHS)
   597  		if n.allowNilUnderlying {
   598  			return nil
   599  		}
   600  	}
   601  
   602  	if !n.stateHas(hasUnder) { // minor performance optimization
   603  		n.resolveUnderlying()
   604  	}
   605  
   606  	return n.underlying
   607  }
   608  
   609  func (t *Named) String() string { return TypeString(t, nil) }
   610  
   611  // ----------------------------------------------------------------------------
   612  // Implementation
   613  //
   614  // TODO(rfindley): reorganize the loading and expansion methods under this
   615  // heading.
   616  
   617  // resolveUnderlying computes the underlying type of n. If n already has an
   618  // underlying type, nothing happens.
   619  //
   620  // It does so by following RHS type chains for alias and named types. If any
   621  // other type T is found, each named type in the chain has its underlying
   622  // type set to T. Aliases are skipped because their underlying type is
   623  // not memoized.
   624  //
   625  // resolveUnderlying assumes that there are no direct cycles; if there were
   626  // any, they were broken (by setting the respective types to invalid) during
   627  // the directCycles check phase.
   628  func (n *Named) resolveUnderlying() {
   629  	assert(n.stateHas(unpacked))
   630  
   631  	var seen map[*Named]bool // for debugging only
   632  	if debug {
   633  		seen = make(map[*Named]bool)
   634  	}
   635  
   636  	var path []*Named
   637  	var u Type
   638  	for rhs := Type(n); u == nil; {
   639  		switch t := rhs.(type) {
   640  		case nil:
   641  			u = Typ[Invalid]
   642  
   643  		case *Alias:
   644  			rhs = unalias(t)
   645  
   646  		case *Named:
   647  			if debug {
   648  				assert(!seen[t])
   649  				seen[t] = true
   650  			}
   651  
   652  			// don't recalculate the underlying
   653  			if t.stateHas(hasUnder) {
   654  				u = t.underlying
   655  				break
   656  			}
   657  
   658  			if debug {
   659  				seen[t] = true
   660  			}
   661  			path = append(path, t)
   662  
   663  			t.unpack()
   664  			assert(t.rhs() != nil || t.allowNilRHS)
   665  			rhs = t.rhs()
   666  
   667  		default:
   668  			u = rhs // any type literal or predeclared type works
   669  		}
   670  	}
   671  
   672  	for _, t := range path {
   673  		func() {
   674  			t.mu.Lock()
   675  			defer t.mu.Unlock()
   676  			// Careful, t.underlying has lock-free readers. Since we might be racing
   677  			// another call to resolveUnderlying, we have to avoid overwriting
   678  			// t.underlying. Otherwise, the race detector will be tripped.
   679  			if !t.stateHas(hasUnder) {
   680  				t.underlying = u
   681  				t.setState(hasUnder)
   682  			}
   683  		}()
   684  	}
   685  }
   686  
   687  func (n *Named) lookupMethod(pkg *Package, name string, foldCase bool) (int, *Func) {
   688  	n.unpack()
   689  	if samePkg(n.obj.pkg, pkg) || isExported(name) || foldCase {
   690  		// If n is an instance, we may not have yet instantiated all of its methods.
   691  		// Look up the method index in orig, and only instantiate method at the
   692  		// matching index (if any).
   693  		if i := n.Origin().methodIndex(name, foldCase); i >= 0 {
   694  			// For instances, m.Method(i) will be different from the orig method.
   695  			return i, n.Method(i)
   696  		}
   697  	}
   698  	return -1, nil
   699  }
   700  
   701  // context returns the type-checker context.
   702  func (check *Checker) context() *Context {
   703  	if check.ctxt == nil {
   704  		check.ctxt = NewContext()
   705  	}
   706  	return check.ctxt
   707  }
   708  
   709  // expandRHS crafts a synthetic RHS for an instantiated type using the RHS of
   710  // its origin type (which must be a generic type).
   711  //
   712  // Suppose that we had:
   713  //
   714  //	type T[P any] struct {
   715  //	  f P
   716  //	}
   717  //
   718  //	type U T[int]
   719  //
   720  // When we go to U, we observe T[int]. Since T[int] is an instantiation, it has no
   721  // declaration. Here, we craft a synthetic RHS for T[int] as if it were declared,
   722  // somewhat similar to:
   723  //
   724  //	type T[int] struct {
   725  //	  f int
   726  //	}
   727  //
   728  // And note that the synthetic RHS here is the same as the underlying for U. Now,
   729  // consider:
   730  //
   731  //	type T[_ any] U
   732  //	type U int
   733  //	type V T[U]
   734  //
   735  // The synthetic RHS for T[U] becomes:
   736  //
   737  //	type T[U] U
   738  //
   739  // Whereas the underlying of V is int, not U.
   740  func (n *Named) expandRHS() (rhs Type) {
   741  	check := n.check
   742  	if check != nil && check.conf.Trace {
   743  		check.trace(n.obj.pos, "-- Named.expandRHS %s", n)
   744  		check.indent++
   745  		defer func() {
   746  			check.indent--
   747  			check.trace(n.obj.pos, "=> %s (rhs = %s)", n, rhs)
   748  		}()
   749  	}
   750  
   751  	assert(!n.stateHas(unpacked))
   752  	assert(n.inst.orig.stateHas(lazyLoaded | unpacked))
   753  
   754  	if n.inst.ctxt == nil {
   755  		n.inst.ctxt = NewContext()
   756  	}
   757  
   758  	ctxt := n.inst.ctxt
   759  	orig := n.inst.orig
   760  
   761  	targs := n.inst.targs
   762  	tpars := orig.tparams
   763  
   764  	if targs.Len() != tpars.Len() {
   765  		return Typ[Invalid]
   766  	}
   767  
   768  	h := ctxt.instanceHash(orig, targs.list())
   769  	u := ctxt.update(h, orig, targs.list(), n) // block fixed point infinite instantiation
   770  	assert(n == u)
   771  
   772  	m := makeSubstMap(tpars.list(), targs.list())
   773  	if check != nil {
   774  		ctxt = check.context()
   775  	}
   776  
   777  	rhs = check.subst(n.obj.pos, orig.rhs(), m, n, ctxt)
   778  
   779  	// TODO(markfreeman): Can we handle this in substitution?
   780  	// If the RHS is an interface, we must set the receiver of interface methods
   781  	// to the named type.
   782  	if iface, _ := rhs.(*Interface); iface != nil {
   783  		if methods, copied := replaceRecvType(iface.methods, orig, n); copied {
   784  			// If the RHS doesn't use type parameters, it may not have been
   785  			// substituted; we need to craft a new interface first.
   786  			if iface == orig.rhs() {
   787  				assert(iface.complete) // otherwise we are copying incomplete data
   788  
   789  				crafted := check.newInterface()
   790  				crafted.complete = true
   791  				crafted.implicit = false
   792  				crafted.embeddeds = iface.embeddeds
   793  
   794  				iface = crafted
   795  			}
   796  			iface.methods = methods
   797  			iface.tset = nil // recompute type set with new methods
   798  
   799  			// go.dev/issue/61561: We have to complete the interface even without a checker.
   800  			if check == nil {
   801  				iface.typeSet()
   802  			}
   803  
   804  			return iface
   805  		}
   806  	}
   807  
   808  	return rhs
   809  }
   810  
   811  // safeUnderlying returns the underlying type of typ without expanding
   812  // instances, to avoid infinite recursion.
   813  //
   814  // TODO(rfindley): eliminate this function or give it a better name.
   815  func safeUnderlying(typ Type) Type {
   816  	if t := asNamed(typ); t != nil {
   817  		return t.underlying
   818  	}
   819  	return typ.Underlying()
   820  }
   821  

View as plain text