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  	finite     bool           // whether the type has finite size
   124  
   125  	// methods declared for this type (not the method set of this type)
   126  	// Signatures are type-checked lazily.
   127  	// For non-instantiated types, this is a fully populated list of methods. For
   128  	// instantiated types, methods are individually expanded when they are first
   129  	// accessed.
   130  	methods []*Func
   131  
   132  	// loader may be provided to lazily load type parameters, underlying type, methods, and delayed functions
   133  	loader func(*Named) ([]*TypeParam, Type, []*Func, []func())
   134  }
   135  
   136  // instance holds information that is only necessary for instantiated named
   137  // types.
   138  type instance struct {
   139  	orig            *Named    // original, uninstantiated type
   140  	targs           *TypeList // type arguments
   141  	expandedMethods int       // number of expanded methods; expandedMethods <= len(orig.methods)
   142  	ctxt            *Context  // local Context; set to nil after full expansion
   143  }
   144  
   145  // stateMask represents each state in the lifecycle of a named type.
   146  //
   147  // Each named type begins in the initial state. A named type may transition to a new state
   148  // according to the below diagram:
   149  //
   150  //	initial
   151  //	lazyLoaded
   152  //	unpacked
   153  //	└── hasMethods
   154  //	└── hasUnder
   155  //	└── hasFinite
   156  //
   157  // That is, descent down the tree is mostly linear (initial through unpacked), except upon
   158  // reaching the leaves (hasMethods, hasUnder, and hasFinite). A type may occupy any
   159  // combination of the leaf states at once (they are independent states).
   160  //
   161  // To represent this independence, the set of active states is represented with a bit set. State
   162  // transitions are monotonic. Once a state bit is set, it remains set.
   163  //
   164  // The above constraints significantly narrow the possible bit sets for a named type. With bits
   165  // set left-to-right, they are:
   166  //
   167  //	00000 | initial
   168  //	10000 | lazyLoaded
   169  //	11000 | unpacked, which implies lazyLoaded
   170  //	11100 | hasMethods, which implies unpacked (which in turn implies lazyLoaded)
   171  //	11010 | hasUnder, which implies unpacked ...
   172  //	11001 | hasFinite, which implies unpacked ...
   173  //	11110 | both hasMethods and hasUnder which implies unpacked ...
   174  //	...   | (other combinations of leaf states)
   175  //
   176  // To read the state of a named type, use [Named.stateHas]; to write, use [Named.setState].
   177  type stateMask uint32
   178  
   179  const (
   180  	// initially, type parameters, RHS, underlying, and methods might be unavailable
   181  	lazyLoaded stateMask = 1 << iota // methods are available, but constraints might be unexpanded (for generic types)
   182  	unpacked                         // methods might be unexpanded (for instances)
   183  	hasMethods                       // methods are all expanded (for instances)
   184  	hasUnder                         // underlying type is available
   185  	hasFinite                        // size finiteness is available
   186  )
   187  
   188  // NewNamed returns a new named type for the given type name, underlying type, and associated methods.
   189  // If the given type name obj doesn't have a type yet, its type is set to the returned named type.
   190  // The underlying type must not be a *Named.
   191  func NewNamed(obj *TypeName, underlying Type, methods []*Func) *Named {
   192  	if asNamed(underlying) != nil {
   193  		panic("underlying type must not be *Named")
   194  	}
   195  	n := (*Checker)(nil).newNamed(obj, underlying, methods)
   196  	if underlying == nil {
   197  		n.allowNilRHS = true
   198  		n.allowNilUnderlying = true
   199  	} else {
   200  		n.SetUnderlying(underlying)
   201  	}
   202  	return n
   203  
   204  }
   205  
   206  // unpack populates the type parameters, methods, and RHS of n.
   207  //
   208  // For the purposes of unpacking, there are three categories of named types:
   209  //  1. Lazy loaded types
   210  //  2. Instantiated types
   211  //  3. All others
   212  //
   213  // Note that the above form a partition.
   214  //
   215  // Lazy loaded types:
   216  // Type parameters, methods, and RHS of n become accessible and are fully
   217  // expanded.
   218  //
   219  // Instantiated types:
   220  // Type parameters, methods, and RHS of n become accessible, though methods
   221  // are lazily populated as needed.
   222  //
   223  // All others:
   224  // Effectively, nothing happens.
   225  func (n *Named) unpack() *Named {
   226  	if n.stateHas(lazyLoaded | unpacked) { // avoid locking below
   227  		return n
   228  	}
   229  
   230  	// TODO(rfindley): if n.check is non-nil we can avoid locking here, since
   231  	// type-checking is not concurrent. Evaluate if this is worth doing.
   232  	n.mu.Lock()
   233  	defer n.mu.Unlock()
   234  
   235  	// only atomic for consistency; we are holding the mutex
   236  	if n.stateHas(lazyLoaded | unpacked) {
   237  		return n
   238  	}
   239  
   240  	// underlying comes after unpacking, do not set it
   241  	defer (func() { assert(!n.stateHas(hasUnder)) })()
   242  
   243  	if n.inst != nil {
   244  		assert(n.fromRHS == nil) // instantiated types are not declared types
   245  		assert(n.loader == nil)  // cannot import an instantiation
   246  
   247  		orig := n.inst.orig
   248  		orig.unpack()
   249  
   250  		n.fromRHS = n.expandRHS()
   251  		n.tparams = orig.tparams
   252  
   253  		if len(orig.methods) == 0 {
   254  			n.setState(lazyLoaded | unpacked | hasMethods) // nothing further to do
   255  			n.inst.ctxt = nil
   256  		} else {
   257  			n.setState(lazyLoaded | unpacked)
   258  		}
   259  		return n
   260  	}
   261  
   262  	// TODO(mdempsky): Since we're passing n to the loader anyway
   263  	// (necessary because types2 expects the receiver type for methods
   264  	// on defined interface types to be the Named rather than the
   265  	// underlying Interface), maybe it should just handle calling
   266  	// SetTypeParams, SetUnderlying, and AddMethod instead?  Those
   267  	// methods would need to support reentrant calls though. It would
   268  	// also make the API more future-proof towards further extensions.
   269  	if n.loader != nil {
   270  		assert(n.fromRHS == nil) // not loaded yet
   271  		assert(n.inst == nil)    // cannot import an instantiation
   272  
   273  		tparams, underlying, methods, delayed := n.loader(n)
   274  		n.loader = nil
   275  
   276  		n.tparams = bindTParams(tparams)
   277  		n.fromRHS = underlying // for cycle detection
   278  		n.methods = methods
   279  
   280  		n.setState(lazyLoaded) // avoid deadlock calling delayed functions
   281  		for _, f := range delayed {
   282  			f()
   283  		}
   284  	}
   285  
   286  	n.setState(lazyLoaded | unpacked | hasMethods)
   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  		// hasFinite => unpacked
   316  		if m&hasFinite != 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 token.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
   418  // method is the named type t. For an uninstantiated generic type t, each
   419  // method receiver is instantiated with its receiver type parameters.
   420  //
   421  // Methods are numbered deterministically: given the same list of source files
   422  // presented to the type checker, or the same sequence of NewMethod and AddMethod
   423  // calls, the mapping from method index to corresponding method remains the same.
   424  // But the specific ordering is not specified and must not be relied on as it may
   425  // change in the future.
   426  func (t *Named) Method(i int) *Func {
   427  	t.unpack()
   428  
   429  	if t.stateHas(hasMethods) {
   430  		return t.methods[i]
   431  	}
   432  
   433  	assert(t.inst != nil) // only instances should have unexpanded methods
   434  	orig := t.inst.orig
   435  
   436  	t.mu.Lock()
   437  	defer t.mu.Unlock()
   438  
   439  	if len(t.methods) != len(orig.methods) {
   440  		assert(len(t.methods) == 0)
   441  		t.methods = make([]*Func, len(orig.methods))
   442  	}
   443  
   444  	if t.methods[i] == nil {
   445  		assert(t.inst.ctxt != nil) // we should still have a context remaining from the resolution phase
   446  		t.methods[i] = t.expandMethod(i)
   447  		t.inst.expandedMethods++
   448  
   449  		// Check if we've created all methods at this point. If we have, mark the
   450  		// type as having all of its methods.
   451  		if t.inst.expandedMethods == len(orig.methods) {
   452  			t.setState(hasMethods)
   453  			t.inst.ctxt = nil // no need for a context anymore
   454  		}
   455  	}
   456  
   457  	return t.methods[i]
   458  }
   459  
   460  // expandMethod substitutes type arguments in the i'th method for an
   461  // instantiated receiver.
   462  func (t *Named) expandMethod(i int) *Func {
   463  	// t.orig.methods is not lazy. origm is the method instantiated with its
   464  	// receiver type parameters (the "origin" method).
   465  	origm := t.inst.orig.Method(i)
   466  	assert(origm != nil)
   467  
   468  	check := t.check
   469  	// Ensure that the original method is type-checked.
   470  	if check != nil {
   471  		check.objDecl(origm)
   472  	}
   473  
   474  	origSig := origm.typ.(*Signature)
   475  	rbase, _ := deref(origSig.Recv().Type())
   476  
   477  	// If rbase is t, then origm is already the instantiated method we're looking
   478  	// for. In this case, we return origm to preserve the invariant that
   479  	// traversing Method->Receiver Type->Method should get back to the same
   480  	// method.
   481  	//
   482  	// This occurs if t is instantiated with the receiver type parameters, as in
   483  	// the use of m in func (r T[_]) m() { r.m() }.
   484  	if rbase == t {
   485  		return origm
   486  	}
   487  
   488  	sig := origSig
   489  	// We can only substitute if we have a correspondence between type arguments
   490  	// and type parameters. This check is necessary in the presence of invalid
   491  	// code.
   492  	if origSig.RecvTypeParams().Len() == t.inst.targs.Len() {
   493  		smap := makeSubstMap(origSig.RecvTypeParams().list(), t.inst.targs.list())
   494  		var ctxt *Context
   495  		if check != nil {
   496  			ctxt = check.context()
   497  		}
   498  		sig = check.subst(origm.pos, origSig, smap, t, ctxt).(*Signature)
   499  	}
   500  
   501  	if sig == origSig {
   502  		// No substitution occurred, but we still need to create a new signature to
   503  		// hold the instantiated receiver.
   504  		copy := *origSig
   505  		sig = &copy
   506  	}
   507  
   508  	var rtyp Type
   509  	if origm.hasPtrRecv() {
   510  		rtyp = NewPointer(t)
   511  	} else {
   512  		rtyp = t
   513  	}
   514  
   515  	sig.recv = cloneVar(origSig.recv, rtyp)
   516  	return cloneFunc(origm, sig)
   517  }
   518  
   519  // SetUnderlying sets the underlying type and marks t as complete.
   520  // t must not have type arguments.
   521  func (t *Named) SetUnderlying(u Type) {
   522  	assert(t.inst == nil)
   523  	if u == nil {
   524  		panic("underlying type must not be nil")
   525  	}
   526  	if asNamed(u) != nil {
   527  		panic("underlying type must not be *Named")
   528  	}
   529  	// be careful to uphold the state invariants
   530  	t.mu.Lock()
   531  	defer t.mu.Unlock()
   532  
   533  	t.fromRHS = u
   534  	t.allowNilRHS = false
   535  	t.setState(lazyLoaded | unpacked | hasMethods) // TODO(markfreeman): Why hasMethods?
   536  
   537  	t.underlying = u
   538  	t.allowNilUnderlying = false
   539  	t.setState(hasUnder)
   540  }
   541  
   542  // AddMethod adds method m unless it is already in the method list.
   543  // The method must be in the same package as t, and t must not have
   544  // type arguments.
   545  func (t *Named) AddMethod(m *Func) {
   546  	assert(samePkg(t.obj.pkg, m.pkg))
   547  	assert(t.inst == nil)
   548  	t.unpack()
   549  	if t.methodIndex(m.name, false) < 0 {
   550  		t.methods = append(t.methods, m)
   551  	}
   552  }
   553  
   554  // methodIndex returns the index of the method with the given name.
   555  // If foldCase is set, capitalization in the name is ignored.
   556  // The result is negative if no such method exists.
   557  func (t *Named) methodIndex(name string, foldCase bool) int {
   558  	if name == "_" {
   559  		return -1
   560  	}
   561  	if foldCase {
   562  		for i, m := range t.methods {
   563  			if strings.EqualFold(m.name, name) {
   564  				return i
   565  			}
   566  		}
   567  	} else {
   568  		for i, m := range t.methods {
   569  			if m.name == name {
   570  				return i
   571  			}
   572  		}
   573  	}
   574  	return -1
   575  }
   576  
   577  // rhs returns [Named.fromRHS].
   578  //
   579  // In debug mode, it also asserts that n is in an appropriate state.
   580  func (n *Named) rhs() Type {
   581  	if debug {
   582  		assert(n.stateHas(lazyLoaded | unpacked))
   583  	}
   584  	return n.fromRHS
   585  }
   586  
   587  // Underlying returns the [underlying type] of the named type t, resolving all
   588  // forwarding declarations. Underlying types are never Named, TypeParam, or
   589  // Alias types.
   590  //
   591  // [underlying type]: https://go.dev/ref/spec#Underlying_types.
   592  func (n *Named) Underlying() Type {
   593  	n.unpack()
   594  
   595  	// The gccimporter depends on writing a nil underlying via NewNamed and
   596  	// immediately reading it back. Rather than putting that in Named.under
   597  	// and complicating things there, we just check for that special case here.
   598  	if n.rhs() == nil {
   599  		assert(n.allowNilRHS)
   600  		if n.allowNilUnderlying {
   601  			return nil
   602  		}
   603  	}
   604  
   605  	if !n.stateHas(hasUnder) { // minor performance optimization
   606  		n.resolveUnderlying()
   607  	}
   608  
   609  	return n.underlying
   610  }
   611  
   612  func (t *Named) String() string { return TypeString(t, nil) }
   613  
   614  // ----------------------------------------------------------------------------
   615  // Implementation
   616  //
   617  // TODO(rfindley): reorganize the loading and expansion methods under this
   618  // heading.
   619  
   620  // resolveUnderlying computes the underlying type of n. If n already has an
   621  // underlying type, nothing happens.
   622  //
   623  // It does so by following RHS type chains for alias and named types. If any
   624  // other type T is found, each named type in the chain has its underlying
   625  // type set to T. Aliases are skipped because their underlying type is
   626  // not memoized.
   627  //
   628  // resolveUnderlying assumes that there are no direct cycles; if there were
   629  // any, they were broken (by setting the respective types to invalid) during
   630  // the directCycles check phase.
   631  func (n *Named) resolveUnderlying() {
   632  	assert(n.stateHas(unpacked))
   633  
   634  	var seen map[*Named]bool // for debugging only
   635  	if debug {
   636  		seen = make(map[*Named]bool)
   637  	}
   638  
   639  	var path []*Named
   640  	var u Type
   641  	for rhs := Type(n); u == nil; {
   642  		switch t := rhs.(type) {
   643  		case nil:
   644  			u = Typ[Invalid]
   645  
   646  		case *Alias:
   647  			rhs = unalias(t)
   648  
   649  		case *Named:
   650  			if debug {
   651  				assert(!seen[t])
   652  				seen[t] = true
   653  			}
   654  
   655  			// don't recalculate the underlying
   656  			if t.stateHas(hasUnder) {
   657  				u = t.underlying
   658  				break
   659  			}
   660  
   661  			if debug {
   662  				seen[t] = true
   663  			}
   664  			path = append(path, t)
   665  
   666  			t.unpack()
   667  			assert(t.rhs() != nil || t.allowNilRHS)
   668  			rhs = t.rhs()
   669  
   670  		default:
   671  			u = rhs // any type literal or predeclared type works
   672  		}
   673  	}
   674  
   675  	for _, t := range path {
   676  		func() {
   677  			t.mu.Lock()
   678  			defer t.mu.Unlock()
   679  			// Careful, t.underlying has lock-free readers. Since we might be racing
   680  			// another call to resolveUnderlying, we have to avoid overwriting
   681  			// t.underlying. Otherwise, the race detector will be tripped.
   682  			if !t.stateHas(hasUnder) {
   683  				t.underlying = u
   684  				t.setState(hasUnder)
   685  			}
   686  		}()
   687  	}
   688  }
   689  
   690  func (n *Named) lookupMethod(pkg *Package, name string, foldCase bool) (int, *Func) {
   691  	n.unpack()
   692  	if samePkg(n.obj.pkg, pkg) || isExported(name) || foldCase {
   693  		// If n is an instance, we may not have yet instantiated all of its methods.
   694  		// Look up the method index in orig, and only instantiate method at the
   695  		// matching index (if any).
   696  		if i := n.Origin().methodIndex(name, foldCase); i >= 0 {
   697  			// For instances, m.Method(i) will be different from the orig method.
   698  			return i, n.Method(i)
   699  		}
   700  	}
   701  	return -1, nil
   702  }
   703  
   704  // context returns the type-checker context.
   705  func (check *Checker) context() *Context {
   706  	if check.ctxt == nil {
   707  		check.ctxt = NewContext()
   708  	}
   709  	return check.ctxt
   710  }
   711  
   712  // expandRHS crafts a synthetic RHS for an instantiated type using the RHS of
   713  // its origin type (which must be a generic type).
   714  //
   715  // Suppose that we had:
   716  //
   717  //	type T[P any] struct {
   718  //	  f P
   719  //	}
   720  //
   721  //	type U T[int]
   722  //
   723  // When we go to U, we observe T[int]. Since T[int] is an instantiation, it has no
   724  // declaration. Here, we craft a synthetic RHS for T[int] as if it were declared,
   725  // somewhat similar to:
   726  //
   727  //	type T[int] struct {
   728  //	  f int
   729  //	}
   730  //
   731  // And note that the synthetic RHS here is the same as the underlying for U. Now,
   732  // consider:
   733  //
   734  //	type T[_ any] U
   735  //	type U int
   736  //	type V T[U]
   737  //
   738  // The synthetic RHS for T[U] becomes:
   739  //
   740  //	type T[U] U
   741  //
   742  // Whereas the underlying of V is int, not U.
   743  func (n *Named) expandRHS() (rhs Type) {
   744  	check := n.check
   745  	if check != nil && check.conf._Trace {
   746  		check.trace(n.obj.pos, "-- Named.expandRHS %s", n)
   747  		check.indent++
   748  		defer func() {
   749  			check.indent--
   750  			check.trace(n.obj.pos, "=> %s (rhs = %s)", n, rhs)
   751  		}()
   752  	}
   753  
   754  	assert(!n.stateHas(unpacked))
   755  	assert(n.inst.orig.stateHas(lazyLoaded | unpacked))
   756  
   757  	if n.inst.ctxt == nil {
   758  		n.inst.ctxt = NewContext()
   759  	}
   760  
   761  	ctxt := n.inst.ctxt
   762  	orig := n.inst.orig
   763  
   764  	targs := n.inst.targs
   765  	tpars := orig.tparams
   766  
   767  	if targs.Len() != tpars.Len() {
   768  		return Typ[Invalid]
   769  	}
   770  
   771  	h := ctxt.instanceHash(orig, targs.list())
   772  	u := ctxt.update(h, orig, targs.list(), n) // block fixed point infinite instantiation
   773  	assert(n == u)
   774  
   775  	m := makeSubstMap(tpars.list(), targs.list())
   776  	if check != nil {
   777  		ctxt = check.context()
   778  	}
   779  
   780  	rhs = check.subst(n.obj.pos, orig.rhs(), m, n, ctxt)
   781  
   782  	// TODO(markfreeman): Can we handle this in substitution?
   783  	// If the RHS is an interface, we must set the receiver of interface methods
   784  	// to the named type.
   785  	if iface, _ := rhs.(*Interface); iface != nil {
   786  		if methods, copied := replaceRecvType(iface.methods, orig, n); copied {
   787  			// If the RHS doesn't use type parameters, it may not have been
   788  			// substituted; we need to craft a new interface first.
   789  			if iface == orig.rhs() {
   790  				assert(iface.complete) // otherwise we are copying incomplete data
   791  
   792  				crafted := check.newInterface()
   793  				crafted.complete = true
   794  				crafted.implicit = false
   795  				crafted.embeddeds = iface.embeddeds
   796  
   797  				iface = crafted
   798  			}
   799  			iface.methods = methods
   800  			iface.tset = nil // recompute type set with new methods
   801  
   802  			// go.dev/issue/61561: We have to complete the interface even without a checker.
   803  			if check == nil {
   804  				iface.typeSet()
   805  			}
   806  
   807  			return iface
   808  		}
   809  	}
   810  
   811  	return rhs
   812  }
   813  
   814  // safeUnderlying returns the underlying type of typ without expanding
   815  // instances, to avoid infinite recursion.
   816  //
   817  // TODO(rfindley): eliminate this function or give it a better name.
   818  func safeUnderlying(typ Type) Type {
   819  	if t := asNamed(typ); t != nil {
   820  		return t.underlying
   821  	}
   822  	return typ.Underlying()
   823  }
   824  

View as plain text