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

View as plain text